forked from microsoft/VSExtensibility
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTextViewMarginProvider.cs
81 lines (70 loc) · 2.89 KB
/
TextViewMarginProvider.cs
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
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace WordCountMarginSample;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.VisualStudio.Extensibility;
using Microsoft.VisualStudio.Extensibility.Editor;
using Microsoft.VisualStudio.RpcContracts.RemoteUI;
/// <summary>
/// A sample text view margin provider, which adds a margin to the Visual Studio editor status bar, to the left
/// of the built-in line number margin, indicating number of words in the current text document.
/// </summary>
[VisualStudioContribution]
internal class TextViewMarginProvider : ExtensionPart, ITextViewMarginProvider, ITextViewOpenClosedListener, ITextViewChangedListener
{
private readonly Dictionary<Uri, WordCountData> dataModels = new();
/// <inheritdoc />
public TextViewExtensionConfiguration TextViewExtensionConfiguration => new()
{
AppliesTo = new[]
{
DocumentFilter.FromDocumentType(DocumentType.KnownValues.Text),
},
};
/// <inheritdoc />
public TextViewMarginProviderConfiguration TextViewMarginProviderConfiguration =>
new(marginContainer: ContainerMarginPlacement.KnownValues.BottomRightCorner)
{
Before = new[] { MarginPlacement.KnownValues.RowMargin },
};
/// <inheritdoc />
public Task<IRemoteUserControl> CreateVisualElementAsync(ITextViewSnapshot textView, CancellationToken cancellationToken)
{
var dataModel = new WordCountData();
dataModel.WordCount = CountWords(textView.Document);
this.dataModels[textView.Uri] = dataModel;
return Task.FromResult<IRemoteUserControl>(new MyMarginContent(dataModel));
}
/// <inheritdoc />
public Task TextViewChangedAsync(TextViewChangedArgs args, CancellationToken cancellationToken)
{
this.dataModels[args.AfterTextView.Uri].WordCount = CountWords(args.AfterTextView.Document);
return Task.CompletedTask;
}
/// <inheritdoc />
public Task TextViewClosedAsync(ITextViewSnapshot textView, CancellationToken cancellationToken)
{
this.dataModels.Remove(textView.Uri);
return Task.CompletedTask;
}
/// <inheritdoc />
public Task TextViewOpenedAsync(ITextViewSnapshot textView, CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
private static int CountWords(ITextDocumentSnapshot documentSnapshot)
{
int wordCount = 0;
for (int i = 1; i < documentSnapshot.Length; i++)
{
if (char.IsWhiteSpace(documentSnapshot[i - 1]) && char.IsLetterOrDigit(documentSnapshot[i]))
{
wordCount++;
}
}
return wordCount;
}
}