File: StringBuilderDocument.cs

package info (click to toggle)
monodevelop 4.0.12%2Bdfsg-6
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 219,596 kB
  • ctags: 253,200
  • sloc: cs: 1,486,058; xml: 952,347; java: 60,981; makefile: 4,213; sh: 1,727; ansic: 867; objc: 302; sql: 111
file content (493 lines) | stat: -rw-r--r-- 12,865 bytes parent folder | download | duplicates (5)
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
// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using ICSharpCode.NRefactory.Utils;

namespace ICSharpCode.NRefactory.Editor
{
	/// <summary>
	/// Document based on a string builder.
	/// This class serves as a reference implementation for the IDocument interface.
	/// </summary>
	public class StringBuilderDocument : IDocument
	{
		readonly StringBuilder b;
		readonly TextSourceVersionProvider versionProvider = new TextSourceVersionProvider();
		
		/// <summary>
		/// Creates a new StringBuilderDocument.
		/// </summary>
		public StringBuilderDocument()
		{
			b = new StringBuilder();
		}
		
		/// <summary>
		/// Creates a new StringBuilderDocument with the specified initial text.
		/// </summary>
		public StringBuilderDocument(string text)
		{
			if (text == null)
				throw new ArgumentNullException("text");
			b = new StringBuilder(text);
		}
		
		/// <summary>
		/// Creates a new StringBuilderDocument with the initial text copied from the specified text source.
		/// </summary>
		public StringBuilderDocument(ITextSource textSource)
		{
			if (textSource == null)
				throw new ArgumentNullException("textSource");
			b = new StringBuilder(textSource.TextLength);
			textSource.WriteTextTo(new StringWriter(b));
		}
		
		/// <inheritdoc/>
		public event EventHandler<TextChangeEventArgs> TextChanging;
		
		/// <inheritdoc/>
		public event EventHandler<TextChangeEventArgs> TextChanged;
		
		/// <inheritdoc/>
		public event EventHandler ChangeCompleted;
		
		/// <inheritdoc/>
		public ITextSourceVersion Version {
			get { return versionProvider.CurrentVersion; }
		}
		
		#region Line<->Offset
		/// <inheritdoc/>
		public int LineCount {
			get { return CreateDocumentSnapshot().LineCount; }
		}
		
		/// <inheritdoc/>
		public IDocumentLine GetLineByNumber(int lineNumber)
		{
			return CreateDocumentSnapshot().GetLineByNumber(lineNumber);
		}
		
		/// <inheritdoc/>
		public IDocumentLine GetLineByOffset(int offset)
		{
			return CreateDocumentSnapshot().GetLineByOffset(offset);
		}
		
		/// <inheritdoc/>
		public int GetOffset(int line, int column)
		{
			return CreateDocumentSnapshot().GetOffset(line, column);
		}
		
		/// <inheritdoc/>
		public int GetOffset(TextLocation location)
		{
			return CreateDocumentSnapshot().GetOffset(location);
		}
		
		/// <inheritdoc/>
		public TextLocation GetLocation(int offset)
		{
			return CreateDocumentSnapshot().GetLocation(offset);
		}
		#endregion
		
		#region Insert/Remove/Replace
		/// <inheritdoc/>
		public void Insert(int offset, string text)
		{
			Replace(offset, 0, text);
		}
		
		/// <inheritdoc/>
		public void Insert(int offset, ITextSource text)
		{
			if (text == null)
				throw new ArgumentNullException("text");
			Replace(offset, 0, text.Text);
		}
		
		/// <inheritdoc/>
		public void Insert(int offset, string text, AnchorMovementType defaultAnchorMovementType)
		{
			if (offset < 0 || offset > this.TextLength)
				throw new ArgumentOutOfRangeException("offset");
			if (text == null)
				throw new ArgumentNullException("text");
			if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion)
				PerformChange(new InsertionWithMovementBefore(offset, text));
			else
				Replace(offset, 0, text);
		}
		
		/// <inheritdoc/>
		public void Insert(int offset, ITextSource text, AnchorMovementType defaultAnchorMovementType)
		{
			if (text == null)
				throw new ArgumentNullException("text");
			Insert(offset, text.Text, defaultAnchorMovementType);
		}
		
		[Serializable]
		sealed class InsertionWithMovementBefore : TextChangeEventArgs
		{
			public InsertionWithMovementBefore(int offset, string newText) : base(offset, string.Empty, newText)
			{
			}
			
			public override int GetNewOffset(int offset, AnchorMovementType movementType)
			{
				if (offset == this.Offset && movementType == AnchorMovementType.Default)
					return offset;
				else
					return base.GetNewOffset(offset, movementType);
			}
		}
		
		/// <inheritdoc/>
		public void Remove(int offset, int length)
		{
			Replace(offset, length, string.Empty);
		}
		
		/// <inheritdoc/>
		public void Replace(int offset, int length, string newText)
		{
			if (offset < 0 || offset > this.TextLength)
				throw new ArgumentOutOfRangeException("offset");
			if (length < 0 || length > this.TextLength - offset)
				throw new ArgumentOutOfRangeException("length");
			if (newText == null)
				throw new ArgumentNullException("newText");
			PerformChange(new TextChangeEventArgs(offset, b.ToString(offset, length), newText));
		}
		
		/// <inheritdoc/>
		public void Replace(int offset, int length, ITextSource newText)
		{
			if (newText == null)
				throw new ArgumentNullException("newText");
			Replace(offset, length, newText.Text);
		}
		
		bool isInChange;
		
		void PerformChange(TextChangeEventArgs change)
		{
			// Ensure that all changes take place inside an update group.
			// Will also take care of throwing an exception if isInChange is set.
			StartUndoableAction();
			try {
				isInChange = true;
				try {
					if (TextChanging != null)
						TextChanging(this, change);
					
					// Perform changes to document and Version property
					documentSnapshot = null;
					cachedText = null;
					b.Remove(change.Offset, change.RemovalLength);
					b.Insert(change.Offset, change.InsertedText.Text);
					versionProvider.AppendChange(change);
					
					// Update anchors and fire Deleted events
					UpdateAnchors(change);
					
					if (TextChanged != null)
						TextChanged(this, change);
				} finally {
					isInChange = false;
				}
			} finally {
				EndUndoableAction();
			}
		}
		#endregion
		
		#region Undo
		int undoGroupNesting = 0;
		
		/// <inheritdoc/>
		public void StartUndoableAction()
		{
			// prevent changes from within the TextChanging/TextChanged event handlers
			if (isInChange)
				throw new InvalidOperationException();
			undoGroupNesting++;
		}
		
		/// <inheritdoc/>
		public void EndUndoableAction()
		{
			undoGroupNesting--;
			if (undoGroupNesting == 0) {
				if (ChangeCompleted != null)
					ChangeCompleted(this, EventArgs.Empty);
			}
		}
		
		/// <inheritdoc/>
		public IDisposable OpenUndoGroup()
		{
			StartUndoableAction();
			return new CallbackOnDispose(EndUndoableAction);
		}
		#endregion
		
		#region CreateSnapshot/CreateReader
		ReadOnlyDocument documentSnapshot;
		
		/// <inheritdoc/>
		public IDocument CreateDocumentSnapshot()
		{
			if (documentSnapshot == null)
				documentSnapshot = new ReadOnlyDocument(this, this.FileName);
			return documentSnapshot;
		}
		
		/// <inheritdoc/>
		public ITextSource CreateSnapshot()
		{
			return new StringTextSource(this.Text, versionProvider.CurrentVersion);
		}
		
		/// <inheritdoc/>
		public ITextSource CreateSnapshot(int offset, int length)
		{
			return new StringTextSource(GetText(offset, length));
		}
		
		/// <inheritdoc/>
		public TextReader CreateReader()
		{
			return new StringReader(this.Text);
		}
		
		/// <inheritdoc/>
		public TextReader CreateReader(int offset, int length)
		{
			return new StringReader(GetText(offset, length));
		}
		
		/// <inheritdoc/>
		public void WriteTextTo(TextWriter writer)
		{
			if (writer == null)
				throw new ArgumentNullException("writer");
			writer.Write(this.Text);
		}
		
		/// <inheritdoc/>
		public void WriteTextTo(TextWriter writer, int offset, int length)
		{
			if (writer == null)
				throw new ArgumentNullException("writer");
			writer.Write(GetText(offset, length));
		}
		#endregion
		
		#region GetText / IndexOf
		string cachedText;
		
		/// <inheritdoc/>
		public string Text {
			get {
				if (cachedText == null)
					cachedText = b.ToString();
				return cachedText;
			}
			set {
				Replace(0, b.Length, value);
			}
		}
		
		/// <inheritdoc/>
		public int TextLength {
			get { return b.Length; }
		}
		
		/// <inheritdoc/>
		public char GetCharAt(int offset)
		{
			return b[offset];
		}
		
		/// <inheritdoc/>
		public string GetText(int offset, int length)
		{
			return b.ToString(offset, length);
		}
		
		/// <inheritdoc/>
		public string GetText(ISegment segment)
		{
			if (segment == null)
				throw new ArgumentNullException("segment");
			return b.ToString(segment.Offset, segment.Length);
		}
		
		/// <inheritdoc/>
		public int IndexOf(char c, int startIndex, int count)
		{
			return this.Text.IndexOf(c, startIndex, count);
		}
		
		/// <inheritdoc/>
		public int IndexOfAny(char[] anyOf, int startIndex, int count)
		{
			return this.Text.IndexOfAny(anyOf, startIndex, count);
		}
		
		/// <inheritdoc/>
		public int IndexOf(string searchText, int startIndex, int count, StringComparison comparisonType)
		{
			return this.Text.IndexOf(searchText, startIndex, count, comparisonType);
		}
		
		/// <inheritdoc/>
		public int LastIndexOf(char c, int startIndex, int count)
		{
			return this.Text.LastIndexOf(c, startIndex + count - 1, count);
		}
		
		/// <inheritdoc/>
		public int LastIndexOf(string searchText, int startIndex, int count, StringComparison comparisonType)
		{
			return this.Text.LastIndexOf(searchText, startIndex + count - 1, count, comparisonType);
		}
		#endregion
		
		#region CreateAnchor
		readonly List<WeakReference> anchors = new List<WeakReference>();
		
		/// <inheritdoc/>
		public ITextAnchor CreateAnchor(int offset)
		{
			var newAnchor = new SimpleAnchor(this, offset);
			for (int i = 0; i < anchors.Count; i++) {
				if (!anchors[i].IsAlive)
					anchors[i] = new WeakReference(newAnchor);
			}
			anchors.Add(new WeakReference(newAnchor));
			return newAnchor;
		}
		
		void UpdateAnchors(TextChangeEventArgs change)
		{
			// First update all anchors, then fire the deleted events.
			List<int> deletedAnchors = new List<int>();
			for (int i = 0; i < anchors.Count; i++) {
				var anchor = anchors[i].Target as SimpleAnchor;
				if (anchor != null) {
					anchor.Update(change);
					if (anchor.IsDeleted)
						deletedAnchors.Add(i);
				}
			}
			deletedAnchors.Reverse();
			foreach (var index in deletedAnchors) {
				var anchor = anchors[index].Target as SimpleAnchor;
				if (anchor != null)
					anchor.RaiseDeletedEvent();
				anchors.RemoveAt(index);
			}
		}
		
		sealed class SimpleAnchor : ITextAnchor
		{
			readonly StringBuilderDocument document;
			int offset;
			
			public SimpleAnchor(StringBuilderDocument document, int offset)
			{
				this.document = document;
				this.offset = offset;
			}
			
			public event EventHandler Deleted;
			
			public TextLocation Location {
				get {
					if (IsDeleted)
						throw new InvalidOperationException();
					return document.GetLocation(offset);
				}
			}
			
			public int Offset {
				get {
					if (IsDeleted)
						throw new InvalidOperationException();
					return offset;
				}
			}
			
			public AnchorMovementType MovementType { get; set; }
			
			public bool SurviveDeletion { get; set; }
			
			public bool IsDeleted {
				get { return offset < 0; }
			}
			
			public void Update(TextChangeEventArgs change)
			{
				if (SurviveDeletion || offset <= change.Offset || offset >= change.Offset + change.RemovalLength) {
					offset = change.GetNewOffset(offset, MovementType);
				} else {
					offset = -1;
				}
			}
			
			public void RaiseDeletedEvent()
			{
				if (Deleted != null)
					Deleted(this, EventArgs.Empty);
			}
			
			public int Line {
				get { return this.Location.Line; }
			}
			
			public int Column {
				get { return this.Location.Column; }
			}
		}
		#endregion
		
		/// <inheritdoc/>
		public virtual object GetService(Type serviceType)
		{
			return null;
		}
		
		/// <inheritdoc/>
		public virtual event EventHandler FileNameChanged { add {} remove {} }
		
		/// <inheritdoc/>
		public virtual string FileName {
			get { return string.Empty; }
		}
	}
}