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

BaseBuffer.cs « TextModel « Impl « Text « src - github.com/microsoft/vs-editor-api.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 4d4ed82e5cbbe87f4feb11cdb1c2dd946a6ed169 (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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
//
//  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.Implementation
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Threading;
    using Microsoft.VisualStudio.Utilities;
    using Microsoft.VisualStudio.Text.Differencing;
    using Microsoft.VisualStudio.Text.Utilities;
    using Microsoft.VisualStudio.Threading;
    using System.Threading.Tasks;

    internal abstract partial class BaseBuffer : ITextBuffer2
    {
        #region ITextEventRaiser Interface
        /// <summary>
        /// Implemented internally to support a heterogeneous event queue.
        /// </summary>
        internal interface ITextEventRaiser
        {
            void RaiseEvent(BaseBuffer baseBuffer, bool immediate);
            bool HasPostEvent { get; }
        }
        #endregion

        #region TextContentChangedEventRaiser Class
        /// <summary>
        /// The agent that knows how to raise ordinary TextContent changed events.
        /// </summary>
        internal class TextContentChangedEventRaiser : ITextEventRaiser
        {
            private TextContentChangedEventArgs args;

            public TextContentChangedEventRaiser(ITextSnapshot beforeSnapshot,
                                                 ITextSnapshot afterSnapshot,
                                                 EditOptions options,
                                                 Object editTag)
            {
                args = new TextContentChangedEventArgs(beforeSnapshot, afterSnapshot, options, editTag);
            }

            public void RaiseEvent(BaseBuffer baseBuffer, bool immediate)
            {
                baseBuffer.RawRaiseEvent(args, immediate);
            }

            public bool HasPostEvent
            {
                get { return true; }
            }
        }
        #endregion

        #region TextBufferBaseEdit Class Definition
        /// <summary>
        /// Checking for edits already in progress and modifications on the proper thread.
        /// </summary>
        protected abstract class TextBufferBaseEdit : IDisposable
        {
            protected BaseBuffer baseBuffer;
            protected bool applied;
            protected bool canceled;

            public TextBufferBaseEdit(BaseBuffer baseBuffer)
            {
                this.baseBuffer = baseBuffer;
                if (!baseBuffer.CheckEditAccess())
                {
                    throw new InvalidOperationException(Strings.InvalidTextBufferEditThread);
                }
                if (baseBuffer.editInProgress)
                {
                    throw new InvalidOperationException(Strings.SimultaneousEdit);
                }
                baseBuffer.editInProgress = true;
                baseBuffer.group.BeginEdit();
            }

            public virtual void Cancel()
            {
                this.CancelApplication();
            }

            public virtual void CancelApplication()
            {
                if (!this.canceled)
                {
                    this.canceled = true;
                    this.baseBuffer.editInProgress = false;
                    this.baseBuffer.group.CancelEdit();
                }
            }

            public bool Canceled
            {
                get
                {
                    return this.canceled;
                }
            }

            public void Dispose()
            {
                if (!this.applied && !this.canceled)
                {
                    this.CancelApplication();
                }
                GC.SuppressFinalize(this);
            }
        }
        #endregion

        #region TextBufferEdit Class Definition
        /// <summary>
        /// Edit protocol checking.
        /// </summary>
        protected abstract partial class TextBufferEdit : TextBufferBaseEdit
        {
            protected ITextSnapshot originSnapshot;
            protected object editTag;

            public TextBufferEdit(BaseBuffer baseBuffer, ITextSnapshot snapshot, object editTag)
                : base(baseBuffer)
            {
                this.baseBuffer = baseBuffer;
                this.originSnapshot = snapshot;
                this.editTag = editTag;
            }

            public ITextSnapshot Snapshot
            {
                get { return this.originSnapshot; }
            }

            public ITextSnapshot Apply()
            {
                ITextSnapshot snapshot;
                try
                {
                    snapshot = PerformApply();
                }
                finally
                {
                    // TextBufferBaseEdit.Cancel may have been called via
                    // the cancellable Changing event. In that case, group.CancelEdit will
                    // have been called and canceled will be true.
                    if (!this.canceled)
                    {
                        this.baseBuffer.group.FinishEdit();
                    }
                }

                return snapshot;
            }

            protected abstract ITextSnapshot PerformApply();

            protected void CheckActive()
            {
                if (this.canceled)
                {
                    throw new InvalidOperationException(Strings.ContinueCanceledEdit);
                }
                if (this.applied)
                {
                    throw new InvalidOperationException(Strings.ReuseAppliedEdit);
                }
            }
        }
        #endregion

        #region Edit Class Definition
        /// <summary>
        /// Fundamental editing operations.
        /// </summary>
        protected abstract partial class Edit : TextBufferEdit, ITextEdit
        {
            private readonly int bufferLength;
            protected FrugalList<TextChange> changes;
            protected readonly EditOptions options;
            protected readonly int? reiteratedVersionNumber;
            private TextContentChangingEventArgs raisedChangingEventArgs;
            private Action cancelAction;
            private bool hasFailedChanges;

            protected Edit(BaseBuffer baseBuffer, ITextSnapshot originSnapshot, EditOptions options, int? reiteratedVersionNumber, Object editTag)
                : base(baseBuffer, originSnapshot, editTag)
            {
                this.bufferLength = originSnapshot.Length;
                this.changes = new FrugalList<TextChange>();
                this.options = options;
                this.reiteratedVersionNumber = reiteratedVersionNumber;
                this.raisedChangingEventArgs = null;
                this.cancelAction = null;
                this.hasFailedChanges = false;
            }

            public bool Insert(int position, string text)
            {
                CheckActive();
                if (position < 0 || position > this.bufferLength)
                {
                    throw new ArgumentOutOfRangeException("position");
                }
                if (text == null)
                {
                    throw new ArgumentNullException("text");
                }

                // Check for ReadOnly
                if (this.baseBuffer.IsReadOnlyImplementation(position, isEdit: true))
                {
                    this.hasFailedChanges = true;
                    return false;
                }

                if (text.Length != 0)
                {
                    this.changes.Add(TextChange.Create(position, string.Empty, text, this.originSnapshot));
                }
                return true;
            }

            public bool Insert(int position, char[] characterBuffer, int startIndex, int length)
            {
                CheckActive();
                if (position < 0 || position > this.bufferLength)
                {
                    throw new ArgumentOutOfRangeException("position");
                }
                if (characterBuffer == null)
                {
                    throw new ArgumentNullException("characterBuffer");
                }
                if (startIndex < 0 || startIndex > characterBuffer.Length)
                {
                    throw new ArgumentOutOfRangeException("startIndex");
                }
                if (length < 0 || startIndex + length > characterBuffer.Length)
                {
                    throw new ArgumentOutOfRangeException("length");
                }

                // Check for ReadOnly
                if (this.baseBuffer.IsReadOnlyImplementation(position, isEdit: true))
                {
                    this.hasFailedChanges = true;
                    return false;
                }

                if (length != 0)
                {
                    this.changes.Add(TextChange.Create(position, string.Empty, new string(characterBuffer, startIndex, length), this.originSnapshot));
                }
                return true;
            }

            public bool Replace(int startPosition, int charsToReplace, string replaceWith)
            {
                CheckActive();
                if (startPosition < 0 || startPosition > this.bufferLength)
                {
                    throw new ArgumentOutOfRangeException("startPosition");
                }
                if (charsToReplace < 0 || startPosition + charsToReplace > this.bufferLength)
                {
                    throw new ArgumentOutOfRangeException("charsToReplace");
                }
                if (replaceWith == null)
                {
                    throw new ArgumentNullException("replaceWith");
                }

                // Check for ReadOnly
                if (this.baseBuffer.IsReadOnlyImplementation(new Span(startPosition, charsToReplace), isEdit: true))
                {
                    this.hasFailedChanges = true;
                    return false;
                }

                if (charsToReplace != 0 || replaceWith.Length != 0)
                {
                    this.changes.Add(TextChange.Create(startPosition, DeletionChangeString(new Span(startPosition, charsToReplace)), replaceWith, this.originSnapshot));
                }
                return true;
            }

            public bool Replace(Span replaceSpan, string replaceWith)
            {
                CheckActive();
                if (replaceSpan.End > this.bufferLength)
                {
                    throw new ArgumentOutOfRangeException("replaceSpan");
                }
                if (replaceWith == null)
                {
                    throw new ArgumentNullException("replaceWith");
                }

                // Check for ReadOnly
                if (this.baseBuffer.IsReadOnlyImplementation(replaceSpan, isEdit: true))
                {
                    this.hasFailedChanges = true;
                    return false;
                }

                if (replaceSpan.Length != 0 || replaceWith.Length != 0)
                {
                    this.changes.Add(TextChange.Create(replaceSpan.Start, DeletionChangeString(replaceSpan), replaceWith, this.originSnapshot));
                }
                return true;
            }

            public bool Delete(int startPosition, int charsToDelete)
            {
                CheckActive();
                if (startPosition < 0 || startPosition > this.bufferLength)
                {
                    throw new ArgumentOutOfRangeException("startPosition");
                }
                if (charsToDelete < 0 || startPosition + charsToDelete > this.bufferLength)
                {
                    throw new ArgumentOutOfRangeException("charsToDelete");
                }

                // Check for ReadOnly
                if (this.baseBuffer.IsReadOnlyImplementation(new Span(startPosition, charsToDelete), isEdit: true))
                {
                    this.hasFailedChanges = true;
                    return false;
                }

                if (charsToDelete != 0)
                {
                    this.changes.Add(TextChange.Create(startPosition, DeletionChangeString(new Span(startPosition, charsToDelete)), StringRebuilder.Empty, this.originSnapshot));
                }
                return true;
            }

            public bool Delete(Span deleteSpan)
            {
                CheckActive();
                if (deleteSpan.End > this.bufferLength)
                {
                    throw new ArgumentOutOfRangeException("deleteSpan");
                }

                // Check for ReadOnly
                if (this.baseBuffer.IsReadOnlyImplementation(deleteSpan, isEdit: true))
                {
                    this.hasFailedChanges = true;
                    return false;
                }

                if (deleteSpan.Length != 0)
                {
                    this.changes.Add(TextChange.Create(deleteSpan.Start, DeletionChangeString(deleteSpan), StringRebuilder.Empty, this.originSnapshot));
                }
                return true;
            }

            private StringRebuilder DeletionChangeString(Span deleteSpan)
            {
                return BufferFactoryService.StringRebuilderFromSnapshotAndSpan(this.originSnapshot, deleteSpan);
            }

            /// <summary>
            /// Checks whether the edit on the buffer is allowed to continue.
            /// </summary>
            /// <param name="cancelationResponse">Additional action to perform if the edit itself is canceled.</param>
            public bool CheckForCancellation(Action cancelationResponse)
            {
                Debug.Assert(this.raisedChangingEventArgs == null, "just checking");

                // If no changes are being applied to this edit's buffer then there will be no new snapshot produced and
                // the Changed event won't be raised and so the cancelable Changing event should not be raised either.
                if (this.changes.Count == 0)
                {
                    return true;
                }

                if (this.raisedChangingEventArgs == null)
                {
                    this.cancelAction = cancelationResponse;
                    this.raisedChangingEventArgs = new TextContentChangingEventArgs(this.Snapshot, this.editTag, (args) =>
                    {
                        this.Cancel();
                    });
                    this.baseBuffer.RaiseChangingEvent(this.raisedChangingEventArgs);
                }
                this.canceled = this.raisedChangingEventArgs.Canceled;
                //Debug.Assert(!this.canceled || !this.applied, "an edit shouldn't be both canceled and applied");
                return !this.raisedChangingEventArgs.Canceled;
            }

            public override void Cancel()
            {
                base.Cancel();

                if (this.cancelAction != null)
                {
                    this.cancelAction();
                }
            }

            public bool HasEffectiveChanges
            {
                get
                {
                    return this.changes.Count > 0;
                }
            }

            public bool HasFailedChanges
            {
                get
                {
                    return this.hasFailedChanges;
                }
            }

            public override string ToString()
            {
                System.Text.StringBuilder builder = new System.Text.StringBuilder();
                for (int c = 0; c < this.changes.Count; ++c)
                {
                    TextChange change = this.changes[c];
                    builder.Append(change.ToString(brief: true));
                    if (c < this.changes.Count - 1)
                    {
                        builder.Append("\r\n");
                    }
                }
                return builder.ToString();
            }

            public void RecordMasterChangeOffset(int masterChangeOffset)
            {
                if (this.changes.Count == 0)
                {
                    throw new InvalidOperationException("Can't record a change offset without a change.");
                }

                this.changes[this.changes.Count - 1].RecordMasterChangeOffset(masterChangeOffset);
            }
        }
        #endregion // Edit Class Definition

        #region Read Only Region Edit Class Definition
        private sealed partial class ReadOnlyRegionEdit : TextBufferEdit, IReadOnlyRegionEdit
        {
            private List<IReadOnlyRegion> readOnlyRegionsToAdd = new List<IReadOnlyRegion>();
            private List<IReadOnlyRegion> readOnlyRegionsToRemove = new List<IReadOnlyRegion>();

            private int aggregateEnd = int.MinValue;
            private int aggregateStart = int.MaxValue;

            public ReadOnlyRegionEdit(BaseBuffer baseBuffer, ITextSnapshot originSnapshot, Object editTag)
                : base(baseBuffer, originSnapshot, editTag)
            {
            }

            protected override ITextSnapshot PerformApply()
            {
                CheckActive();

                this.applied = true;

                if ((this.readOnlyRegionsToAdd.Count > 0) || (this.readOnlyRegionsToRemove.Count > 0))
                {
                    if (this.readOnlyRegionsToAdd.Count > 0)
                    {
                        // We leave the read only regions collection on the buffer null
                        // since most buffers will never have a read only region. Since
                        // regions are being added, create it now.
                        if (this.baseBuffer.readOnlyRegions == null)
                        {
                            this.baseBuffer.readOnlyRegions = new FrugalList<IReadOnlyRegion>();
                        }

                        this.baseBuffer.readOnlyRegions.AddRange(this.readOnlyRegionsToAdd);
                    }

                    if (this.readOnlyRegionsToRemove.Count > 0)
                    {
                        // We've already verified that it makes sense to remove these read only
                        // regions, so just proceed without further checks.
                        foreach (IReadOnlyRegion readOnlyRegion in this.readOnlyRegionsToRemove)
                        {
                            this.baseBuffer.readOnlyRegions.Remove(readOnlyRegion);
                        }
                    }

                    // Save off the current state of the read only spans
                    this.baseBuffer.readOnlyRegionSpanCollection = new ReadOnlySpanCollection(this.baseBuffer.CurrentVersion, this.baseBuffer.readOnlyRegions);

                    ReadOnlyRegionsChangedEventRaiser raiser = 
                        new ReadOnlyRegionsChangedEventRaiser(new SnapshotSpan(this.baseBuffer.CurrentSnapshot, this.aggregateStart, this.aggregateEnd - this.aggregateStart));
                    this.baseBuffer.group.EnqueueEvents(raiser, this.baseBuffer);
                    // no immediate event for read only regions
                    this.baseBuffer.editInProgress = false;
                }
                else
                {
                    this.baseBuffer.editInProgress = false;
                }

                // no new snapshot
                return this.originSnapshot;
            }

            #region IReadOnlyRegionEdit Members

            public IReadOnlyRegion CreateReadOnlyRegion(Span span, SpanTrackingMode trackingMode, EdgeInsertionMode edgeInsertionMode)
            {
                return CreateDynamicReadOnlyRegion(span, trackingMode, edgeInsertionMode, callback: null);
            }

            public IReadOnlyRegion CreateDynamicReadOnlyRegion(Span span, SpanTrackingMode trackingMode, EdgeInsertionMode edgeInsertionMode, DynamicReadOnlyRegionQuery callback)
            {
                ReadOnlyRegion readOnlyRegion = new ReadOnlyRegion(this.baseBuffer.CurrentVersion, span, trackingMode, edgeInsertionMode, callback);

                readOnlyRegionsToAdd.Add(readOnlyRegion);

                this.aggregateStart = Math.Min(this.aggregateStart, span.Start);
                this.aggregateEnd = Math.Max(this.aggregateEnd, span.End);

                return readOnlyRegion;
            }

            public IReadOnlyRegion CreateReadOnlyRegion(Span span)
            {
                return CreateReadOnlyRegion(span, SpanTrackingMode.EdgeExclusive, EdgeInsertionMode.Allow);
            }

            public void RemoveReadOnlyRegion(IReadOnlyRegion readOnlyRegion)
            {
                // Throw if trying to remove a region if there aren't that many regions created.
                if (this.baseBuffer.readOnlyRegions == null)
                {
                    throw new InvalidOperationException(Strings.RemoveNoReadOnlyRegion);
                }

                // Throw if trying to remove a region from the wrong buffer
                if (this.readOnlyRegionsToRemove.Exists(delegate(IReadOnlyRegion match) { return !object.ReferenceEquals(match.Span.TextBuffer, this.baseBuffer); }))
                {
                    throw new InvalidOperationException(Strings.InvalidReadOnlyRegion);
                }

                this.readOnlyRegionsToRemove.Add(readOnlyRegion);

                Span regionSpan = readOnlyRegion.Span.GetSpan(this.baseBuffer.CurrentSnapshot);
                this.aggregateStart = Math.Min(this.aggregateStart, regionSpan.Start);
                this.aggregateEnd = Math.Max(this.aggregateEnd, regionSpan.End);
            }

            #endregion
        }
        #endregion // Read Only Region Edit Class Definition

        #region ContentType Edit Class Definition
        private sealed class ContentTypeEdit : TextBufferEdit, ISubordinateTextEdit
        {
            private IContentType _newContentType;

            public ContentTypeEdit(BaseBuffer baseBuffer, ITextSnapshot originSnapshot, Object editTag, IContentType newContentType)
                : base(baseBuffer, originSnapshot, editTag)
            {
                _newContentType = newContentType;
            }

            public ITextBuffer TextBuffer
            {
                get { return this.baseBuffer; }
            }

            protected override ITextSnapshot PerformApply()
            {
                CheckActive();

                this.applied = true;

                if (_newContentType != null)
                {
                    // we need to perform a group edit because any projection buffers that use this buffer will
                    // generate new snapshots as independent edits.
                    this.baseBuffer.group.PerformMasterEdit(this.baseBuffer, this, EditOptions.None, this.editTag);
                }
                else
                {
                    this.baseBuffer.editInProgress = false;
                }

                return this.baseBuffer.currentSnapshot;
            }

            public void PreApply()
            {
                // all the action is in FinalApply()
            }

            public void FinalApply()
            {
                IContentType beforeContentType = baseBuffer.contentType;
                this.baseBuffer.contentType = _newContentType;
                this.baseBuffer.SetCurrentVersionAndSnapshot(NormalizedTextChangeCollection.Empty);
                ITextEventRaiser raiser = new ContentTypeChangedEventRaiser(this.originSnapshot, baseBuffer.currentSnapshot, beforeContentType, baseBuffer.contentType, editTag);
                this.baseBuffer.group.EnqueueEvents(raiser, this.baseBuffer);
                raiser.RaiseEvent(this.baseBuffer, true);
                this.baseBuffer.editInProgress = false;
            }

            public bool CheckForCancellation(Action cancelAction)
            {
                // Not cancelable.
                return true;
            }

            public void RecordMasterChangeOffset(int masterChangeOffset)
            {
                throw new InvalidOperationException("Content type edits shouldn't have change offsets.");
            }
        }
        #endregion // IContentType Edit Class Definition

        #region Private members and construction
        private IContentType contentType;
        private PropertyCollection properties;
        private readonly Object syncLock = new Object();
        private Thread editThread;
        protected internal BufferGroup group;
        protected internal StringRebuilder builder;
        protected internal BaseSnapshot currentSnapshot;
        protected TextVersion currentVersion;
        private FrugalList<IReadOnlyRegion> readOnlyRegions;
        protected ReadOnlySpanCollection readOnlyRegionSpanCollection;
        protected internal bool editInProgress;
        protected internal ITextDifferencingService textDifferencingService;
        protected readonly GuardedOperations guardedOperations;

        private static bool eventTracing = false;
        private static int eventDepth = 0;

        protected BaseBuffer(IContentType contentType, int initialLength, ITextDifferencingService textDifferencingService, GuardedOperations guardedOperations)
        {
            // parameters are validated outside
            Debug.Assert(contentType != null);

            this.contentType = contentType;
            this.currentVersion = new TextVersion(this, new TextImageVersion(initialLength));
            // this.builder should be set in calling ctor
            this.textDifferencingService = textDifferencingService;
            this.guardedOperations = guardedOperations;
        }
        #endregion

        #region ITextBuffer members
        public IContentType ContentType
        {
            get { return this.contentType; }
        }

        public PropertyCollection Properties
        {
            get
            {
                if (this.properties == null)
                {
                    lock (this.syncLock)
                    {
                        if (this.properties == null)
                        {
                            this.properties = new PropertyCollection();
                        }
                    }
                }
                return this.properties;
            }
        }

        public ITextSnapshot CurrentSnapshot
        {
            get { return this.currentSnapshot; }
        }

        protected TextVersion CurrentVersion
        {
            get { return this.currentVersion; }
        }

        public abstract ITextEdit CreateEdit(EditOptions options, int? reiteratedVersionNumber, object editTag);

        public ITextEdit CreateEdit()
        {
            return CreateEdit(EditOptions.None, null, null);
        }

        public IReadOnlyRegionEdit CreateReadOnlyRegionEdit()
        {
            return CreateReadOnlyRegionEdit(null);
        }

        public IReadOnlyRegionEdit CreateReadOnlyRegionEdit(object editTag)
        {
            return new ReadOnlyRegionEdit(this, this.CurrentSnapshot, editTag);
        }

        public void ChangeContentType(IContentType newContentType, object editTag)
        {
            if (newContentType == null)
            {
                throw new ArgumentNullException("newContentType");
            }

            if (newContentType != this.contentType)
            {
                using (ContentTypeEdit edit = new ContentTypeEdit(this, this.currentSnapshot, editTag, newContentType))
                {
                    edit.Apply();
                }
            }
        }

        public bool EditInProgress
        {
            get { return this.editInProgress; }
        }

        public void TakeThreadOwnership()
        {
            lock (this.syncLock)
            {
                if (this.editThread != null && this.editThread != Thread.CurrentThread)
                {
                    throw new InvalidOperationException(Strings.InvalidBufferThreadOwnershipChange);
                }
                this.editThread = Thread.CurrentThread;
            }
        }

        public bool CheckEditAccess()
        {
            return this.editThread == null || this.editThread == Thread.CurrentThread;
        }

        protected abstract BaseSnapshot TakeSnapshot();
        #endregion

        #region ReadOnlyRegion support
        public bool IsReadOnly(int position)
        {
            return IsReadOnly(position, isEdit: false);
        }

        public bool IsReadOnly(int position, bool isEdit)
        {
            ReadOnlyQueryThreadCheck();
            if ((position < 0) || (position > this.currentSnapshot.Length))
            {
                throw new ArgumentOutOfRangeException("position");
            }

            return IsReadOnlyImplementation(position, isEdit);
        }

        public bool IsReadOnly(Span span)
        {
            return IsReadOnly(span, isEdit: false);
        }

        public bool IsReadOnly(Span span, bool isEdit)
        {
            ReadOnlyQueryThreadCheck();
            if (span.End > this.currentSnapshot.Length)
            {
                throw new ArgumentOutOfRangeException("span");
            }

            return IsReadOnlyImplementation(span, isEdit);
        }

        protected internal virtual bool IsReadOnlyImplementation(int position, bool isEdit)
        {
            if (this.readOnlyRegionSpanCollection == null)
            {
                return false;
            }
            return this.readOnlyRegionSpanCollection.IsReadOnly(position, this.currentSnapshot, isEdit);
        }

        protected internal virtual bool IsReadOnlyImplementation(Span span, bool isEdit)
        {
            if (this.readOnlyRegionSpanCollection == null)
            {
                return false;
            }
            return this.readOnlyRegionSpanCollection.IsReadOnly(span, this.currentSnapshot, isEdit);
        }

        public NormalizedSpanCollection GetReadOnlyExtents(Span span)
        {
            ReadOnlyQueryThreadCheck();
            if (span.End > this.CurrentSnapshot.Length)
            {
                throw new ArgumentOutOfRangeException("span");
            }
            return GetReadOnlyExtentsImplementation(span);
        }

        protected internal virtual NormalizedSpanCollection GetReadOnlyExtentsImplementation(Span span)
        {
            FrugalList<Span> spans = new FrugalList<Span>();

            if (this.readOnlyRegionSpanCollection != null)
            {
                foreach (ReadOnlySpan readOnlySpan in this.readOnlyRegionSpanCollection.QueryAllEffectiveReadOnlySpans(this.currentVersion))
                {
                    Span readOnlySpanSpan = readOnlySpan.GetSpan(this.currentSnapshot);
                    Span? overlapSpan = (readOnlySpanSpan == span) ? readOnlySpanSpan : readOnlySpanSpan.Overlap(span);
                    if (overlapSpan.HasValue)
                    {
                        spans.Add(overlapSpan.Value);
                    }
                }
            }

            return new NormalizedSpanCollection(spans);
        }

        private void ReadOnlyQueryThreadCheck()
        {
            if (!CheckEditAccess())
            {
                throw new InvalidOperationException(Strings.InvalidTextBufferEditThread);
            }
        }

        public event EventHandler<SnapshotSpanEventArgs> ReadOnlyRegionsChanged;

        protected class ReadOnlyRegionsChangedEventRaiser : ITextEventRaiser
        {
            private SnapshotSpan affectedSpan;

            public ReadOnlyRegionsChangedEventRaiser(SnapshotSpan affectedSpan)
            {
                this.affectedSpan = affectedSpan;
            }

            public void RaiseEvent(BaseBuffer baseBuffer, bool immediate)
            {
                // there is no immediate form of this event since it does not create a snapshot
                Debug.Assert(!immediate);
                EventHandler<SnapshotSpanEventArgs> handler = baseBuffer.ReadOnlyRegionsChanged;
                if (handler != null)
                {
                    var args = new SnapshotSpanEventArgs(affectedSpan);
                    baseBuffer.guardedOperations.RaiseEvent(baseBuffer, handler, args);
                }
            }

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

        #region IContentType change support
        public event EventHandler<ContentTypeChangedEventArgs> ContentTypeChanged;

        protected class ContentTypeChangedEventRaiser : ITextEventRaiser
        {
            #region Private Members
            ITextSnapshot beforeSnapshot;
            ITextSnapshot afterSnapshot;
            object editTag;
            IContentType beforeContentType;
            IContentType afterContentType;
            #endregion

            public ContentTypeChangedEventRaiser(ITextSnapshot beforeSnapshot, ITextSnapshot afterSnapshot, IContentType beforeContentType, IContentType afterContentType, object editTag)
            {
                this.beforeSnapshot = beforeSnapshot;
                this.afterSnapshot = afterSnapshot;
                this.editTag = editTag;
                this.beforeContentType = beforeContentType;
                this.afterContentType = afterContentType;
            }

            public void RaiseEvent(BaseBuffer baseBuffer, bool immediate)
            {
                EventHandler<ContentTypeChangedEventArgs> handler = immediate ? baseBuffer.ContentTypeChangedImmediate : baseBuffer.ContentTypeChanged;
                if (handler != null)
                {
                    var eventArgs = new ContentTypeChangedEventArgs(this.beforeSnapshot, this.afterSnapshot, this.beforeContentType, this.afterContentType, this.editTag);
                    baseBuffer.guardedOperations.RaiseEvent(baseBuffer, handler, eventArgs);
                }
            }

            public bool HasPostEvent
            {
                get { return true; }
            }
        }
        #endregion

        #region Editing Shortcuts
        public ITextSnapshot Insert(int position, string text)
        {
            using (ITextEdit textEdit = CreateEdit())
            {
                textEdit.Insert(position, text);
                return textEdit.Apply();
            }
        }

        public ITextSnapshot Delete(Span deleteSpan)
        {
            using (ITextEdit textEdit = CreateEdit())
            {
                textEdit.Delete(deleteSpan);
                return textEdit.Apply();
            }
        }

        public ITextSnapshot Replace(Span replaceSpan, string replaceWith)
        {
            using (ITextEdit textEdit = CreateEdit())
            {
                textEdit.Replace(replaceSpan, replaceWith);
                return textEdit.Apply();
            }
        }
        #endregion

        #region Change Application and Eventing
        protected void SetCurrentVersionAndSnapshot(INormalizedTextChangeCollection normalizedChanges, int reiteratedVersionNumber = -1)
        {
            this.currentVersion = this.currentVersion.CreateNext(normalizedChanges, newLength: -1, reiteratedVersionNumber: reiteratedVersionNumber);
            this.builder = this.ApplyChangesToStringRebuilder(normalizedChanges, this.builder);
            this.currentSnapshot = TakeSnapshot();
        }

        public StringRebuilder ApplyChangesToStringRebuilder(INormalizedTextChangeCollection normalizedChanges, StringRebuilder source)
        {
            var doppelganger = this.GetDoppelgangerBuilder();
            if (doppelganger != null)
                return doppelganger;

            for (int i = normalizedChanges.Count - 1; (i >= 0); --i)
            {
                ITextChange change = normalizedChanges[i];
                source = source.Replace(change.OldSpan, TextChange.NewStringRebuilder(change));
            }

            return source;
        }

        protected internal abstract ISubordinateTextEdit CreateSubordinateEdit(EditOptions options, int? reiteratedVersionNumber, object editTag);
        protected virtual StringRebuilder GetDoppelgangerBuilder() { return null; }

        public event EventHandler<TextContentChangingEventArgs> Changing;

        public event EventHandler<TextContentChangedEventArgs> ChangedHighPriority;
        public event EventHandler<TextContentChangedEventArgs> Changed;
        public event EventHandler<TextContentChangedEventArgs> ChangedLowPriority;

        public event EventHandler PostChanged;
        public event EventHandler<TextContentChangedEventArgs> ChangedOnBackground;
        private Task _lastChangeOnBackgroundRaisedEvent = TextUtilities.CompletedNonInliningTask;

        internal event EventHandler<TextContentChangedEventArgs> ChangedImmediate;
        internal event EventHandler<ContentTypeChangedEventArgs> ContentTypeChangedImmediate;

        internal void RawRaiseEvent(TextContentChangedEventArgs args, bool immediate)
        {
            if (immediate)
            {
                EventHandler<TextContentChangedEventArgs> immediateHandler = ChangedImmediate;
                if (immediateHandler != null)
                {
                    if (BaseBuffer.eventTracing)
                    {
                        Debug.WriteLine("<<< Imm  events from " + ToString());
                    }
                    immediateHandler(this, args);
                }
                return;
            }

            EventHandler<TextContentChangedEventArgs> highHandler = ChangedHighPriority;
            EventHandler<TextContentChangedEventArgs> medHandler = Changed;
            EventHandler<TextContentChangedEventArgs> lowHandler = ChangedLowPriority;
            EventHandler<TextContentChangedEventArgs> changedOnBackgroundHandler = ChangedOnBackground;

            BaseBuffer.eventDepth++;
            string indent = BaseBuffer.eventTracing ? new String(' ', 3 * (BaseBuffer.eventDepth - 1)) : null;
            if (highHandler != null)
            {
                if (BaseBuffer.eventTracing)
                {
                    Debug.WriteLine(">>> " + indent + "High events from " + ToString());
                }
                this.guardedOperations.RaiseEvent(this, highHandler, args);
            }
            if (changedOnBackgroundHandler != null)
            {
                if (BaseBuffer.eventTracing)
                {
                    Debug.WriteLine(">>> " + indent + "background events from " + ToString());
                }

                // As this is a background event, we need to make sure handlers are executed synchronized
                // and in the order the edits were applied.
                // TODO: with this implementation any handler might delay all subsequent handlers.
                // That's true for other Changed* events too, but this event is raised on a background thread
                // so introducing delays in a handler won't be that easily noticable, also being on a
                // background thread might suggest it's actually ok to perform some long running
                // calculation directly in the  handler.
                // For isolation purposes we need a chain of tasks per handler, or some other, more
                // optimized isolation strategy. Tracked by #449694.
                _lastChangeOnBackgroundRaisedEvent = _lastChangeOnBackgroundRaisedEvent
                    .ContinueWith(_ =>
                    {
                        // changedOnBackgroundHandler might be stale at this point, get the latest list of handlers
                        var currentChangedOnBackgroundHandler = ChangedOnBackground;
                        if (currentChangedOnBackgroundHandler != null)
                        {
                            this.guardedOperations.RaiseEvent(this, currentChangedOnBackgroundHandler, args);
                        }
                    },
                    CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default);

#if WINDOWS
                // Now register pending task with task tracker to ensure it's completed when editor host is shutdown
                this.guardedOperations.NonJoinableTaskTracker?.Register(_lastChangeOnBackgroundRaisedEvent);
#endif
            }
            if (medHandler != null)
            {
                if (BaseBuffer.eventTracing)
                {
                    Debug.WriteLine(">>> " + indent + "Med  events from " + ToString());
                }
                this.guardedOperations.RaiseEvent(this, medHandler, args);
            }
            if (lowHandler != null)
            {
                if (BaseBuffer.eventTracing)
                {
                    Debug.WriteLine(">>> " + indent + "Low  events from " + ToString());
                }
                this.guardedOperations.RaiseEvent(this, lowHandler, args);
            }
            BaseBuffer.eventDepth--;
        }

        internal void RaisePostChangedEvent()
        {
            this.guardedOperations.RaiseEvent(this, PostChanged);
        }

        internal void RaiseChangingEvent(TextContentChangingEventArgs args)
        {
            var changing = this.Changing;

            if (changing != null)
            {
                foreach (Delegate handlerDelegate in changing.GetInvocationList())
                {
                    var handler = (EventHandler<TextContentChangingEventArgs>)handlerDelegate;
                    try
                    {
                        handler(this, args);
                    }
                    catch (Exception e)
                    {
                        this.guardedOperations.HandleException(handler, e);
                    }

                    if (args.Canceled)
                        return;
                }
            }
        }
        #endregion

        #region Diagnostic Support

        public override string ToString()
        {
            string suffix = TextUtilities.GetTag(this);
            if (string.IsNullOrEmpty(suffix))
            {
                ITextSnapshot snap = this.currentSnapshot;
                if (snap != null)
                {
                    suffix = "\"" + snap.GetText(0, Math.Min(16, snap.Length)) + "\"";
                }
            }
            return this.ContentType.TypeName + ":" + suffix;
        }

#if _DEBUG
        private string DebugOnly_AllText
        {
            get
            {
                return this.currentSnapshot.DebugOnly_AllText;
            }
        }
#endif

        #endregion
    }
}