-
Notifications
You must be signed in to change notification settings - Fork 36
/
OutliningTagger.cs
98 lines (80 loc) · 3.36 KB
/
OutliningTagger.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Windows.Threading;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Tagging;
using Microsoft.VisualStudio.Utilities;
namespace MarkdownMode
{
[Export(typeof(ITaggerProvider))]
[TagType(typeof(IOutliningRegionTag))]
[ContentType(ContentType.Name)]
sealed class OutliningTaggerProvider : ITaggerProvider
{
public ITagger<T> CreateTagger<T>(ITextBuffer buffer) where T : ITag
{
return buffer.Properties.GetOrCreateSingletonProperty(() => new OutliningTagger(buffer)) as ITagger<T>;
}
}
class MarkdownSection
{
public MarkdownParser.TokenType TokenType;
public ITrackingSpan Span;
}
sealed class OutliningTagger : ITagger<IOutliningRegionTag>, IDisposable
{
ITextBuffer _buffer;
List<MarkdownSection> _sections;
public OutliningTagger(ITextBuffer buffer)
{
_buffer = buffer;
_sections = new List<MarkdownSection>();
ReparseFile(null, EventArgs.Empty);
BufferIdleEventUtil.AddBufferIdleEventListener(buffer, ReparseFile);
}
void ReparseFile(object sender, EventArgs args)
{
ITextSnapshot snapshot = _buffer.CurrentSnapshot;
List<MarkdownSection> newSections = new List<MarkdownSection>(
MarkdownParser.ParseMarkdownSections(snapshot)
.Select(t => new MarkdownSection()
{
TokenType = t.TokenType,
Span = snapshot.CreateTrackingSpan(t.Span, SpanTrackingMode.EdgeExclusive)
}));
// For now, just dirty the entire file
_sections = newSections;
var temp = TagsChanged;
if (temp != null)
temp(this, new SnapshotSpanEventArgs(new SnapshotSpan(snapshot, 0, snapshot.Length)));
}
public IEnumerable<ITagSpan<IOutliningRegionTag>> GetTags(NormalizedSnapshotSpanCollection spans)
{
if (_sections == null || _sections.Count == 0 || spans.Count == 0)
yield break;
ITextSnapshot snapshot = spans[0].Snapshot;
foreach (var section in _sections)
{
var sectionSpan = section.Span.GetSpan(snapshot);
if (spans.IntersectsWith(new NormalizedSnapshotSpanCollection(sectionSpan)))
{
string firstLine = sectionSpan.Start.GetContainingLine().GetText().TrimStart(' ', '\t', '#');
string collapsedHintText;
if (sectionSpan.Length > 250)
collapsedHintText = snapshot.GetText(sectionSpan.Start, 247) + "...";
else
collapsedHintText = sectionSpan.GetText();
var tag = new OutliningRegionTag(firstLine, collapsedHintText);
yield return new TagSpan<IOutliningRegionTag>(sectionSpan, tag);
}
}
}
public event EventHandler<SnapshotSpanEventArgs> TagsChanged;
public void Dispose()
{
BufferIdleEventUtil.RemoveBufferIdleEventListener(_buffer, ReparseFile);
}
}
}