Repository navigation
Expand file tree
/
Copy pathProgram.cs
More file actions
96 lines (82 loc) · 3.02 KB
/
Copy pathProgram.cs
File metadata and controls
96 lines (82 loc) · 3.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Classification;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Text;
internal static class Program
{
private static void Main(string[] args)
{
TestFormatterAndClassifierAsync().Wait();
}
private static async Task TestFormatterAndClassifierAsync()
{
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;
var 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();
}
private static IEnumerable<Range> FillGaps(SourceText text, IEnumerable<Range> ranges)
{
const string WhitespaceClassification = null;
int current = 0;
Range previous = null;
foreach (Range range in ranges)
{
int start = range.TextSpan.Start;
if (start > current)
{
yield return new Range(WhitespaceClassification, TextSpan.FromBounds(current, start), text);
}
if (previous == null || range.TextSpan != previous.TextSpan)
{
yield return range;
}
previous = range;
current = range.TextSpan.End;
}
if (current < text.Length)
{
yield return new Range(WhitespaceClassification, TextSpan.FromBounds(current, text.Length), text);
}
}
}