internal static void RenderProperties(IEnumerable<Sentence> properties, FormattingOptions options, StringBuilder iniBuilder) { foreach (var property in properties) { var comments = property.Comments(); RenderComments(comments, options, iniBuilder); iniBuilder.AppendLine(); iniBuilder.Append(property.Tokens.PropertyToken()); if (options.HasFlag(FormattingOptions.SpaceBeforePropertyValueDelimiter)) { iniBuilder.Append(Grammar.Space); } iniBuilder.Append(property.Tokens.PropertyValueDelimiterToken()); if (options.HasFlag(FormattingOptions.SpaceAfterPropertyValueDelimiter)) { iniBuilder.Append(Grammar.Space); } iniBuilder.Append(property.Tokens.ValueToken()); } }
public static string Render(Sentence globalSection, FormattingOptions options = FormattingOptions.None) { var iniBuilder = new StringBuilder(); foreach (var section in globalSection.After.Sections()) { RenderSectionContents(section, options, iniBuilder); } var ini = iniBuilder.ToString(); return ini; }
internal static void RenderSection(Sentence section, FormattingOptions options, StringBuilder iniBuilder) { if (iniBuilder.Length > 0) { iniBuilder.AppendLine(); } iniBuilder .Append(section.Tokens[0]) .Append(section.Tokens[1]) .Append(section.Tokens[2]); }
internal static void RenderComments(IEnumerable<Sentence> comments, FormattingOptions options, StringBuilder iniBuilder) { foreach (var comment in comments) { iniBuilder.Append(comment.Tokens.CommentIndicaotrToken()); if (options.HasFlag(FormattingOptions.SpaceAfterCommentIndicator)) { iniBuilder.Append(Grammar.Space); } iniBuilder.AppendLine(comment.Tokens.CommentToken()); } }
internal static void RenderSectionContents(Sentence section, FormattingOptions options, StringBuilder iniBuilder) { if (options.HasFlag(FormattingOptions.BlankLineBeforeSection)) { iniBuilder.AppendLine(); } if (section.SectionToken() != Grammar.GlobalSectionName) { RenderComments(section.Comments(), options, iniBuilder); RenderSection(section, options, iniBuilder); } RenderProperties(section.Properties(), options, iniBuilder); }
public string Format(Signal signal, FormattingOptions options) { LinkedList<string> sequence = new LinkedList<string>(); sequence.AddFirst("sentinel"); FormatExpression(signal, sequence, options); sequence.RemoveFirst(); StringBuilder sb = new StringBuilder(8 * sequence.Count); // heuristics foreach(string token in sequence) sb.Append(token); //sb.Replace("+-", "-"); //sb.Replace("--", "+"); return sb.ToString(); }
/// <summary> /// Write human readable output. /// </summary> public override void WriteTo(ITextOutput output, FormattingOptions format) { if (Values != null) { foreach (var i in Values) { output.WriteLine("case {0}:", i); } } else { output.WriteLine("default:"); } output.Indent(); base.WriteTo(output, format); output.Unindent(); }
private string TrimPunctuationAndQuotationMarks( string s, FormattingOptions formattingOptions) { if (formattingOptions.TrimQuotes) { s = TrimQuotes(s); } if (formattingOptions.TrimPunctuation) { var punctChars = s.Where(char.IsPunctuation).ToArray(); s = s.Trim(punctChars); } return(s); }
public override async Task <TextEdit[]> ApplyFormattedEditsAsync( DocumentUri uri, DocumentSnapshot documentSnapshot, RazorLanguageKind kind, TextEdit[] formattedEdits, FormattingOptions options, CancellationToken cancellationToken, bool bypassValidationPasses = false, bool collapseEdits = false) { if (kind == RazorLanguageKind.Html) { // We don't support formatting HTML edits yet. return(formattedEdits); } // If we only received a single edit, let's always return a single edit back. // Otherwise, merge only if explicitly asked. collapseEdits |= formattedEdits.Length == 1; var codeDocument = await documentSnapshot.GetGeneratedOutputAsync(); using var context = FormattingContext.Create(uri, documentSnapshot, codeDocument, options, isFormatOnType: true); var result = new FormattingResult(formattedEdits, kind); foreach (var pass in _formattingPasses) { if (pass.IsValidationPass && bypassValidationPasses) { continue; } cancellationToken.ThrowIfCancellationRequested(); result = await pass.ExecuteAsync(context, result, cancellationToken); } var edits = result.Edits; if (collapseEdits) { var collapsedEdit = MergeEdits(result.Edits, context.SourceText); edits = new[] { collapsedEdit }; } return(edits); }
public async Task ElseBlockTwoSpaceNoEdits(int line, int col) { var position = new Position { line = line, character = col }; var options = new FormattingOptions { insertSpaces = true, tabSize = 2 }; var src = TestData.GetPath("TestData", "Formatting", "elseBlocks2.py"); using (var reader = new StreamReader(src)) { var edits = await BlockFormatter.ProvideEdits(reader, position, options); edits.Should().BeEmpty(); } }
public void BraceOnNewLineWithInterveningSingleLineComment() { const string before = @" struct S // This is a comment. { float4 position; float3 normal; };"; var options = new FormattingOptions { NewLines = { PlaceOpenBraceOnNewLineForTypes = false } }; AssertFormat(before, @" struct S // This is a comment. { float4 position; float3 normal; };", options: options); options = new FormattingOptions { NewLines = { PlaceOpenBraceOnNewLineForTypes = true } }; AssertFormat(before, @" struct S // This is a comment. { float4 position; float3 normal; };", options: options); }
public void ElseOnNewLine() { const string before = @" void main() { if (false) { } else { } }"; var options = new FormattingOptions { NewLines = { PlaceElseOnNewLine = false } }; AssertFormat(before, @" void main() { if (false) { } else { } }", options: options); options = new FormattingOptions { NewLines = { PlaceElseOnNewLine = true } }; AssertFormat(before, @" void main() { if (false) { } else { } }", options: options); }
public async Task ElseBlockFourSpace(int line, int col, int startCharacter, int endCharacter) { var position = new Position { line = line, character = col }; var options = new FormattingOptions { insertSpaces = true, tabSize = 4 }; var src = TestData.GetPath("TestData", "Formatting", "elseBlocks4.py"); using (var reader = new StreamReader(src)) { var edits = await BlockFormatter.ProvideEdits(reader, position, options); edits.Should().OnlyHaveTextEdit(string.Empty, (line, startCharacter, line, endCharacter)); } }
public void BraceOnNewLineForFunctions() { const string before = @" float4 main() { return float4(1, 0, 0, 1); }"; var options = new FormattingOptions { NewLines = { OpenBracePositionForFunctions = OpenBracesPosition.KeepOnSameLineAndPrependSpace } }; AssertFormat(before, @" float4 main() { return float4(1, 0, 0, 1); }", options: options); options = new FormattingOptions { NewLines = { OpenBracePositionForFunctions = OpenBracesPosition.MoveToNewLine } }; AssertFormat(before, @" float4 main() { return float4(1, 0, 0, 1); }", options: options); options = new FormattingOptions { NewLines = { OpenBracePositionForFunctions = OpenBracesPosition.DoNotMove } }; AssertFormat(before, @" float4 main() { return float4(1, 0, 0, 1); }", options: options); }
/// <summary> /// Initialization method for when EDI data string is known /// and the segment seperator if the interchange is known /// </summary> private void Parse(string value, FormattingOptions options) { var segmentStringValueCollection = value.Split(options.SegmentTerminator.AsSplitDelimiter(), StringSplitOptions.None); var functionalGroupStringArray = new List <System.Text.StringBuilder>(); foreach (var segment in segmentStringValueCollection) { var segmentStringInstance = segment; segmentStringInstance = RemoveCharacterFromString(segmentStringInstance, "\r", options); segmentStringInstance = RemoveCharacterFromString(segmentStringInstance, "\n", options); if (segmentStringInstance.Length < 3) { continue; } switch (segmentStringInstance.Substring(0, 3)) { case InterchangeControlHeader.ElementName: Header = new InterchangeControlHeader(segmentStringInstance, options); break; case InterchangeControlTrailer.ElementName: Trailer = new InterchangeControlTrailer(segmentStringInstance, options); break; default: if (segmentStringInstance.Substring(0, 2).Equals(FunctionalGroupHeader.ElementName)) { functionalGroupStringArray.Add(new System.Text.StringBuilder()); } functionalGroupStringArray[functionalGroupStringArray.Count - 1].Append(segmentStringInstance); functionalGroupStringArray[functionalGroupStringArray.Count - 1].Append(options.SegmentTerminator); break; } } foreach (var functionalGroupString in functionalGroupStringArray) { var fg = new FunctionalGroup.FunctionalGroup(functionalGroupString.ToString(), FormattingOptions); FunctionalGroups.Add(fg); } FunctionalGroups.TrimExcess(); }
public async Task TryBlockTab(int line, int col, int startCharacter, int endCharacter) { var position = new Position { line = line, character = col }; var options = new FormattingOptions { insertSpaces = false, tabSize = 4 }; var src = TestData.GetPath("TestData", "Formatting", "tryBlocksTab.py"); var newText = new string('\t', endCharacter - 1); using (var reader = new StreamReader(src)) { var edits = await BlockFormatter.ProvideEdits(reader, position, options); edits.Should().OnlyHaveTextEdit(newText, (line, startCharacter, line, endCharacter)); } }
public string Format(Signal signal, FormattingOptions options) { LinkedList <string> sequence = new LinkedList <string>(); sequence.AddFirst("sentinel"); FormatExpression(signal, sequence, options); sequence.RemoveFirst(); StringBuilder sb = new StringBuilder(8 * sequence.Count); // heuristics foreach (string token in sequence) { sb.Append(token); } //sb.Replace("+-", "-"); //sb.Replace("--", "+"); return(sb.ToString()); }
public void CommaDotSpacing() { const string before = @" void main() { float4 c = myTex. Sample(mySampler, coords); } "; var options = new FormattingOptions { Spacing = new SpacingOptions { InsertSpaceBeforeComma = false, InsertSpaceAfterComma = false, InsertSpaceBeforeDot = false, InsertSpaceAfterDot = false, } }; AssertFormat(before, @" void main() { float4 c = myTex.Sample(mySampler,coords); } ", options: options); options = new FormattingOptions { Spacing = new SpacingOptions { InsertSpaceBeforeComma = true, InsertSpaceAfterComma = true, InsertSpaceBeforeDot = true, InsertSpaceAfterDot = true } }; AssertFormat(before, @" void main() { float4 c = myTex . Sample(mySampler , coords); } ", options: options); }
protected async Task RunFormattingTestAsync( string input, string expected, int tabSize = 4, bool insertSpaces = true, string?fileKind = null, IReadOnlyList <TagHelperDescriptor>?tagHelpers = null, bool allowDiagnostics = false) { // Arrange fileKind ??= FileKinds.Component; TestFileMarkupParser.GetSpans(input, out input, out ImmutableArray <TextSpan> spans); var span = spans.IsEmpty ? new TextSpan(0, input.Length) : spans.Single(); var source = SourceText.From(input); var range = span.AsRange(source); var path = "file:///path/to/Document." + fileKind; var uri = new Uri(path); var(codeDocument, documentSnapshot) = CreateCodeDocumentAndSnapshot(source, uri.AbsolutePath, tagHelpers, fileKind, allowDiagnostics); var options = new FormattingOptions() { TabSize = tabSize, InsertSpaces = insertSpaces, }; var formattingService = CreateFormattingService(codeDocument); // Act var edits = await formattingService.FormatAsync(uri, documentSnapshot, range, options, CancellationToken.None); // Assert var edited = ApplyEdits(source, edits); var actual = edited.ToString(); new XUnitVerifier().EqualOrDiff(expected, actual); if (input.Equals(expected)) { Assert.Empty(edits); } }
public override async Task <TextEdit[]> FormatAsync( DocumentUri uri, DocumentSnapshot documentSnapshot, Range range, FormattingOptions options, CancellationToken cancellationToken) { if (uri is null) { throw new ArgumentNullException(nameof(uri)); } if (documentSnapshot is null) { throw new ArgumentNullException(nameof(documentSnapshot)); } if (range is null) { throw new ArgumentNullException(nameof(range)); } if (options is null) { throw new ArgumentNullException(nameof(options)); } var codeDocument = await documentSnapshot.GetGeneratedOutputAsync(); using var context = FormattingContext.Create(uri, documentSnapshot, codeDocument, options, _workspaceFactory); var result = new FormattingResult(Array.Empty <TextEdit>()); foreach (var pass in _formattingPasses) { cancellationToken.ThrowIfCancellationRequested(); result = await pass.ExecuteAsync(context, result, cancellationToken); } var filteredEdits = result.Edits.Where(e => range.LineOverlapsWith(e.Range)).ToArray(); return(filteredEdits); }
private void Parse(string value, FormattingOptions options) { FormattingOptions = options; var segmentStringValueCollection = value.Split(options.SegmentTerminator.AsSplitDelimiter(), StringSplitOptions.None); var transactionStringArray = new List <System.Text.StringBuilder>(); foreach (var segment in segmentStringValueCollection) { if (segment.Length < 2) { continue; } switch (segment.Substring(0, 2)) { case FunctionalGroupHeader.ElementName: Header = new FunctionalGroupHeader(segment, FormattingOptions); break; case FunctionalGroupTrailer.ElementName: Trailer = new FunctionalGroupTrailer(segment, FormattingOptions); break; case TransactionSetHeader.ElementName: transactionStringArray.Add(new System.Text.StringBuilder()); transactionStringArray[transactionStringArray.Count - 1].Append(segment); transactionStringArray[transactionStringArray.Count - 1].Append(options.SegmentTerminator); break; default: transactionStringArray[transactionStringArray.Count - 1].Append(segment); transactionStringArray[transactionStringArray.Count - 1].Append(options.SegmentTerminator); break; } } foreach (var transactionString in transactionStringArray) { var tx = new Transaction.Transaction(transactionString.ToString(), FormattingOptions); TransactionSets.Add(tx); } TransactionSets.TrimExcess(); }
public void RewritePinvoke(string inputFile, string outputFile) { var syntaxTree = SyntaxTree.ParseFile(Path.GetFullPath(inputFile)); var root = syntaxTree.GetRoot(); var compilation = Compilation.Create("PinvokeRewriter") .AddSyntaxTrees(syntaxTree) .AddReferences(new MetadataFileReference(typeof(object).Assembly.Location)); var semanticModel = compilation.GetSemanticModel(syntaxTree); var pinvokeRewriter = new PinvokeSyntaxRewriter(semanticModel); var rewritten = pinvokeRewriter.Visit(root).Format(FormattingOptions.GetDefaultOptions()).GetFormattedRoot(); using (var writer = new StreamWriter(outputFile)) { rewritten.WriteTo(writer); } }
protected async Task RunOnTypeFormattingTestAsync( string input, string expected, char triggerCharacter, int tabSize = 4, bool insertSpaces = true, string?fileKind = null) { // Arrange fileKind ??= FileKinds.Component; TestFileMarkupParser.GetPosition(input, out input, out var positionAfterTrigger); var razorSourceText = SourceText.From(input); var path = "file:///path/to/Document.razor"; var uri = new Uri(path); var(codeDocument, documentSnapshot) = CreateCodeDocumentAndSnapshot(razorSourceText, uri.AbsolutePath, fileKind: fileKind); var mappingService = new DefaultRazorDocumentMappingService(LoggerFactory); var languageKind = mappingService.GetLanguageKind(codeDocument, positionAfterTrigger); var formattingService = CreateFormattingService(codeDocument); var options = new FormattingOptions() { TabSize = tabSize, InsertSpaces = insertSpaces, }; // Act var edits = await formattingService.FormatOnTypeAsync(uri, documentSnapshot, languageKind, Array.Empty <TextEdit>(), options, hostDocumentIndex : positionAfterTrigger, triggerCharacter : triggerCharacter, CancellationToken.None); // Assert var edited = ApplyEdits(razorSourceText, edits); var actual = edited.ToString(); new XUnitVerifier().EqualOrDiff(expected, actual); if (input.Equals(expected)) { Assert.Empty(edits); } }
public void BraceOnNewLineForTechniquesAndPasses() { const string before = @" technique T { pass P { // A comment VertexShader = compile vs_2_0 VS ( ) ; PixelShader = compile ps_2_0 PS(); } }"; var options = new FormattingOptions { NewLines = { PlaceOpenBraceOnNewLineForTechniquesAndPasses = false } }; AssertFormat(before, @" technique T { pass P { // A comment VertexShader = compile vs_2_0 VS(); PixelShader = compile ps_2_0 PS(); } }", options: options); options = new FormattingOptions { NewLines = { PlaceOpenBraceOnNewLineForTechniquesAndPasses = true } }; AssertFormat(before, @" technique T { pass P { // A comment VertexShader = compile vs_2_0 VS(); PixelShader = compile ps_2_0 PS(); } }", options: options); }
protected async Task RunFormattingTestAsync( string input, string expected, int tabSize = 4, bool insertSpaces = true, string fileKind = null, IReadOnlyList <TagHelperDescriptor> tagHelpers = null) { // Arrange fileKind ??= FileKinds.Component; TestFileMarkupParser.GetSpans(input, out input, out ImmutableArray <TextSpan> spans); var span = spans.IsEmpty ? new TextSpan(0, input.Length) : spans.Single(); var source = SourceText.From(input); var range = span.AsRange(source); var path = "file:///path/to/document.razor"; var uri = new Uri(path); var(codeDocument, documentSnapshot) = CreateCodeDocumentAndSnapshot(source, uri.AbsolutePath, tagHelpers, fileKind); var options = new FormattingOptions() { TabSize = tabSize, InsertSpaces = insertSpaces, }; var formattingService = CreateFormattingService(codeDocument); // Act var edits = await formattingService.FormatAsync(uri, documentSnapshot, range, options, CancellationToken.None); // Assert var edited = ApplyEdits(source, edits); var actual = edited.ToString(); #if GENERATE_BASELINES Assert.False(true, "GENERATE_BASELINES is set to true."); #else Assert.Equal(expected, actual, ignoreLineEndingDifferences: true); #endif }
protected async Task RunOnTypeFormattingTestAsync(string input, string expected, string triggerCharacter, int tabSize = 4, bool insertSpaces = true, string fileKind = null) { // Arrange fileKind ??= FileKinds.Component; input = input.TrimStart('\r', '\n'); expected = expected.TrimStart('\r', '\n'); var beforeTrigger = input.IndexOf('|', StringComparison.Ordinal); var afterTrigger = input.LastIndexOf('|') - 1; input = input.Replace("|", string.Empty, StringComparison.Ordinal); var source = SourceText.From(input); var path = "file:///path/to/document.razor"; var uri = new Uri(path); var(codeDocument, documentSnapshot) = CreateCodeDocumentAndSnapshot(source, uri.AbsolutePath, fileKind: fileKind); var options = new FormattingOptions() { TabSize = tabSize, InsertSpaces = insertSpaces, }; var formattingService = CreateFormattingService(codeDocument); var(kind, projectedEdits) = GetFormattedEdits(codeDocument, expected, beforeTrigger); // Act var edits = await formattingService.ApplyFormattedEditsAsync(uri, documentSnapshot, kind, projectedEdits, options, CancellationToken.None); // Assert var edited = ApplyEdits(source, edits); var actual = edited.ToString(); #if GENERATE_BASELINES Assert.False(true, "GENERATE_BASELINES is set to true."); #else Assert.Equal(expected, actual); #endif }
protected async Task RunFormattingTestAsync(string input, string expected, int tabSize = 4, bool insertSpaces = true, string fileKind = null) { // Arrange fileKind ??= FileKinds.Component; input = input.TrimStart('\r', '\n'); expected = expected.TrimStart('\r', '\n'); var start = input.IndexOf('|', StringComparison.Ordinal); var end = input.LastIndexOf('|'); input = input.Replace("|", string.Empty, StringComparison.Ordinal); var source = SourceText.From(input); var span = TextSpan.FromBounds(start, end - 1); var range = span.AsRange(source); var path = "file:///path/to/document.razor"; var uri = new Uri(path); var(codeDocument, documentSnapshot) = CreateCodeDocumentAndSnapshot(source, uri.AbsolutePath, fileKind: fileKind); var options = new FormattingOptions() { TabSize = tabSize, InsertSpaces = insertSpaces, }; var formattingService = CreateFormattingService(codeDocument); // Act var edits = await formattingService.FormatAsync(uri, documentSnapshot, range, options, CancellationToken.None); // Assert var edited = ApplyEdits(source, edits); var actual = edited.ToString(); #if GENERATE_BASELINES Assert.False(true, "GENERATE_BASELINES is set to true."); #else Assert.Equal(expected, actual, ignoreLineEndingDifferences: true); #endif }
private void Format() { SnapshotPoint caret = this.TextView.Caret.Position.BufferPosition; Range range = new Range(0, caret.Snapshot.Length); List <DisableableRules> disabledRules = this.GetDisabledRules(Settings); FormattingOptions formattingOptions = GetFormattingOptions(Settings); List <TextEditInfo> edits = luaLuaFeature.Formatter.Format(txtCache.Get(caret.Snapshot), range, formattingOptions); using (ITextEdit textEdit = this.TextView.TextBuffer.CreateEdit()) { foreach (TextEditInfo edit in edits) { textEdit.Replace(edit.Start, edit.Length, edit.ReplacingWith); } textEdit.Apply(); } }
public void RaiseOptionsChanged() { AdvancedOptions = GetDialogPage <HlslAdvancedOptionsPage>().Options; var indentationOptions = GetDialogPage <HlslFormattingIndentationOptionsPage>().Options; var newLinesOptions = GetDialogPage <HlslFormattingNewLinesOptionsPage>().Options; var spacingOptions = GetDialogPage <HlslFormattingSpacingOptionsPage>().Options; FormattingOptions = new FormattingOptions { Indentation = indentationOptions, NewLines = newLinesOptions, Spacing = spacingOptions, SpacesPerIndent = HlslPackage.Instance.LanguagePreferences.SpacesPerIndent }; GeneralOptions = GetDialogPage <HlslFormattingGeneralOptionsPage>().Options; OptionsChanged?.Invoke(this, EventArgs.Empty); }
public void Init(int bookNumber, string chapterAndVersesString) { Verses.Clear(); using (var reader = new BibleTextReader(_optionsService.EpubPath)) { var formattingOptions = new FormattingOptions { IncludeVerseNumbers = false, ShowBreakInVerses = false, TrimPunctuation = _optionsService.TrimPunctuation, TrimQuotes = _optionsService.TrimQuotes, UseTildeSeparator = _optionsService.UseTildeMarker }; var verses = reader.ExtractVerseTextArray( bookNumber, chapterAndVersesString, formattingOptions); var epubPath = _optionsService.EpubPath; foreach (var vs in verses) { var modifiedText = _verseEditorService.Get(epubPath, vs.BookNumber, vs.ChapterNumber, vs.VerseNumber); var verseText = new EditVerseTextViewModel { EpubPath = epubPath, BookNumber = vs.BookNumber, Chapter = vs.ChapterNumber, Verse = vs.VerseNumber, OriginalVerseText = vs.Text, ModifiedVerseText = modifiedText ?? vs.Text }; Verses.Add(verseText); } } }
public override FormattingOptions?GetOptions(Uri lspDocumentUri) { if (lspDocumentUri is null) { throw new ArgumentNullException(nameof(lspDocumentUri)); } if (!_documentManager.TryGetDocument(lspDocumentUri, out var documentSnapshot)) { // Couldn't resolve document and therefore can't resolve the corresponding formatting options. return(null); } _indentationManagerService.GetIndentation(documentSnapshot.Snapshot.TextBuffer, explicitFormat: false, out var insertSpaces, out var tabSize, out _); var formattingOptions = new FormattingOptions() { InsertSpaces = insertSpaces, TabSize = tabSize, }; return(formattingOptions); }
internal static FormattingOptions CreateFormattingOptions(IEditorOptions editorOptions, ITextSnapshot snapshot) { FormattingOptions res = new FormattingOptions(); if (editorOptions.IsConvertTabsToSpacesEnabled()) { res.SpacesPerIndent = editorOptions.GetIndentSize(); } else { res.SpacesPerIndent = null; } res.NewLine = VsExtensions.GetNewLineText(snapshot); res.SpaceAfterComma = NodejsPackage.Instance.FormattingSpacingOptionsPage.SpaceAfterComma; res.SpaceAfterSemiColonInFor = NodejsPackage.Instance.FormattingSpacingOptionsPage.SpaceAfterSemicolonInFor; res.SpaceBeforeAndAfterBinaryOperator = NodejsPackage.Instance.FormattingSpacingOptionsPage.SpaceBeforeAndAfterBinaryOperator; res.SpaceAfterKeywordsInControlFlowStatements = NodejsPackage.Instance.FormattingSpacingOptionsPage.SpaceAfterKeywordsInControlFlow; res.SpaceAfterFunctionInAnonymousFunctions = NodejsPackage.Instance.FormattingSpacingOptionsPage.SpaceAfterFunctionKeywordForAnonymousFunctions; res.SpaceAfterOpeningAndBeforeClosingNonEmptyParenthesis = NodejsPackage.Instance.FormattingSpacingOptionsPage.SpaceAfterOpeningAndBeforeClosingNonEmptyParens; res.OpenBracesOnNewLineForFunctions = NodejsPackage.Instance.FormattingBracesOptionsPage.BraceOnNewLineForFunctions; res.OpenBracesOnNewLineForControl = NodejsPackage.Instance.FormattingBracesOptionsPage.BraceOnNewLineForControlBlocks; return res; }
public void TestBibleEpubParser() { if (!File.Exists(EpubPath)) { return; } var parser = new BibleEpubParser(EpubPath); var bookData = parser.ExtractBookData(); Assert.IsNotNull(bookData); // Gen 1:1 var formattingOptions = new FormattingOptions(); var s = parser.ExtractVerseText(1, 1, 1, formattingOptions); Assert.IsNotNull(s); var s2 = parser.ExtractVersesText(1, "1:1-3", formattingOptions); Assert.IsNotNull(s2); }
public void IndentBlockContents() { const string before = @" int Method() { int x; int y; }"; var options = new FormattingOptions { Indentation = { IndentBlockContents = false } }; AssertFormat(before, @" int Method() { int x; int y; }", options: options); options = new FormattingOptions { Indentation = { IndentBlockContents = true } }; AssertFormat(before, @" int Method() { int x; int y; }", options: options); }
public void BraceOnNewLineForControlBlocks() { const string before = @" float4 main() { for (int i = 0; i < 10; i++) { } }"; var options = new FormattingOptions { NewLines = { PlaceOpenBraceOnNewLineForControlBlocks = false } }; AssertFormat(before, @" float4 main() { for (int i = 0; i < 10; i++) { } }", options: options); options = new FormattingOptions { NewLines = { PlaceOpenBraceOnNewLineForControlBlocks = true } }; AssertFormat(before, @" float4 main() { for (int i = 0; i < 10; i++) { } }", options: options); }
public void IndentBraces() { const string before = @" int Method() { int x; int y; }"; var options = new FormattingOptions { Indentation = { IndentOpenAndCloseBraces = false } }; AssertFormat(before, @" int Method() { int x; int y; }", options: options); options = new FormattingOptions { Indentation = { IndentOpenAndCloseBraces = true } }; AssertFormat(before, @" int Method() { int x; int y; }", options: options); }
public OmniSharpOptions() { AspNet5 = new AspNet5Options(); FormattingOptions = new FormattingOptions(); }
/// <returns>precedence group</returns> private int FormatExpression(Signal signal, LinkedList<string> sequence, FormattingOptions options) { if(signal.BehavesAsSourceSignal) { if(signal.Value != null) { IFormattableLeaf leaf = signal.Value as IFormattableLeaf; if(leaf != null) { int prec; sequence.AddLast(leaf.Format(options, out prec)); return prec; } else { sequence.AddLast(signal.Value.ToString()); return -1; } } if(!string.IsNullOrEmpty(signal.Label)) { sequence.AddLast(signal.Label); return -1; } sequence.AddLast("signal"); return -1; } Port port = signal.DrivenByPort; IEntity entity = port.Entity; int precedence = entity.PrecedenceGroup; InfixNotation notation = entity.Notation; if(notation == InfixNotation.PreOperator) sequence.AddLast(entity.Symbol); else if(notation == InfixNotation.None) { sequence.AddLast(entity.Symbol); sequence.AddLast("("); } bool notFirst = false; foreach(Signal s in port.InputSignals) { if(notFirst) sequence.AddLast(entity.Symbol); else notFirst = true; LinkedListNode<string> before = sequence.Last; int subPrecedence = FormatExpression(s, sequence, options); if(subPrecedence >= precedence && notation != InfixNotation.None) { sequence.AddAfter(before, "("); sequence.AddLast(")"); } } if(notation == InfixNotation.PostOperator) sequence.AddLast(entity.Symbol); else if(notation == InfixNotation.None) sequence.AddLast(")"); return precedence; }
protected string FormatBase(string value, FormattingOptions options) { if((options & FormattingOptions.Compact) == FormattingOptions.Compact) return value; else return TypeId.ToString() + "(" + value + ")"; }
public void Save(string fileName, FormattingOptions options = FormattingOptions.None) { var iniText = IniRenderer.Render(GlobalSection, options); }
public OmniSharpOptions() { AspNet5 = new AspNet5Options(); MsBuild = new MSBuildOptions(); FormattingOptions = new FormattingOptions(); }
/// <summary> /// Turns a TimeSpan into a human-readable text. /// For example: "31.23:59:00.555" = "31 days 23 hours 59 minutes 0 seconds 555 milliseconds" /// </summary> /// <param name="FromTime"></param> /// <param name="smallestToDisplay">The lowest value that gets calculated. For example, if set to Minutes, then seconds (and milliseconds) will never get shown.</param> /// <param name="TruncationOption">Determines how much info is returned</param> /// <param name="Abbreviate">Example: "1d 2h 3m 4s 5ms" or "1 day 2 hours 3 minutes 4 seconds 5 milliseconds"</param> /// <param name="largestToDisplay">Example: If largest = Hours, then "3d 12h ..." = "84h ..."</param> /// <param name="IfZeroIncludeLessThan">Example: If largest = Hours and FromTime = 1 minute, then returns "less than 1 hour"</param> public static string ToTimeString(TimeSpan FromTime, FormattingOptions formattingOptions) { string ret = ""; bool TextStarted = false; if (formattingOptions.LargestUnitToDisplay < formattingOptions.SmallestUnitToDisplay) { formattingOptions.LargestUnitToDisplay = formattingOptions.SmallestUnitToDisplay; } // Do some rounding if necessary: bool RoundDown = formattingOptions.IfZeroIncludeLessThan; switch (formattingOptions.SmallestUnitToDisplay) { case AccuracyOptions.Weeks: if (RoundDown) { FromTime = TimeSpan.FromDays(Math.Floor(FromTime.TotalDays / 7) * 7); } else { FromTime = TimeSpan.FromDays(Math.Ceiling(FromTime.TotalDays / 7) * 7); } break; case AccuracyOptions.Days: if (RoundDown) { FromTime = TimeSpan.FromDays(Math.Floor(FromTime.TotalDays)); } else { FromTime = TimeSpan.FromDays(Math.Ceiling(FromTime.TotalDays)); } break; case AccuracyOptions.Hours: if (RoundDown) { FromTime = TimeSpan.FromHours(Math.Floor(FromTime.TotalHours)); } else { FromTime = TimeSpan.FromHours(Math.Ceiling(FromTime.TotalHours)); } break; case AccuracyOptions.Minutes: if (RoundDown) { FromTime = TimeSpan.FromMinutes(Math.Floor(FromTime.TotalMinutes)); } else { FromTime = TimeSpan.FromMinutes(Math.Ceiling(FromTime.TotalMinutes)); } break; case AccuracyOptions.Seconds: if (RoundDown) { FromTime = TimeSpan.FromSeconds(Math.Floor(FromTime.TotalSeconds)); } else { FromTime = TimeSpan.FromSeconds(Math.Ceiling(FromTime.TotalSeconds)); } break; case AccuracyOptions.Milliseconds: if (RoundDown) { FromTime = TimeSpan.FromMilliseconds(Math.Floor(FromTime.TotalMilliseconds)); } else { FromTime = TimeSpan.FromMilliseconds(Math.Ceiling(FromTime.TotalMilliseconds)); } break; } for (AccuracyOptions i = formattingOptions.LargestUnitToDisplay; i >= formattingOptions.SmallestUnitToDisplay; i += -1) { double Value = 0; string TimeTitle = ""; switch (i) { case AccuracyOptions.Weeks: Value = Math.Floor(FromTime.TotalDays / 7); TimeTitle = (formattingOptions.Abbreviate ? "w" : " week"); FromTime -= TimeSpan.FromDays(Value * 7); break; case AccuracyOptions.Days: Value = Math.Floor(FromTime.TotalDays); TimeTitle = (formattingOptions.Abbreviate ? "d" : " day"); FromTime -= TimeSpan.FromDays(Value); break; case AccuracyOptions.Hours: Value = Math.Floor(FromTime.TotalHours); TimeTitle = (formattingOptions.Abbreviate ? "h" : " hour"); FromTime -= TimeSpan.FromHours(Value); break; case AccuracyOptions.Minutes: Value = Math.Floor(FromTime.TotalMinutes); TimeTitle = (formattingOptions.Abbreviate ? "m" : " minute"); FromTime -= TimeSpan.FromMinutes(Value); break; case AccuracyOptions.Seconds: Value = Math.Floor(FromTime.TotalSeconds); TimeTitle = (formattingOptions.Abbreviate ? "s" : " second"); FromTime -= TimeSpan.FromSeconds(Value); break; case AccuracyOptions.Milliseconds: Value = Math.Floor(FromTime.TotalMilliseconds); TimeTitle = (formattingOptions.Abbreviate ? "ms" : " millisecond"); FromTime -= TimeSpan.FromMilliseconds(Value); break; } //Determine whether to display this value bool DisplayThisValue = false; switch (formattingOptions.TruncationOption) { case TruncationOptions.Auto: if (Value > 0) DisplayThisValue = true; break; case TruncationOptions.Shortest: if (TextStarted) break; // TODO: might not be correct. Was : Exit For if (Value > 0) DisplayThisValue = true; break; case TruncationOptions.Fill: if (TextStarted | Value > 0) DisplayThisValue = true; break; case TruncationOptions.Full: DisplayThisValue = true; break; } //we need to display SOMETHING (even if it's zero) if (i == formattingOptions.SmallestUnitToDisplay & TextStarted == false) { DisplayThisValue = true; if (formattingOptions.IfZeroIncludeLessThan & Value == 0){ret += "less than ";Value = 1;} } if (DisplayThisValue) { ret += Value + TimeTitle; if (Value != 1 & !formattingOptions.Abbreviate) ret += "s"; ret += " "; TextStarted = true; } } return ret.Trim(); }
public TimestringPlugin(FormattingOptions formattingOptions) { _formattingOptions = formattingOptions; }
/// <summary> /// Converts the Timespan into a string, using the format options as a shortcut. /// Example: /// ts$ = TimeString(Now.TimeOfDay, "[(smallest)w|d|h|m|s|ms] [(largest)w|d|h|m|s|ms] [auto|short|fill|full] [abbr|noabbr]") /// </summary> /// <param name="FromTime"></param> /// <param name="formatOptions">A list of flags options. /// Syntax: /// [(smallest)w|d|h|m|s|ms] [(largest)w|d|h|m|s|ms] [auto|short|fill|full] [abbr|noabbr] [less|noless] /// </param> /// <remarks> The format options are case insensitive. </remarks> public static string ToTimeString(TimeSpan FromTime, string formatOptions, FormattingOptions defaultFormattingOptions) { formatOptions = formatOptions.ToLower(); TruncationOptions TruncationOption = defaultFormattingOptions.TruncationOption; bool Abbreviate = defaultFormattingOptions.Abbreviate; bool IfZeroIncludeLessThan = defaultFormattingOptions.IfZeroIncludeLessThan; AccuracyOptions LargestToDisplay = AccuracyOptions.Milliseconds - 1; AccuracyOptions SmallestToDisplay = AccuracyOptions.Weeks + 1; AccuracyOptions? newRange = null; foreach (Match m in static_TimeString_r.Matches(formatOptions)) { switch (m.Value) { case "w": newRange = AccuracyOptions.Weeks; break; case "d": newRange = AccuracyOptions.Days; break; case "h": newRange = AccuracyOptions.Hours; break; case "m": newRange = AccuracyOptions.Minutes; break; case "s": newRange = AccuracyOptions.Seconds; break; case "ms": newRange = AccuracyOptions.Milliseconds; break; case "auto": TruncationOption = TruncationOptions.Auto; break; case "short": TruncationOption = TruncationOptions.Shortest; break; case "fill": TruncationOption = TruncationOptions.Fill; break; case "full": TruncationOption = TruncationOptions.Full; break; case "abbr": Abbreviate = true; break; case "noabbr": Abbreviate = false; break; case "less": IfZeroIncludeLessThan = true; break; case "noless": IfZeroIncludeLessThan = false; break; } if (newRange.HasValue) { if (SmallestToDisplay > newRange.Value) { SmallestToDisplay = newRange.Value; } if (LargestToDisplay < newRange.Value) { LargestToDisplay = newRange.Value; } } } if (!newRange.HasValue) { //let's do defaults: SmallestToDisplay = defaultFormattingOptions.SmallestUnitToDisplay; LargestToDisplay = defaultFormattingOptions.LargestUnitToDisplay; } return ToTimeString(FromTime, new FormattingOptions() { SmallestUnitToDisplay = SmallestToDisplay, LargestUnitToDisplay = LargestToDisplay, TruncationOption = TruncationOption, Abbreviate = Abbreviate, IfZeroIncludeLessThan = IfZeroIncludeLessThan }); }