Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
A Visual Studio extension can classify a document's syntax allowing for
the text to be colorized accordingly, which is achieved by contributing
a tagger that returns ClassificationTag
values.
A detailed description of how to provide a tagger can be found in the Extending Visual Studio editor with a new tagger article.
To provide classification, we first implement a tagger provider and a tagger:
[VisualStudioContribution]
internal class MyClassificationTaggerProvider :
ExtensionPart,
ITextViewTaggerProvider<ClassificationTag>,
ITextViewChangedListener
{
...
internal class MyClassificationTagger :
TextViewTagger<ClassificationTag>
{
...
Since we want the document colorization to appear as instantly as possible, the generation of taggers needs to be as fast as possible. This article stresses the importance of:
- only generating tags for the requested document portion (or a small superset of it), not the whole document;
- avoiding parsing the whole document in order to generate tags.
Once the tagger structure is ready and the syntax parsing for the specific
file format is implemented, the tagger can provide text classification, by creating ClassificationTag
values using the available
ClassificationType
know values, and calling UpdateTagsAsync
.
List<TaggedTrackingTextRange<ClassificationTag>> tags = new();
List<TextRange> ranges = new();
...
ranges.Add(new(document, lineStart, lineLength));
tags.Add(
new TaggedTrackingTextRange<ClassificationTag>(
new TrackingTextRange(
document,
tagStartPosition,
tagLength,
TextRangeTrackingMode.ExtendNone),
new ClassificationTag(ClassificationType.KnownValues.Operator)));
...
await this.UpdateTagsAsync(ranges, tags, CancellationToken.None);
At this time, VisualStudio.Extensibility doesn't support defining text colors
for new classification types yet, so we must use existing classification types
(ClassificationType.KnownValues
).
VisualStudio.Extensibility in-proc extension, can use ClassificationTypeDefinition
to define new classification types. Their name can be referenced using
ClassificationType.Custom
.