-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathCBETagger.cs
More file actions
1024 lines (867 loc) · 34.8 KB
/
Copy pathCBETagger.cs
File metadata and controls
1024 lines (867 loc) · 34.8 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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Thanks to https://github.com/jaredpar/ControlCharAdornmentSample/blob/master/CharDisplayTaggerSource.cs
using CodeBlockEndTag.Extensions;
using CodeBlockEndTag.Model;
using CodeBlockEndTag.Shell;
using CommunityToolkit.HighPerformance;
using Microsoft.VisualStudio.Imaging.Interop;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Outlining;
using Microsoft.VisualStudio.Text.Tagging;
using Microsoft.VisualStudio.Utilities;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
namespace CodeBlockEndTag;
/// <summary>f
/// This tagger provides editor tags that are inserted into the TextView (IntraTextAdornmentTags)
/// The tags are added after each code block encapsulated by curly bracets: { ... }
/// The tags will show the code blocks condition, or whatever serves as header for the block
/// By clicking on a tag, the editor will jump to that code blocks header
/// </summary>
internal class CBETagger : ITagger<IntraTextAdornmentTag>, IDisposable
{
private static readonly ReadOnlyCollection<ITagSpan<IntraTextAdornmentTag>> EmptyTagColllection =
new([]);
#region Properties & Fields
// EventHandler for ITagger<IntraTextAdornmentTag> tags changed event
private EventHandler<SnapshotSpanEventArgs> _changedEvent;
/// <summary>
/// The outlining manager for this text view (provides collapsible regions)
/// </summary>
private readonly IOutliningManager _OutliningManager;
/// <summary>
/// Whether outlining is supported and enabled for this buffer
/// </summary>
private readonly bool _OutliningSupported;
/// <summary>
/// The TextView this tagger is assigned to
/// </summary>
private readonly IWpfTextView _TextView;
/// <summary>
/// This is a list of already created adornment tags used as cache
/// </summary>
private readonly Dictionary<AdornmentDataKey, CBAdornmentData> _adornmentCache = new(50);
private struct AdornmentDataKey(int start, int end)
{
public int StartPosition = start;
public int EndPosition = end;
}
/// <summary>
/// This is the visible span of the textview
/// </summary>
private Span? _VisibleSpan;
/// <summary>
/// Timer for debouncing layout changed events
/// </summary>
private System.Windows.Threading.DispatcherTimer _LayoutChangedDebounceTimer;
/// <summary>
/// Pending span to invalidate after debounce
/// </summary>
private Span? _PendingInvalidateSpan;
/// <summary>
/// Is set, when the instance is disposed
/// </summary>
private bool _Disposed;
#endregion
#region Ctor
/// <summary>
/// Creates a new instance of CBRTagger
/// </summary>
/// <param name="provider">the CBETaggerProvider that created the tagger</param>
/// <param name="textView">the WpfTextView this tagger is assigned to</param>
internal CBETagger(CBETaggerProvider provider, IWpfTextView textView)
{
if (provider == null || textView == null)
{
throw new ArgumentNullException("The arguments of CBETagger can't be null");
}
ThreadHelper.ThrowIfNotOnUIThread();
_TextView = textView;
// Get outlining manager for collapsible regions
_OutliningManager = provider.OutliningManagerService?.GetOutliningManager(_TextView);
_OutliningSupported = _OutliningManager != null && _OutliningManager.Enabled;
// Hook up events
_TextView.TextBuffer.Changed += TextBuffer_Changed;
_TextView.LayoutChanged += OnTextViewLayoutChanged;
_TextView.Caret.PositionChanged += Caret_PositionChanged;
// Hook up outlining events if supported
if (_OutliningManager != null)
{
_OutliningManager.RegionsChanged += OnOutliningRegionsChanged;
}
// Initialize debounce timer for layout changes (150ms delay)
_LayoutChangedDebounceTimer = new System.Windows.Threading.DispatcherTimer
{
Interval = TimeSpan.FromMilliseconds(150)
};
_LayoutChangedDebounceTimer.Tick += OnLayoutChangedDebounceTimerTick;
// Listen for package events
InitializeCBEPackage();
}
#endregion
#region TextBuffer changed
private void Caret_PositionChanged(object sender, CaretPositionChangedEventArgs e)
{
#if DEBUG
System.Diagnostics.Debug.WriteLine($"Caret_PositionChanged called: VisibilityMode={CBETagPackage.CBEVisibilityMode}");
#endif
var oldPos = e.OldPosition.BufferPosition.Position;
var newPos = e.NewPosition.BufferPosition.Position;
#if DEBUG
System.Diagnostics.Debug.WriteLine($" oldPos={oldPos}, newPos={newPos}");
#endif
// Get the lines containing the old and new caret positions
var snapshot = _TextView.TextBuffer.CurrentSnapshot;
var oldLine = snapshot.GetLineFromPosition(oldPos);
var newLine = snapshot.GetLineFromPosition(newPos);
// Invalidate from the start of the first line to the end of the last line
var start = Math.Min(oldLine.Start.Position, newLine.Start.Position);
var end = Math.Max(oldLine.End.Position, newLine.End.Position);
#if DEBUG
System.Diagnostics.Debug.WriteLine($" -> Invalidating span: start={start}, end={end} (full lines)");
#endif
InvalidateSpan(Span.FromBounds(start, end), false);
}
private void TextBuffer_Changed(object sender, TextContentChangedEventArgs e)
{
foreach (var textChange in e.Changes)
{
OnTextChanged(textChange);
}
}
private void OnTextChanged(ITextChange textChange)
{
// remove or update tags in adornment cache
int oldEnd = textChange.OldEnd;
int oldPosition = textChange.OldPosition;
int delta = textChange.Delta;
foreach (var entry in _adornmentCache.ToList())
{
var adornment = entry.Value;
bool isHeaderAfterChange = adornment.HeaderStartPosition > oldEnd;
if (!(isHeaderAfterChange || adornment.EndPosition < oldPosition))
{
if (adornment.Adornment is CBETagControl tag)
{
tag.TagClicked -= Adornment_TagClicked;
}
_adornmentCache.Remove(entry.Key);
}
if (isHeaderAfterChange)
{
adornment.Move(delta);
}
}
}
private void OnOutliningRegionsChanged(object sender, RegionsChangedEventArgs e)
{
// Invalidate cache for affected regions
var affectedSpan = e.AffectedSpan;
InvalidateSpan(affectedSpan, clearCache: true);
}
#endregion
#region ITagger<IntraTextAdornmentTag>
IEnumerable<ITagSpan<IntraTextAdornmentTag>> ITagger<IntraTextAdornmentTag>.GetTags(NormalizedSnapshotSpanCollection spans)
{
ThreadHelper.ThrowIfNotOnUIThread();
// Check if content type (language) is supported and active for tagging
if (!CBETagPackage.IsLanguageSupported(_TextView.TextBuffer.ContentType.TypeName))
{
yield break;
}
// Second chance to hook up events
InitializeCBEPackage();
#if DEBUG
System.Diagnostics.Debug.WriteLine($">>> GetTags called with {spans.Count} span(s)");
foreach (var span in spans)
{
System.Diagnostics.Debug.WriteLine($" Span: {span.Start.Position}-{span.End.Position} (length: {span.Length})");
}
#endif
foreach (var span in spans)
{
foreach (var tag in GetTags(span))
{
yield return tag;
}
}
#if DEBUG
System.Diagnostics.Debug.WriteLine($"<<< GetTags finished");
#endif
}
event EventHandler<SnapshotSpanEventArgs> ITagger<IntraTextAdornmentTag>.TagsChanged
{
add => _changedEvent += value;
remove => _changedEvent -= value;
}
#endregion
#region Tag placement
internal ReadOnlyCollection<ITagSpan<IntraTextAdornmentTag>> GetTags(SnapshotSpan span)
{
#if DEBUG
System.Diagnostics.Debug.WriteLine($" GetTags(span): {span.Start.Position}-{span.End.Position}");
System.Diagnostics.Debug.WriteLine($" CBETaggerEnabled: {CBETagPackage.CBETaggerEnabled}");
System.Diagnostics.Debug.WriteLine($" OutliningSupported: {_OutliningSupported}");
System.Diagnostics.Debug.WriteLine($" VisibleSpan: {(_VisibleSpan.HasValue ? $"{_VisibleSpan.Value.Start}-{_VisibleSpan.Value.End}" : "(null)")}");
#endif
if (!CBETagPackage.CBETaggerEnabled ||
span.Snapshot != _TextView.TextBuffer.CurrentSnapshot ||
span.Length == 0)
{
#if DEBUG
System.Diagnostics.Debug.WriteLine($" -> Returning empty (disabled or invalid span)");
#endif
return EmptyTagColllection;
}
// Check if outlining is supported
if (!_OutliningSupported)
{
#if DEBUG
System.Diagnostics.Debug.WriteLine($" -> Returning empty (outlining not supported)");
#endif
return EmptyTagColllection;
}
// if big span, return only tags for visible area
if (span.Length > 1000 && _VisibleSpan.HasValue)
{
var overlap = span.Overlap(_VisibleSpan.Value);
if (overlap.HasValue)
{
span = overlap.Value;
#if DEBUG
System.Diagnostics.Debug.WriteLine($" -> Big span, using overlap: {span.Start.Position}-{span.End.Position}");
#endif
if (span.Length == 0)
{
#if DEBUG
System.Diagnostics.Debug.WriteLine($" -> Returning empty (overlap is empty)");
#endif
return EmptyTagColllection;
}
}
}
return GetTagsCore(span);
}
#if DEBUG
private System.Diagnostics.Stopwatch _watch;
#endif
private ReadOnlyCollection<ITagSpan<IntraTextAdornmentTag>> GetTagsCore(SnapshotSpan span)
{
List<ITagSpan<IntraTextAdornmentTag>> list = new(32);
var snapshot = span.Snapshot;
#if DEBUG
// Stop time
_watch ??= new System.Diagnostics.Stopwatch();
_watch.Restart();
System.Diagnostics.Debug.WriteLine($" GetTagsCore: Processing span {span.Start.Position}-{span.End.Position}");
#endif
try
{
// Expand the query span to include regions that might end in our visible area
// but start before it. Query from beginning of file to end of requested span.
var expandedSpan = new SnapshotSpan(snapshot, 0, span.End.Position);
#if DEBUG
System.Diagnostics.Debug.WriteLine($" Expanded span for query: 0-{span.End.Position}");
#endif
// Get all collapsible regions from the outlining manager
var regions = _OutliningManager.GetAllRegions(expandedSpan);
#if DEBUG
System.Diagnostics.Debug.WriteLine($" Found {regions.Count()} total regions in expanded span");
#endif
int processedCount = 0;
int skippedBefore = 0;
int skippedSingleLine = 0;
int skippedInvisible = 0;
int addedCount = 0;
foreach (var region in regions)
{
processedCount++;
// Get the extent of this collapsible region
var extent = region.Extent.GetSpan(snapshot);
// Only process regions that end within or after the requested span
if (extent.End.Position < span.Start.Position)
{
skippedBefore++;
continue;
}
// Skip if region is not multi-line
var startLine = snapshot.GetLineFromPosition(extent.Start);
var endLine = snapshot.GetLineFromPosition(extent.End);
if (startLine.LineNumber == endLine.LineNumber)
{
skippedSingleLine++;
continue;
}
// Get positions
int regionStart = extent.Start.Position;
int regionEnd = extent.End.Position;
#if DEBUG
if (addedCount < 5 || processedCount <= 10) // Log first few for detail
{
System.Diagnostics.Debug.WriteLine($" Region #{processedCount}: {regionStart}-{regionEnd}");
}
#endif
// Check if this region should be blocklisted (comments, etc.) before processing
// Strip closing brackets and whitespace from the beginning to handle cases like "} /*"
var firstLineText = startLine.GetText().AsSpan().Trim();
firstLineText = firstLineText.TrimStart('}').TrimStart();
if (IsBlocklistedRegion(firstLineText))
{
skippedInvisible++;
continue;
}
// Extract header from the first line of the region
ReadOnlySpan<char> cbHeader = GetHeaderFromRegion(region, snapshot, out int cbHeaderPosition);
// Check tag visibility (includes caret position check)
if (!IsTagVisible(cbHeaderPosition, regionEnd, _VisibleSpan, snapshot))
{
skippedInvisible++;
continue;
}
// Clean up header text - remove extra spaces and tabs
if (!cbHeader.IsEmpty)
{
PooledStringBuilder sbPool = PooledStringBuilder.GetInstance();
StringBuilder stringBuilder = sbPool.Builder;
char lastChar = '\0';
int lastNonSpaceIndex = -1;
for (int i = 0; i < cbHeader.Length; i++)
{
char chr = cbHeader[i];
if (char.IsControl(chr) || chr == '\n' || chr == '\r')
{
continue;
}
if (chr == '\t')
{
chr = ' ';
}
if (chr == ' ' && (stringBuilder.Length == 0 || lastChar == ' '))
{
continue;
}
stringBuilder.Append(chr);
lastChar = chr;
if (chr != ' ')
{
lastNonSpaceIndex = stringBuilder.Length;
}
}
cbHeader = sbPool.ToStringAndFree(0, lastNonSpaceIndex);
}
// Use cache or create new tag
AdornmentDataKey adornmentDataKey = new(regionStart, regionEnd);
_adornmentCache.TryGetValue(adornmentDataKey, out var cbAdornmentData);
CBETagControl tagElement;
if (cbAdornmentData.Adornment is CBETagControl tagControl)
{
tagElement = tagControl;
}
else
{
// Icon for tag
ImageMoniker iconMoniker =
CBETagPackage.CBEDisplayMode == (int)DisplayModes.Text ||
cbHeader.IsWhiteSpace() ||
cbHeader.IndexOf("{") >= 0
? Microsoft.VisualStudio.Imaging.KnownMonikers.QuestionMark
: IconMonikerSelector.SelectMoniker(cbHeader);
// create new adornment
tagElement = new CBETagControl()
{
Text = cbHeader.ToString(),
IconMoniker = iconMoniker,
DisplayMode = CBETagPackage.CBEDisplayMode,
Margin = new System.Windows.Thickness(CBETagPackage.CBEMargin, 0, 0, 0)
};
tagElement.TagClicked += Adornment_TagClicked;
cbAdornmentData = new CBAdornmentData(regionStart, regionEnd, cbHeaderPosition, tagElement);
tagElement.AdornmentData = cbAdornmentData;
_adornmentCache.Add(adornmentDataKey, cbAdornmentData);
}
tagElement.SetResourceReference(CBETagControl.LineHeightProperty, EndTagColors.FontSizeKey);
tagElement.SetResourceReference(CBETagControl.TextColorProperty, EndTagColors.GetForegroundResourceKey(_TextView.TextBuffer.ContentType.TypeName));
// Add new tag to list
// Place tag at the end of the region
IntraTextAdornmentTag cbTag = new(tagElement, null, PositionAffinity.Predecessor);
// Compute insertion position for the adornment. Use the region end as base but
// advance one character when the next character is a closing delimiter
// (for example '>' in XML/XAML or '}' in code) so the tag is rendered after
// the closing token instead of between characters like '/' and '>'.
int insertionIndex = regionEnd;
try
{
if (insertionIndex < snapshot.Length)
{
char nextChar = snapshot[insertionIndex];
if (nextChar == '>' || nextChar == '}' || nextChar == ')' || nextChar == ']')
{
insertionIndex = Math.Min(insertionIndex + 1, snapshot.Length);
}
}
}
catch
{
// Be defensive - if snapshot access fails for some reason, fall back to regionEnd
insertionIndex = Math.Min(regionEnd, snapshot.Length);
}
SnapshotSpan cbSnapshotSpan = new(snapshot, insertionIndex, 0);
TagSpan<IntraTextAdornmentTag> cbTagSpan = new(cbSnapshotSpan, cbTag);
list.Add(cbTagSpan);
addedCount++;
}
#if DEBUG
System.Diagnostics.Debug.WriteLine($" Summary: Processed={processedCount}, Added={addedCount}, Skipped: Before={skippedBefore}, SingleLine={skippedSingleLine}, Invisible={skippedInvisible}");
#endif
}
catch (Exception ex)
{
#if DEBUG
System.Diagnostics.Debug.WriteLine($" Exception in GetTagsCore: {ex.Message}");
System.Diagnostics.Debug.WriteLine($" Stack: {ex.StackTrace}");
#endif
// May happen when closing a text editor or during rapid edits
}
#if DEBUG
_watch.Stop();
System.Diagnostics.Debug.WriteLine($" GetTagsCore completed: {list.Count} tags in {_watch.ElapsedMilliseconds}ms");
#endif
// Track telemetry for tag creation (only periodically to avoid spam)
try
{
if (list.Count > 0 && _tagCreationCounter++ % 50 == 0)
{
var language = _TextView?.TextBuffer?.ContentType?.TypeName ?? "Unknown";
Telemetry.TelemetryEvents.TrackTagsCreated(language, list.Count);
}
}
catch
{
// Telemetry should never break functionality
}
return new ReadOnlyCollection<ITagSpan<IntraTextAdornmentTag>>(list);
}
private int _tagCreationCounter = 0;
/// <summary>
/// Extracts the header text from a collapsible region
/// Returns the text and outputs the start position within the snapshot
/// </summary>
private ReadOnlySpan<char> GetHeaderFromRegion(
ICollapsible region,
ITextSnapshot snapshot,
out int headerStart)
{
var extent = region.Extent.GetSpan(snapshot);
var firstLine = snapshot.GetLineFromPosition(extent.Start);
headerStart = firstLine.Start.Position;
// Get text from the first line
var lineText = firstLine.GetText().AsSpan().Trim();
// For #endregion, don't show tags
if (lineText.StartsWith("#endregion"))
{
headerStart = -1;
return ReadOnlySpan<char>.Empty;
}
// Find opening brace and get everything before it
int braceIndex = lineText.IndexOf('{');
if (braceIndex > 0)
{
lineText = lineText.Slice(0, braceIndex).Trim();
}
else if (braceIndex == 0)
{
// Standalone block with just '{' - allow it with empty header
return ReadOnlySpan<char>.Empty;
}
// For #region and other non-brace collapsibles, take the whole line
// but remove #region/#endregion keywords
else if (lineText.StartsWith("#region"))
{
lineText = lineText.Slice(7).Trim(); // Remove "#region"
}
return lineText;
}
/// <summary>
/// Checks if a region header matches blocklisted patterns (comments, etc.)
/// </summary>
/// <param name="headerText">The header text to check</param>
/// <returns>True if the region should be ignored</returns>
private bool IsBlocklistedRegion(ReadOnlySpan<char> headerText)
{
if (headerText.IsEmpty)
{
return false; // Allow empty headers (standalone blocks)
}
// Block single-line comments
if (headerText.StartsWith("//"))
{
return true;
}
// Block multi-line comments
if (headerText.StartsWith("/*") || headerText.StartsWith("*"))
{
return true;
}
// Block XML documentation comments
if (headerText.StartsWith("///"))
{
return true;
}
// Block #endregion
if (headerText.StartsWith("#endregion"))
{
return true;
}
// Block using directives (namespace imports) but NOT using statements (resource disposal)
// using directives: "using System;" or "using Microsoft.VisualStudio.Shell;"
// using statements: "using (var conn = ...)" or "using var conn = ..."
if (headerText.StartsWith("using"))
{
// Check if it's a using directive (has a semicolon and no parentheses/var keyword)
// using statements will have either '(' or 'var' after 'using'
ReadOnlySpan<char> afterUsing = headerText.Slice(5).TrimStart();
// If it starts with '(' or 'var', it's a using statement (keep it)
if (afterUsing.StartsWith("(") || afterUsing.StartsWith("var"))
{
return false; // Keep using statements
}
// Otherwise, it's a using directive (block it)
return true;
}
return false;
}
#endregion
#region Tag Clicked Handler
/// <summary>
/// Handles the click event on a tag
/// </summary>
private void Adornment_TagClicked(CBAdornmentData adornment, bool jumpToHead)
{
if (_TextView == null)
{
return;
}
// Track tag click
try
{
Telemetry.TelemetryEvents.TrackTagClicked(jumpToHead);
}
catch
{
// Telemetry should never break functionality
}
SnapshotPoint targetPoint;
if (jumpToHead)
{
// Jump to header
targetPoint = new SnapshotPoint(_TextView.TextBuffer.CurrentSnapshot, adornment.HeaderStartPosition);
_TextView.DisplayTextLineContainingBufferPosition(targetPoint, 30, ViewRelativePosition.Top);
}
else
{
// Set caret behind closing bracet
targetPoint = new SnapshotPoint(_TextView.TextBuffer.CurrentSnapshot, adornment.EndPosition + 1);
}
_TextView.Caret.MoveTo(targetPoint);
}
#endregion
#region Options changed
/// <summary>
/// Handles the event when any package option is changed
/// </summary>
private void OnPackageOptionChanged(object sender)
{
InvalidateSpan(
Span.FromBounds(
Math.Max(0, _VisibleSpan?.Start ?? 0),
Math.Max(1, _VisibleSpan?.End ?? 1)));
}
/// <summary>
/// Invalidates all cached tags within or after the given span
/// </summary>
private void InvalidateSpan(Span invalidateSpan, bool clearCache = true)
{
// Remove tags from cache
if (clearCache)
{
foreach (var entry in _adornmentCache.ToList())
{
var adornment = entry.Value;
if (adornment.HeaderStartPosition < invalidateSpan.Start && adornment.EndPosition < invalidateSpan.Start)
{
continue;
}
if (adornment.Adornment is CBETagControl tag)
{
tag.TagClicked -= Adornment_TagClicked;
}
_adornmentCache.Remove(entry.Key);
}
}
// Invalidate span
var snapshop = _TextView.TextBuffer.CurrentSnapshot;
if (invalidateSpan.End <= snapshop.Length)
{
_changedEvent?.Invoke(this, new(new(snapshop, invalidateSpan)));
}
}
/// <summary>
/// Hooks up events at the package
/// Due to AsyncPackage usage, the Tagger may be initialized before the Package
/// So be safe about this
/// </summary>
private void InitializeCBEPackage()
{
if (isPackageInitialized || CBETagPackage.Instance == null || _Disposed)
{
return;
}
ThreadHelper.ThrowIfNotOnUIThread();
CBETagPackage.Instance.PackageOptionChanged += OnPackageOptionChanged;
FontAndColorDefaultsCSharpTags.Instance.EnsureFontAndColorsInitialized();
isPackageInitialized = true;
}
private bool isPackageInitialized;
#endregion
#region IDisposable
/// <summary>
/// Clean up all events and references
/// </summary>
private void Dispose(bool disposing)
{
if (_Disposed || !disposing)
{
return;
}
// Stop and dispose the debounce timer
if (_LayoutChangedDebounceTimer != null)
{
_LayoutChangedDebounceTimer.Stop();
_LayoutChangedDebounceTimer.Tick -= OnLayoutChangedDebounceTimerTick;
_LayoutChangedDebounceTimer = null;
}
CBETagPackage.Instance?.PackageOptionChanged -= OnPackageOptionChanged;
if (_OutliningManager != null)
{
_OutliningManager.RegionsChanged -= OnOutliningRegionsChanged;
}
_TextView?.LayoutChanged -= OnTextViewLayoutChanged;
_TextView?.Caret?.PositionChanged -= Caret_PositionChanged;
_TextView?.TextBuffer?.Changed -= TextBuffer_Changed;
_Disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
#region visibility of tags
/// <summary>
/// Checks if a tag's header is visible
/// </summary>
/// <param name="start">Start position of code block</param>
/// <param name="end">End position of code block</param>
/// <param name="visibleSpan">the visible span in the textview</param>
/// <param name="snapshot">reference to text snapshot. Used for caret check</param>
/// <returns>true if the tag is visible (or if all tags are shown)</returns>
private bool IsTagVisible(int start, int end, Span? visibleSpan, ITextSnapshot snapshot)
{
// Always check if caret is at the closing bracket position first
if (_TextView != null)
{
var caretIndex = _TextView.Caret.Position.BufferPosition.Position;
#if DEBUG
System.Diagnostics.Debug.WriteLine($"IsTagVisible: caretIndex={caretIndex}, end={end}, end+1={end + 1}, start={start}");
#endif
// Hide tag if caret is at the closing bracket or right after it (where the tag is placed)
if (caretIndex == end || caretIndex == end + 1)
{
#if DEBUG
System.Diagnostics.Debug.WriteLine($" -> Hiding tag: caret at closing bracket position");
#endif
return false;
}
}
// Check general condition for visibility mode
if (CBETagPackage.CBEVisibilityMode == (int)VisibilityModes.Always || !visibleSpan.HasValue)
{
#if DEBUG
System.Diagnostics.Debug.WriteLine($" -> Showing tag: Always mode or no visible span");
#endif
return true;
}
// Check non-visible span
var val = visibleSpan.Value;
if (!(start < val.Start && end >= val.Start && end <= val.End))
{
#if DEBUG
System.Diagnostics.Debug.WriteLine($" -> Hiding tag: not in visible span");
#endif
return false;
}
// Check if caret is in this line
if (_TextView == null)
{
return true;
}
var caretIdx = _TextView.Caret.Position.BufferPosition.Position;
var lineStart = Math.Min(caretIdx, end);
var lineEnd = Math.Max(caretIdx, end);
// Same line -> not visible
if (lineStart == lineEnd)
{
#if DEBUG
System.Diagnostics.Debug.WriteLine($" -> Hiding tag: same line (lineStart == lineEnd)");
#endif
return false;
}
// hide tag if caret is in same line
if (lineStart >= 0 && lineEnd <= snapshot.Length)
{
string line = snapshot.GetText(lineStart, lineEnd - lineStart);
if (!line.Contains('\n'))
{
#if DEBUG
System.Diagnostics.Debug.WriteLine($" -> Hiding tag: caret on same line (no newline between caret and end)");
#endif
return false;
}
}
#if DEBUG
System.Diagnostics.Debug.WriteLine($" -> Showing tag");
#endif
return true;
}
/// <summary>
/// Returns the visible span for the given textview
/// </summary>
private Span? GetVisibleSpan(ITextView textView)
{
ITextViewLineCollection lines = textView?.TextViewLines;
int lineCount = lines?.Count ?? 0;
if (lines == null || lineCount <= 2)
{
return null;
}
// Index 0 not yet visible
// Last index not visible, too
return Span.FromBounds(lines[1].Start, lines[lineCount - 2].End);
}
#endregion
#region TextView scrolling
private void OnTextViewLayoutChanged(object sender, TextViewLayoutChangedEventArgs e)
{
#if DEBUG
System.Diagnostics.Debug.WriteLine($"=== OnTextViewLayoutChanged ===");
System.Diagnostics.Debug.WriteLine($" TranslatedLines: {e.TranslatedLines.Count}");
System.Diagnostics.Debug.WriteLine($" NewOrReformattedLines: {e.NewOrReformattedLines.Count}");
#endif
// get new visible span
var visibleSpan = GetVisibleSpan(_TextView);
if (!visibleSpan.HasValue)
{
#if DEBUG
System.Diagnostics.Debug.WriteLine($" -> No visible span, returning");
#endif
return;
}
#if DEBUG
System.Diagnostics.Debug.WriteLine($" New visible span: {visibleSpan.Value.Start}-{visibleSpan.Value.End}");
if (_VisibleSpan.HasValue)
{
System.Diagnostics.Debug.WriteLine($" Old visible span: {_VisibleSpan.Value.Start}-{_VisibleSpan.Value.End}");
}
else
{
System.Diagnostics.Debug.WriteLine($" Old visible span: (null)");
}
#endif
// only if new visible span is different from old
if (_VisibleSpan.HasValue &&
_VisibleSpan.Value.Start == visibleSpan.Value.Start &&
_VisibleSpan.Value.End >= visibleSpan.Value.End)
{
#if DEBUG
System.Diagnostics.Debug.WriteLine($" -> Visible span unchanged, returning");
#endif
return;
}
// Calculate the span to invalidate
var newSpan = visibleSpan.Value;
Span spanToInvalidate;
if (!_VisibleSpan.HasValue)
{
spanToInvalidate = newSpan;
#if DEBUG
System.Diagnostics.Debug.WriteLine($" -> First time, will invalidate new span: {newSpan.Start}-{newSpan.End}");
#endif
}
else
{
var oldSpan = _VisibleSpan.Value;
// invalidate two spans if old and new do not overlap
if (newSpan.Start > oldSpan.End || newSpan.End < oldSpan.Start)
{
// Join both spans into one larger span
spanToInvalidate = Span.FromBounds(
Math.Min(newSpan.Start, oldSpan.Start),
Math.Max(newSpan.End, oldSpan.End));
#if DEBUG
System.Diagnostics.Debug.WriteLine($" -> No overlap, will invalidate joined span");
System.Diagnostics.Debug.WriteLine($" New: {newSpan.Start}-{newSpan.End}");
System.Diagnostics.Debug.WriteLine($" Old: {oldSpan.Start}-{oldSpan.End}");
System.Diagnostics.Debug.WriteLine($" Joined: {spanToInvalidate.Start}-{spanToInvalidate.End}");
#endif
}
else
{
// invalidate one big span (old and new joined)
spanToInvalidate = newSpan.Join(oldSpan);
#if DEBUG
System.Diagnostics.Debug.WriteLine($" -> Overlap detected, will invalidate joined span: {spanToInvalidate.Start}-{spanToInvalidate.End}");
#endif
}
}
// Update the visible span
_VisibleSpan = visibleSpan;
// Store the span to invalidate and restart debounce timer
_PendingInvalidateSpan = spanToInvalidate;
_LayoutChangedDebounceTimer.Stop();
_LayoutChangedDebounceTimer.Start();
#if DEBUG
System.Diagnostics.Debug.WriteLine($" -> Debounce timer started/restarted");
System.Diagnostics.Debug.WriteLine($"=== End OnTextViewLayoutChanged ===");
#endif
}
/// <summary>
/// Handles the debounce timer tick event to invalidate the pending span
/// </summary>
private void OnLayoutChangedDebounceTimerTick(object sender, EventArgs e)
{
_LayoutChangedDebounceTimer.Stop();
if (!_PendingInvalidateSpan.HasValue)
{
return;