static async Task Main(string[] args) { AdhocWorkspace workspace = new AdhocWorkspace(); Solution solution = workspace.CurrentSolution; Project project = solution.AddProject("projectName", "assemblyName", LanguageNames.CSharp); Document document = project.AddDocument("name.cs", @"class C { static void Main() { WriteLine(""Hello, World!""); } }"); document = await Formatter.FormatAsync(document); SourceText text = await document.GetTextAsync(); IEnumerable <ClassifiedSpan> classifiedSpans = await Classifier.GetClassifiedSpansAsync(document, TextSpan.FromBounds(0, text.Length)); Console.BackgroundColor = ConsoleColor.Black; IEnumerable <Range> ranges = classifiedSpans.Select(classifiedSpan => new Range(classifiedSpan, text.GetSubText(classifiedSpan.TextSpan).ToString())); ranges = FillGaps(text, ranges); foreach (Range range in ranges) { switch (range.ClassificationType) { case "keyword": Console.ForegroundColor = ConsoleColor.DarkCyan; break; case "class name": Console.ForegroundColor = ConsoleColor.Cyan; break; case "string": Console.ForegroundColor = ConsoleColor.DarkYellow; break; default: Console.ForegroundColor = ConsoleColor.White; break; } Console.Write(range.Text); } Console.ResetColor(); Console.WriteLine(); }
public override SourceText GetSubText(TextSpan span) => _text.GetSubText(span);
public override SourceText GetSubText(TextSpan span) => new AvalonEditSourceText(_container, _sourceText.GetSubText(span));
public static SourceText GetLineContainingPosition(SourceText text, int position) { var line = text.Lines.GetLineFromPosition(position); return(text.GetSubText(line.Span)); }
private Range CreateRange(SourceText text, TextSpan span, string classification) { return(new Range(classification, span, text.GetSubText(span).ToString())); }
public Range(string classification, TextSpan span, SourceText text) : this(classification, span, text.GetSubText(span).ToString()) { }
public List <ClassFileInfo> Deep() { List <ClassFileInfo> result = new List <ClassFileInfo>(); var solutionFilePath = BuildWorkspaceHelper.GetRelativeWorkspacePath("Syinpo.Model\\Syinpo.Model.csproj"); { //using( var work = MSBuildWorkspace.Create() ) { // var project = work.OpenProjectAsync( solutionFilePath ).Result; // var documents = project.Documents.Where( w => w.Name.EndsWith( ".cs" ) ).ToList(); //} } AnalyzerManager manager = new AnalyzerManager(); var analyzer = manager.GetProject(solutionFilePath); AdhocWorkspace workspace = analyzer.GetWorkspace(); var project = workspace.CurrentSolution.Projects.First(); var documents = project.Documents.Where(w => w.Name.EndsWith(".cs")).ToList(); foreach (var document in documents) { string fileName = document.Name; string filePath = document.FilePath; var classes = document.GetSyntaxRootAsync().Result.DescendantNodes().OfType <ClassDeclarationSyntax>(); var classes2 = document.GetSyntaxRootAsync().Result.DescendantNodes().ToList().OfType <EnumDeclarationSyntax>(); if (classes.Any()) { foreach (var cl in classes) { NamespaceDeclarationSyntax namespaceDeclarationSyntax = null; if (!SyntaxNodeHelper.TryGetParentSyntax(cl, out namespaceDeclarationSyntax)) { continue; } var namespaceName = namespaceDeclarationSyntax.Name.ToString(); var fullClassName = namespaceName + "." + cl.Identifier.ToString(); var keys = document.Folders.ToList(); keys.Add(fileName); result.Add(new ClassFileInfo { FileName = fileName, FilePath = filePath, ClassName = cl.Identifier.ToString(), FullClassName = fullClassName, Key = string.Join(@"/", keys.ToArray()) }); } } if (classes2.Any()) { foreach (var cl in classes2) { NamespaceDeclarationSyntax namespaceDeclarationSyntax = null; if (!SyntaxNodeHelper.TryGetParentSyntax(cl, out namespaceDeclarationSyntax)) { continue; } var namespaceName = namespaceDeclarationSyntax.Name.ToString(); var fullClassName = namespaceName + "." + cl.Identifier.ToString(); var keys = document.Folders.ToList(); keys.Add(fileName); result.Add(new ClassFileInfo { FileName = fileName, FilePath = filePath, ClassName = cl.Identifier.ToString(), FullClassName = fullClassName, Key = string.Join(@"/", keys.ToArray()) }); } } #region Old if (false) { SourceText text = document.GetTextAsync().Result; var span = TextSpan.FromBounds(0, text.Length); IEnumerable <ClassifiedSpan> classifiedSpans = null; try { classifiedSpans = Classifier.GetClassifiedSpansAsync(document, span).Result; IEnumerable <Range> ranges = classifiedSpans.Select(classifiedSpan => new Range(classifiedSpan, text.GetSubText(classifiedSpan.TextSpan).ToString())); // var classes = ranges.Where(w => w.ClassificationType == "class name").ToList(); } catch (Exception ex) { throw new Exception("Exception during Classification of document: " + document.FilePath); } } #endregion } return(result); }
public override string ToString() { var subText = SourceText.GetSubText(Span); return(subText.ToString()); }
/// <summary> /// Check spacing rules in the leading comments. /// </summary> /// <param name="context">Analysis context.</param> /// <param name="childNode">Node to check for leading comments.</param> private static void CheckLeadingCommentSpace( SyntaxNodeAnalysisContext context, SyntaxNode childNode) { // If there's no leading trivia we can skip the whole node. if (!childNode.HasLeadingTrivia) { return; } // Get the leading comments. var comments = childNode.GetLeadingTrivia() .Where(trivia => trivia.IsKind(SyntaxKind.SingleLineCommentTrivia)) .ToList(); // We'll cache the source text if we need it. SourceText sourceText = null; // Process each comment trivia. // // Keep track of the previous comment line since we will consider subsequent lines // as single comments and won't require empty lines between them. var previousLineNumber = int.MinValue; for (var i = 0; i < comments.Count; ++i) { // Grab the comment line number. var comment = comments[i]; var currentLineNumber = comment.GetLocation().GetLineSpan().StartLinePosition.Line; // If this is continuation block, skip the checks. if (previousLineNumber == currentLineNumber - 1) { // Continuation comment. Store the line number and proceed to the next comment. previousLineNumber = currentLineNumber; continue; } // Not a continuation comment. Require empty line before. // Store the previous line number as we won't need it during this iteration // anymore and we might continue out of it at some point. previousLineNumber = currentLineNumber; // If we haven't retrieved the source text yet, do so now. // The source should be the same for all the trivia here. if (sourceText == null) { sourceText = comment.GetLocation().SourceTree .GetText(context.CancellationToken); } // Get the text for the line above. var lineAbove = sourceText.GetSubText(sourceText.Lines[currentLineNumber - 1].Span) .ToString().Trim(); // If the previous line is nothing but an opening brace, consider this okay. if (string.IsNullOrEmpty(lineAbove) || lineAbove == "{") { continue; } // Create the diagnostic message and report it. var diagnostic = Diagnostic.Create( NewlineBeforeComment.Rule, comment.GetLocation()); context.ReportDiagnostic(diagnostic); } }
internal async Task <FormattedText> InternalGetFormattedCodeAsync(string scriptCode, ScriptingOptions Options, FormatColorScheme ColorScheme) { var document = GetOrCreateDocument(Array.Empty <IParameter>(), scriptCode, Options); document = Formatter.FormatAsync(document).Result; SourceText documentText = await document.GetTextAsync(); IEnumerable <ClassifiedSpan> classifiedSpans = await Classifier.GetClassifiedSpansAsync(document, Microsoft.CodeAnalysis.Text.TextSpan.FromBounds(0, documentText.Length)); var ranges = classifiedSpans.Select(classifiedSpan => new Range(classifiedSpan, documentText.GetSubText(classifiedSpan.TextSpan).ToString())); var LineSpans = documentText.Lines.Select(x => x.SpanIncludingLineBreak); var result = new FormattedText(); var originalText = documentText.ToString(); var codeBuilder = new StringBuilder(); var segmentedSpans = DivideSpans(LineSpans, ranges.Select(x => x.TextSpan)).ToArray(); FormattedTextLine line = result.AppendLine(); foreach (var span in segmentedSpans) { var info = ranges.SingleOrDefault(x => x.TextSpan.CompareTo(span) == 0); TextFormat format; if (info != null) { var color = ColorScheme.GetColorForKeyword(info.ClassificationType); format = new TextFormat(color); } else { var color = ColorScheme.Unknown; format = new TextFormat(color); } var text = originalText.Substring(span.Start, span.Length); if (text.EndsWith(Environment.NewLine)) { text = text.Substring(0, text.Length - Environment.NewLine.Length); line.AppendText(text, format); line = result.AppendLine(); } else { line.AppendText(text, format); } //{ //text = text.Substring(0, text.Length - Environment.NewLine.Length); // line = result.AppendLine(); /* } else * { * line.AppendText(text, format); * }*/ } return(result); }
public Range(string classification, Microsoft.CodeAnalysis.Text.TextSpan span, SourceText text) : this(classification, span, text.GetSubText(span).ToString()) { }