Welcome to mirror list, hosted at ThFree Co, Russian Federation.

BufferGraph.cs « Projection « TextModel « Impl « Text « src - github.com/microsoft/vs-editor-api.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: da4d4ebb19e9281b8d67a307f54509af0b1732d7 (plain)
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
//
//  Copyright (c) Microsoft Corporation. All rights reserved.
//  Licensed under the MIT License. See License.txt in the project root for license information.
//
// This file contain implementations details that are subject to change without notice.
// Use at your own risk.
//
namespace Microsoft.VisualStudio.Text.Projection.Implementation
{
    using System;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using Microsoft.VisualStudio.Text;
    using Microsoft.VisualStudio.Text.Implementation;
    using Microsoft.VisualStudio.Text.Utilities;
    using Strings = Microsoft.VisualStudio.Text.Implementation.Strings;

    partial class BufferGraph : IBufferGraph
    {
        #region Private members
        private readonly ITextBuffer topBuffer;
        private readonly GuardedOperations guardedOperations;
        internal Dictionary<ITextBuffer, FrugalList<IProjectionBufferBase>> importingProjectionBufferMap = new Dictionary<ITextBuffer, FrugalList<IProjectionBufferBase>>();
        internal List<WeakEventHookForBufferGraph> eventHooks = new List<WeakEventHookForBufferGraph>();
        #endregion

        #region Construction
        public BufferGraph(ITextBuffer topBuffer, GuardedOperations guardedOperations)
        {
            if (topBuffer == null)
            {
                throw new ArgumentNullException(nameof(topBuffer));
            }
            if (guardedOperations == null)
            {
                throw new ArgumentNullException(nameof(guardedOperations));
            }

            this.topBuffer = topBuffer;
            this.guardedOperations = guardedOperations;

            this.importingProjectionBufferMap.Add(topBuffer, null);
            // The top buffer has no targets, but it is put here so membership in this map can be used uniformly
            // to determine whether a buffer is in the buffer graph

            // Subscribe to content type changed events on the toplevel buffer
            this.eventHooks.Add(new WeakEventHookForBufferGraph(this, topBuffer));

            IProjectionBufferBase projectionBufferBase = topBuffer as IProjectionBufferBase;
            if (projectionBufferBase != null)
            {
                IList<ITextBuffer> sourceBuffers = projectionBufferBase.SourceBuffers;
                FrugalList<ITextBuffer> dontCare = new FrugalList<ITextBuffer>();
                foreach (ITextBuffer sourceBuffer in sourceBuffers)
                {
                    AddSourceBuffer(projectionBufferBase, sourceBuffer, dontCare);
                }
            }
        }
        #endregion

        #region Buffers
        public ITextBuffer TopBuffer
        {
            get { return this.topBuffer; }
        }

        public Collection<ITextBuffer> GetTextBuffers(Predicate<ITextBuffer> match)
        {
            if (match == null)
            {
                throw new ArgumentNullException(nameof(match));
            }
            FrugalList<ITextBuffer> buffers = new FrugalList<ITextBuffer>();
            foreach (ITextBuffer buffer in this.importingProjectionBufferMap.Keys)
            {
                if (match(buffer))
                {
                    buffers.Add(buffer);
                }
            }
            return new Collection<ITextBuffer>(buffers);
        }
        #endregion

        #region Mapping Point/Span Factories
        public IMappingPoint CreateMappingPoint(SnapshotPoint point, PointTrackingMode trackingMode)
        {
            return new MappingPoint(point, trackingMode, this);
        }

        public IMappingSpan CreateMappingSpan(SnapshotSpan span, SpanTrackingMode trackingMode)
        {
            return new MappingSpan(span, trackingMode, this);
        }
        #endregion

        #region Point Mapping
        public SnapshotPoint? MapDownToFirstMatch(SnapshotPoint position, PointTrackingMode trackingMode, Predicate<ITextSnapshot> match, PositionAffinity affinity)
        {
            if (position.Snapshot == null)
            {
                throw new ArgumentNullException(nameof(position));
            }
            if (trackingMode < PointTrackingMode.Positive || trackingMode > PointTrackingMode.Negative)
            {
                throw new ArgumentOutOfRangeException(nameof(trackingMode));
            }
            if (match == null)
            {
                throw new ArgumentNullException(nameof(match));
            }
            if (affinity < PositionAffinity.Predecessor || affinity > PositionAffinity.Successor)
            {
                throw new ArgumentOutOfRangeException(nameof(affinity));
            }
            if (!this.importingProjectionBufferMap.ContainsKey(position.Snapshot.TextBuffer))
            {
                return null;
            }

            ITextBuffer currentBuffer = position.Snapshot.TextBuffer;
            ITextSnapshot currentSnapshot = currentBuffer.CurrentSnapshot;
            int currentPosition = position.TranslateTo(currentSnapshot, trackingMode).Position;
            while (!match(currentSnapshot))
            {
                IProjectionBufferBase projBuffer = currentBuffer as IProjectionBufferBase;
                if (projBuffer == null)
                {
                    return null;
                }
                IProjectionSnapshot projSnap = projBuffer.CurrentSnapshot;
                if (projSnap.SourceSnapshots.Count == 0)
                {
                    return null;
                }
                SnapshotPoint currentPoint = projSnap.MapToSourceSnapshot(currentPosition, affinity);
                currentPosition = currentPoint.Position;
                currentSnapshot = currentPoint.Snapshot;
                currentBuffer = currentSnapshot.TextBuffer;
            }
            return new SnapshotPoint(currentSnapshot, currentPosition);
        }

        public SnapshotPoint? MapDownToInsertionPoint(SnapshotPoint position, PointTrackingMode trackingMode, Predicate<ITextSnapshot> match)
        {
            if (position.Snapshot == null)
            {
                throw new ArgumentNullException(nameof(position));
            }
            if (trackingMode < PointTrackingMode.Positive || trackingMode > PointTrackingMode.Negative)
            {
                throw new ArgumentOutOfRangeException(nameof(trackingMode));
            }
            if (match == null)
            {
                throw new ArgumentNullException(nameof(match));
            }

            ITextBuffer currentBuffer = position.Snapshot.TextBuffer;
            int currentPosition = position.TranslateTo(currentBuffer.CurrentSnapshot, trackingMode);
            ITextSnapshot currentSnapshot = currentBuffer.CurrentSnapshot;
            while (!match(currentSnapshot))
            {
                IProjectionBufferBase projBuffer = currentBuffer as IProjectionBufferBase;
                if (projBuffer == null)
                {
                    return null;
                }
                IProjectionSnapshot projSnap = projBuffer.CurrentSnapshot;
                if (projSnap.SourceSnapshots.Count == 0)
                {
                    return null;
                }
                SnapshotPoint currentPoint = projSnap.MapToSourceSnapshot(currentPosition);
                currentPosition = currentPoint.Position;
                currentSnapshot = currentPoint.Snapshot;
                currentBuffer = currentSnapshot.TextBuffer;
            }
            return new SnapshotPoint(currentSnapshot, currentPosition);
        }

        public SnapshotPoint? MapDownToBuffer(SnapshotPoint position, PointTrackingMode trackingMode, ITextBuffer targetBuffer, PositionAffinity affinity)
        {
            if (position.Snapshot == null)
            {
                throw new ArgumentNullException(nameof(position));
            }
            if (trackingMode < PointTrackingMode.Positive || trackingMode > PointTrackingMode.Negative)
            {
                throw new ArgumentOutOfRangeException(nameof(trackingMode));
            }
            if (targetBuffer == null)
            {
                throw new ArgumentNullException(nameof(targetBuffer));
            }
            if (affinity < PositionAffinity.Predecessor || affinity > PositionAffinity.Successor)
            {
                throw new ArgumentOutOfRangeException(nameof(affinity));
            }

            ITextBuffer currentBuffer = position.Snapshot.TextBuffer;
            ITextSnapshot currentSnapshot = currentBuffer.CurrentSnapshot;
            int currentPosition = position.TranslateTo(currentSnapshot, trackingMode).Position;

            while (currentBuffer != targetBuffer)
            {
                IProjectionBufferBase projBuffer = currentBuffer as IProjectionBufferBase;
                if (projBuffer == null)
                {
                    return null;
                }
                IProjectionSnapshot projSnap = projBuffer.CurrentSnapshot;
                if (projSnap.SourceSnapshots.Count == 0)
                {
                    return null;
                }
                SnapshotPoint currentPoint = projSnap.MapToSourceSnapshot(currentPosition, affinity);
                currentPosition = currentPoint.Position;
                currentSnapshot = currentPoint.Snapshot;
                currentBuffer = currentSnapshot.TextBuffer;
            }

            return new SnapshotPoint(currentSnapshot, currentPosition);
        }

        public SnapshotPoint? MapDownToSnapshot(SnapshotPoint position, PointTrackingMode trackingMode, ITextSnapshot targetSnapshot, PositionAffinity affinity)
        {
            if (targetSnapshot == null)
            {
                throw new ArgumentNullException(nameof(targetSnapshot));
            }

            SnapshotPoint? result = MapDownToBuffer(position, trackingMode, targetSnapshot.TextBuffer, affinity);
            if (result.HasValue && (result.Value.Snapshot != targetSnapshot))
            {
                result = result.Value.TranslateTo(targetSnapshot, trackingMode);
            }

            return result;
        }

        public SnapshotPoint? MapUpToBuffer(SnapshotPoint point, PointTrackingMode trackingMode, PositionAffinity affinity, ITextBuffer targetBuffer)
        {
            return CheckedMapUpToBuffer(point, trackingMode, snapshot => (snapshot.TextBuffer == targetBuffer), affinity);
        }


        public SnapshotPoint? MapUpToSnapshot(SnapshotPoint position, PointTrackingMode trackingMode, PositionAffinity affinity, ITextSnapshot targetSnapshot)
        {
            if (targetSnapshot == null)
            {
                throw new ArgumentNullException(nameof(targetSnapshot));
            }

            SnapshotPoint? result = MapUpToBuffer(position, trackingMode, affinity, targetSnapshot.TextBuffer);
            if (result.HasValue && (result.Value.Snapshot != targetSnapshot))
            {
                result = result.Value.TranslateTo(targetSnapshot, trackingMode);
            }

            return result;
        }

        public SnapshotPoint? MapUpToFirstMatch(SnapshotPoint point, PointTrackingMode trackingMode, Predicate<ITextSnapshot> match, PositionAffinity affinity)
        {
            if (match == null)
            {
                throw new ArgumentNullException(nameof(match));
            }
            return CheckedMapUpToBuffer(point, trackingMode, match, affinity);
        }

        private SnapshotPoint? CheckedMapUpToBuffer(SnapshotPoint point, PointTrackingMode trackingMode, Predicate<ITextSnapshot> match, PositionAffinity affinity)
        {
            if (point.Snapshot == null)
            {
                throw new ArgumentNullException(nameof(point));
            }
            if (trackingMode < PointTrackingMode.Positive || trackingMode > PointTrackingMode.Negative)
            {
                throw new ArgumentOutOfRangeException(nameof(trackingMode));
            }
            if (affinity < PositionAffinity.Predecessor || affinity > PositionAffinity.Successor)
            {
                throw new ArgumentOutOfRangeException(nameof(affinity));
            }

            if (!this.importingProjectionBufferMap.ContainsKey(point.Snapshot.TextBuffer))
            {
                return null;
            }
            else
            {
                SnapshotPoint currentPoint = point.TranslateTo(point.Snapshot.TextBuffer.CurrentSnapshot, trackingMode);
                return MapUpToBufferGuts(currentPoint, affinity, match);
            }
        }

        private SnapshotPoint? MapUpToBufferGuts(SnapshotPoint currentPoint, PositionAffinity affinity, Predicate<ITextSnapshot> match)
        {
            if (match(currentPoint.Snapshot))
            {
                return currentPoint;
            }
            FrugalList<IProjectionBufferBase> targetBuffers = this.importingProjectionBufferMap[currentPoint.Snapshot.TextBuffer];
            if (targetBuffers != null)  // targetBuffers will be null if we fell off the top
            {
                foreach (IProjectionBufferBase projBuffer in targetBuffers)
                {
                    SnapshotPoint? position = projBuffer.CurrentSnapshot.MapFromSourceSnapshot(currentPoint, affinity);
                    if (position.HasValue)
                    {
                        position = MapUpToBufferGuts(position.Value, affinity, match);
                        if (position.HasValue)
                        {
                            return position;
                        }
                    }
                }
            }
            return null;
        }
        #endregion

        #region Span Mapping
        public NormalizedSnapshotSpanCollection MapDownToFirstMatch(SnapshotSpan span, SpanTrackingMode trackingMode, Predicate<ITextSnapshot> match)
        {
            if (span.Snapshot == null)
            {
                throw new ArgumentNullException(nameof(span));
            }
            if (trackingMode < SpanTrackingMode.EdgeExclusive || trackingMode > SpanTrackingMode.EdgeNegative)
            {
                throw new ArgumentOutOfRangeException(nameof(trackingMode));
            }
            if (match == null)
            {
                throw new ArgumentNullException(nameof(match));
            }

            if (!this.importingProjectionBufferMap.ContainsKey(span.Snapshot.TextBuffer))
            {
                return NormalizedSnapshotSpanCollection.Empty;
            }

            ITextBuffer currentBuffer = span.Snapshot.TextBuffer;
            SnapshotSpan currentTopSpan = span.TranslateTo(currentBuffer.CurrentSnapshot, trackingMode);

            if (match(currentBuffer.CurrentSnapshot))
            {
                return new NormalizedSnapshotSpanCollection(currentTopSpan);
            }
            else if (!(currentBuffer is IProjectionBufferBase))
            {
                return NormalizedSnapshotSpanCollection.Empty;
            }
            else
            {
                FrugalList<Span> targetSpans = new FrugalList<Span>();
                FrugalList<SnapshotSpan> spans = new FrugalList<SnapshotSpan>() { currentTopSpan };
                ITextSnapshot chosenSnapshot = null;
                do
                {
                    spans = MapDownOneLevel(spans, match, ref chosenSnapshot, ref targetSpans);
                } while (spans.Count > 0);
                return chosenSnapshot == null ? NormalizedSnapshotSpanCollection.Empty : new NormalizedSnapshotSpanCollection(chosenSnapshot, targetSpans);
            }
        }

        public NormalizedSnapshotSpanCollection MapDownToBuffer(SnapshotSpan span, SpanTrackingMode trackingMode, ITextBuffer targetBuffer)
        {
            if (targetBuffer == null)
            {
                throw new ArgumentNullException(nameof(targetBuffer));
            }

            if (!this.importingProjectionBufferMap.ContainsKey(targetBuffer))
            {
                return NormalizedSnapshotSpanCollection.Empty;
            }
            else
            {
                return MapDownToFirstMatch(span, trackingMode, snapshot => (snapshot.TextBuffer == targetBuffer));
            }
        }

        public NormalizedSnapshotSpanCollection MapDownToSnapshot(SnapshotSpan span, SpanTrackingMode trackingMode, ITextSnapshot targetSnapshot)
        {
            if (targetSnapshot == null)
            {
                throw new ArgumentNullException(nameof(targetSnapshot));
            }

            NormalizedSnapshotSpanCollection results = MapDownToBuffer(span, trackingMode, targetSnapshot.TextBuffer);
            if ((results.Count > 0) && (results[0].Snapshot != targetSnapshot))
            {
                FrugalList<SnapshotSpan> translatedSpans = new FrugalList<SnapshotSpan>();
                foreach (SnapshotSpan s in results)
                {
                    translatedSpans.Add(s.TranslateTo(targetSnapshot, trackingMode));
                }

                results = new NormalizedSnapshotSpanCollection(translatedSpans);
            }

            return results;
        }

        public NormalizedSnapshotSpanCollection MapUpToSnapshot(SnapshotSpan span, SpanTrackingMode trackingMode, ITextSnapshot targetSnapshot)
        {
            if (targetSnapshot == null)
            {
                throw new ArgumentNullException(nameof(targetSnapshot));
            }

            NormalizedSnapshotSpanCollection results = MapUpToBuffer(span, trackingMode, targetSnapshot.TextBuffer);
            if ((results.Count > 0) && (results[0].Snapshot != targetSnapshot))
            {
                FrugalList<SnapshotSpan> translatedSpans = new FrugalList<SnapshotSpan>();
                foreach (SnapshotSpan s in results)
                {
                    translatedSpans.Add(s.TranslateTo(targetSnapshot, trackingMode));
                }

                results = new NormalizedSnapshotSpanCollection(translatedSpans);
            }

            return results;
        }

        private static FrugalList<SnapshotSpan> MapDownOneLevel(FrugalList<SnapshotSpan> inputSpans, Predicate<ITextSnapshot> match, ref ITextSnapshot chosenSnapshot, ref FrugalList<Span> targetSpans)
        {
            FrugalList<SnapshotSpan> downSpans = new FrugalList<SnapshotSpan>();
            foreach (SnapshotSpan inputSpan in inputSpans)
            {
                IProjectionBufferBase projBuffer = (IProjectionBufferBase)inputSpan.Snapshot.TextBuffer;
                IProjectionSnapshot projSnap = projBuffer.CurrentSnapshot;
                if (projSnap.SourceSnapshots.Count > 0)
                {
                    IList<SnapshotSpan> mappedSpans = projSnap.MapToSourceSnapshots(inputSpan);
                    for (int s = 0; s < mappedSpans.Count; ++s)
                    {
                        SnapshotSpan mappedSpan = mappedSpans[s];
                        ITextBuffer mappedBuffer = mappedSpan.Snapshot.TextBuffer;
                        if (mappedBuffer.CurrentSnapshot == chosenSnapshot)
                        {
                            targetSpans.Add(mappedSpan.Span);
                        }
                        else if (chosenSnapshot == null && match(mappedBuffer.CurrentSnapshot))
                        {
                            chosenSnapshot = mappedBuffer.CurrentSnapshot;
                            targetSpans.Add(mappedSpan.Span);
                        }
                        else
                        {
                            IProjectionBufferBase mappedProjBuffer = mappedBuffer as IProjectionBufferBase;
                            if (mappedProjBuffer != null)
                            {
                                downSpans.Add(mappedSpan);
                            }
                        }
                    }
                }
            }
            return downSpans;
        }

        public NormalizedSnapshotSpanCollection MapUpToBuffer(SnapshotSpan span, SpanTrackingMode trackingMode, ITextBuffer targetBuffer)
        {
            if (!this.importingProjectionBufferMap.ContainsKey(targetBuffer))
            {
                return NormalizedSnapshotSpanCollection.Empty;
            }
            else
            {
                return CheckedMapUpToBuffer(span, trackingMode, snapshot => (snapshot.TextBuffer == targetBuffer));
            }
        }

        public NormalizedSnapshotSpanCollection MapUpToFirstMatch(SnapshotSpan span, SpanTrackingMode trackingMode, Predicate<ITextSnapshot> match)
        {
            if (match == null)
            {
                throw new ArgumentNullException(nameof(match));
            }
            return CheckedMapUpToBuffer(span, trackingMode, match);
        }

        public NormalizedSnapshotSpanCollection CheckedMapUpToBuffer(SnapshotSpan span, SpanTrackingMode trackingMode, Predicate<ITextSnapshot> match)
        {
            if (span.Snapshot == null)
            {
                throw new ArgumentNullException(nameof(span));
            }
            if (trackingMode < SpanTrackingMode.EdgeExclusive || trackingMode > SpanTrackingMode.EdgeNegative)
            {
                throw new ArgumentOutOfRangeException(nameof(trackingMode));
            }
            ITextBuffer buffer = span.Snapshot.TextBuffer;
            if (!this.importingProjectionBufferMap.ContainsKey(buffer))
            {
                return NormalizedSnapshotSpanCollection.Empty;
            }
            SnapshotSpan currentSpan = span.TranslateTo(buffer.CurrentSnapshot, trackingMode);
            if (match(buffer.CurrentSnapshot))
            {
                return new NormalizedSnapshotSpanCollection(currentSpan);
            }

            ITextSnapshot chosenSnapshot = null;
            FrugalList<Span> result = new FrugalList<Span>();
            FrugalList<SnapshotSpan> spans = new FrugalList<SnapshotSpan>() { currentSpan };
            do
            {
                spans = MapUpOneLevel(spans, ref chosenSnapshot, match, result);
            } while (spans.Count > 0);

            if (chosenSnapshot == null)
            {
                return NormalizedSnapshotSpanCollection.Empty;
            }
            else
            {
                return new NormalizedSnapshotSpanCollection(chosenSnapshot, result);
            }
        }

        private FrugalList<SnapshotSpan> MapUpOneLevel(FrugalList<SnapshotSpan> spans, ref ITextSnapshot chosenSnapshot, Predicate<ITextSnapshot> match, FrugalList<Span> topSpans)
        {
            FrugalList<SnapshotSpan> upSpans = new FrugalList<SnapshotSpan>();
            foreach (SnapshotSpan span in spans)
            {
                FrugalList<IProjectionBufferBase> targetBuffers;
                if (this.importingProjectionBufferMap.TryGetValue(span.Snapshot.TextBuffer, out targetBuffers))
                {
                    if (targetBuffers != null)  // make sure we don't fall off the top
                    {
                        foreach (IProjectionBufferBase projBuffer in targetBuffers)
                        {
                            IList<Span> projSpans = projBuffer.CurrentSnapshot.MapFromSourceSnapshot(span);
                            if (projBuffer.CurrentSnapshot == chosenSnapshot)
                            {
                                topSpans.AddRange(projSpans);
                            }
                            else if (chosenSnapshot == null && match(projBuffer.CurrentSnapshot))
                            {
                                chosenSnapshot = projBuffer.CurrentSnapshot;
                                topSpans.AddRange(projSpans);
                            }
                            else
                            {
                                foreach (Span projSpan in projSpans)
                                {
                                    upSpans.Add(new SnapshotSpan(projBuffer.CurrentSnapshot, projSpan));
                                }
                            }
                        }
                    }
                }
            }
            return upSpans;
        }
        #endregion

        #region Event Handling
        private class GraphEventRaiser : BaseBuffer.ITextEventRaiser
        {
            private BufferGraph graph;
            private GraphBuffersChangedEventArgs args;

            public GraphEventRaiser(BufferGraph graph, GraphBuffersChangedEventArgs args)
            {
                this.graph = graph;
                this.args = args;
            }

            public void RaiseEvent(BaseBuffer baseBuffer, bool immediate)
            {
                this.graph.RaiseGraphBuffersChanged(this.args);
            }

            public bool HasPostEvent
            {
                get { return false; }
            }
        }

        public void RaiseGraphBuffersChanged(GraphBuffersChangedEventArgs args)
        {
            var listeners = GraphBuffersChanged;
            if (listeners != null)
            {
                this.guardedOperations.RaiseEvent(this, listeners, args);
            }
        }

        private void SourceBuffersChanged(object sender, ProjectionSourceBuffersChangedEventArgs e)
        {
            IProjectionBufferBase projBuffer = (IProjectionBufferBase)sender;
            FrugalList<ITextBuffer> addedToGraphBuffers = new FrugalList<ITextBuffer>();
            FrugalList<ITextBuffer> removedFromGraphBuffers = new FrugalList<ITextBuffer>();

            foreach (ITextBuffer addedBuffer in e.AddedBuffers)
            {
                AddSourceBuffer(projBuffer, addedBuffer, addedToGraphBuffers);
            }

            foreach (ITextBuffer removedBuffer in e.RemovedBuffers)
            {
                RemoveSourceBuffer(projBuffer, removedBuffer, removedFromGraphBuffers);
            }

            if (addedToGraphBuffers.Count > 0 || removedFromGraphBuffers.Count > 0)
            {
                var listeners = GraphBuffersChanged;
                if (listeners != null)
                {
                    ((BaseBuffer)projBuffer).group.EnqueueEvents
                        (new GraphEventRaiser(this, new GraphBuffersChangedEventArgs(addedToGraphBuffers, removedFromGraphBuffers)), null);
                }
            }
        }

        private void AddSourceBuffer(IProjectionBufferBase projBuffer, ITextBuffer sourceBuffer, FrugalList<ITextBuffer> addedToGraphBuffers)
        {
            bool firstEncounter = false;
            FrugalList<IProjectionBufferBase> importingProjectionBuffers;
            if (!this.importingProjectionBufferMap.TryGetValue(sourceBuffer, out importingProjectionBuffers))
            {
                // sourceBuffer is new to this buffer graph
                addedToGraphBuffers.Add(sourceBuffer);
                firstEncounter = true;

                importingProjectionBuffers = new FrugalList<IProjectionBufferBase>();
                this.importingProjectionBufferMap.Add(sourceBuffer, importingProjectionBuffers);

                this.eventHooks.Add(new WeakEventHookForBufferGraph(this, sourceBuffer));
            }
            importingProjectionBuffers.Add(projBuffer);

            if (firstEncounter)
            {
                IProjectionBufferBase addedProjBufferBase = sourceBuffer as IProjectionBufferBase;
                if (addedProjBufferBase != null)
                {
                    foreach (ITextBuffer furtherSourceBuffer in addedProjBufferBase.SourceBuffers)
                    {
                        AddSourceBuffer(addedProjBufferBase, furtherSourceBuffer, addedToGraphBuffers);
                    }
                }
            }
        }

        private void RemoveSourceBuffer(IProjectionBufferBase projBuffer, ITextBuffer sourceBuffer, FrugalList<ITextBuffer> removedFromGraphBuffers)
        {
            IList<IProjectionBufferBase> importingProjectionBuffers = this.importingProjectionBufferMap[sourceBuffer];
            importingProjectionBuffers.Remove(projBuffer);
            if (importingProjectionBuffers.Count == 0)
            {
                removedFromGraphBuffers.Add(sourceBuffer);
                this.importingProjectionBufferMap.Remove(sourceBuffer);

                for (int i = 0; (i < this.eventHooks.Count); ++i)
                {
                    if (this.eventHooks[i].SourceBuffer == sourceBuffer)
                    {
                        this.eventHooks[i].UnsubscribeFromSourceBuffer();
                        this.eventHooks.RemoveAt(i);
                        break;
                    }
                }

                IProjectionBufferBase removedProjBufferBase = sourceBuffer as IProjectionBufferBase;
                if (removedProjBufferBase != null)
                {
                    foreach (ITextBuffer furtherSourceBuffer in removedProjBufferBase.SourceBuffers)
                    {
                        RemoveSourceBuffer(removedProjBufferBase, furtherSourceBuffer, removedFromGraphBuffers);
                    }
                }
            }
        }

        protected void ContentTypeChanged(object sender, ContentTypeChangedEventArgs args)
        {
            // we do not subscribe to the immediate form of the sender's content type changed
            // event, so we do not need to queue this event
            var handler = GraphBufferContentTypeChanged;
            if (handler != null)
            {
                handler(this, new GraphBufferContentTypeChangedEventArgs((ITextBuffer)sender, args.BeforeContentType, args.AfterContentType));
            }
        }

        public event EventHandler<GraphBuffersChangedEventArgs> GraphBuffersChanged;
        public event EventHandler<GraphBufferContentTypeChangedEventArgs> GraphBufferContentTypeChanged;

        #endregion

        /// <summary>
        /// This an equivalent of the WeakEventHook, but for the buffer graph instead of being for a projection buffer.
        /// </summary>
        internal class WeakEventHookForBufferGraph
        {
            private readonly WeakReference<BufferGraph> _targetGraph;
            private ITextBuffer _sourceBuffer;

            public WeakEventHookForBufferGraph(BufferGraph targetGraph, ITextBuffer sourceBuffer)
            {
                _targetGraph = new WeakReference<BufferGraph>(targetGraph);
                _sourceBuffer = sourceBuffer;

                sourceBuffer.ContentTypeChanged += OnSourceBufferContentTypeChanged;
                ProjectionBuffer projectionBuffer = sourceBuffer as ProjectionBuffer;
                if (projectionBuffer != null)
                {
                    projectionBuffer.SourceBuffersChangedImmediate += OnSourceBuffersChanged;
                }
            }

            public ITextBuffer SourceBuffer { get { return _sourceBuffer; } }

            public BufferGraph GetTargetGraph()  // Not a property since it has side-effects
            {
                BufferGraph targetGraph;
                if (_targetGraph.TryGetTarget(out targetGraph))
                {
                    return targetGraph;
                }

                // The target buffer that was listening to events on the source buffer has died (no one was using it).
                // Dead buffers tell no tales so they get to stop listening to tales as well. Unsubscribe from the
                // events it hooked on the source buffer.
                this.UnsubscribeFromSourceBuffer();
                return null;
            }

            private void OnSourceBufferContentTypeChanged(object sender, ContentTypeChangedEventArgs e)
            {
                BufferGraph targetGraph = this.GetTargetGraph();
                if (targetGraph != null)
                {
                    targetGraph.ContentTypeChanged(sender, e);
                }
            }

            private void OnSourceBuffersChanged(object sender, ProjectionSourceBuffersChangedEventArgs e)
            {
                BufferGraph targetGraph = this.GetTargetGraph();
                if (targetGraph != null)
                {
                    targetGraph.SourceBuffersChanged(sender, e);
                }
            }

            public void UnsubscribeFromSourceBuffer()
            {
                if (_sourceBuffer != null)
                {
                    _sourceBuffer.ContentTypeChanged -= OnSourceBufferContentTypeChanged;
                    ProjectionBuffer projectionBuffer = _sourceBuffer as ProjectionBuffer;
                    if (projectionBuffer != null)
                    {
                        projectionBuffer.SourceBuffersChangedImmediate -= OnSourceBuffersChanged;
                    }

                    _sourceBuffer = null;
                }
            }
        }
    }
}