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

TextEditorData.cs « Mono.TextEditor « Mono.Texteditor « core « src « main - github.com/mono/monodevelop.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: a9c9e75adccddb52b610f18194b430e94270d279 (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
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
// TextEditorData.cs
//
// Author:
//   Mike Krüger <mkrueger@novell.com>
//
// Copyright (c) 2008 Novell, Inc (http://www.novell.com)
//
// 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.Text;
using Gtk;
using System.IO;
using System.Diagnostics;
using Mono.TextEditor.Highlighting;
using ICSharpCode.NRefactory.Editor;
using Xwt.Drawing;

namespace Mono.TextEditor
{
	public enum SelectionMode {
		Normal,
		Block
	}
	
	public class TextEditorData : IDisposable
	{
		ITextEditorOptions    options;
		TextDocument document; 
		readonly Caret        caret;
		
		static Adjustment emptyAdjustment = new Adjustment (0, 0, 0, 0, 0, 0);
		
		Adjustment hadjustment = emptyAdjustment; 
		public Adjustment HAdjustment {
			get {
				return hadjustment;
			}
			set {
				hadjustment = value;
			}
		}
		
		Adjustment vadjustment = emptyAdjustment;
		public Adjustment VAdjustment {
			get {
				return vadjustment;
			}
			set {
				vadjustment = value;
			}
		}
		
		EditMode currentMode = null;
		public EditMode CurrentMode {
			get {
				return currentMode;
			}
			set {
				var oldMode = currentMode;
				currentMode = value;
				currentMode.AddedToEditor (this);
				if (oldMode != null)
					oldMode.RemovedFromEditor (this);
				OnEditModeChanged (new EditModeChangedEventArgs (oldMode, currentMode));
			}
		}

		protected virtual void OnEditModeChanged (EditModeChangedEventArgs e)
		{
			var handler = EditModeChanged;
			if (handler != null)
				handler (this, e);
		}

		/// <summary>
		/// Occurs when the edit mode changed.
		/// </summary>
		public event EventHandler<EditModeChangedEventArgs> EditModeChanged;
		
		public TextEditor Parent {
			get;
			set;
		}
		
		public string FileName {
			get {
				return Document != null ? Document.FileName : null;
			}
		}
		
		public string MimeType {
			get {
				return Document != null ? Document.MimeType : null;
			}
		}

		public bool IsDisposed {
			get;
			protected set;
		}

		ISelectionSurroundingProvider selectionSurroundingProvider = new DefaultSelectionSurroundingProvider ();
		public ISelectionSurroundingProvider SelectionSurroundingProvider {
			get {
				return selectionSurroundingProvider;
			}
			set {
				if (value == null)
					throw new ArgumentNullException ("surrounding provider needs to be != null");
				selectionSurroundingProvider = value;
			}
		}

		bool? customTabsToSpaces;
		public bool TabsToSpaces {
			get {
				return customTabsToSpaces.HasValue ? customTabsToSpaces.Value : options.TabsToSpaces;
			}
			set {
				customTabsToSpaces = value;
			}
		}

		bool? customShowRuler;
		public bool ShowRuler {
			get {
				return customShowRuler.HasValue ? customShowRuler.Value : options.ShowRuler;
			}
			set {
				customShowRuler = value;
			}
		}

		bool? customHighlightCaretLine;
		public bool HighlightCaretLine {
			get {
				return customHighlightCaretLine.HasValue ? customHighlightCaretLine.Value : options.HighlightCaretLine;
			}
			set {
				customHighlightCaretLine = value;
			}
		}

		#region Tooltip providers
		internal List<TooltipProvider> tooltipProviders = new List<TooltipProvider> ();
		public IEnumerable<TooltipProvider> TooltipProviders {
			get { return tooltipProviders; }
		}
		
		/// <summary>
		/// If set the tooltips wont show up.
		/// </summary>
		public bool SuppressTooltips {
			get;
			set;
		}

		public void ClearTooltipProviders ()
		{
			foreach (var tp in tooltipProviders) {
				var disposableProvider = tp as IDisposable;
				if (disposableProvider == null)
					continue;
				disposableProvider.Dispose ();
			}
			tooltipProviders.Clear ();
		}
		
		public void AddTooltipProvider (TooltipProvider provider)
		{
			tooltipProviders.Add (provider);
		}
		
		public void RemoveTooltipProvider (TooltipProvider provider)
		{
			tooltipProviders.Remove (provider);
		}
		#endregion

		public TextEditorData () : this (new TextDocument ())
		{
		}

		public TextEditorData (TextDocument doc)
		{
			LineHeight = 16;

			caret = new Caret (this);
			caret.PositionChanged += CaretPositionChanged;

			options = TextEditorOptions.DefaultOptions;
			
			document = doc;
			document.BeginUndo += OnBeginUndo;
			document.EndUndo += OnEndUndo;

			document.Undone += DocumentHandleUndone;
			document.Redone += DocumentHandleRedone;
			document.LineChanged += HandleDocLineChanged;
			document.TextReplaced += HandleTextReplaced;

			document.TextSet += HandleDocTextSet;
			document.Folded += HandleTextEditorDataDocumentFolded;
			document.FoldTreeUpdated += HandleFoldTreeUpdated;
			SearchEngine = new BasicSearchEngine ();

			HeightTree = new HeightTree (this);
			HeightTree.Rebuild ();
			IndentationTracker = new DefaultIndentationTracker (document);
		}

		void HandleFoldTreeUpdated (object sender, EventArgs e)
		{
			HeightTree.Rebuild ();
		}

		void HandleDocTextSet (object sender, EventArgs e)
		{
			if (vadjustment != null)
				vadjustment.Value = vadjustment.Lower;
			if (hadjustment != null)
				hadjustment.Value = hadjustment.Lower;
			HeightTree.Rebuild ();
			ClearSelection ();
			caret.SetDocument (document);
		}

		public double GetLineHeight (DocumentLine line)
		{
			if (Parent == null)
				return LineHeight;
			return Parent.GetLineHeight (line);
		}
		
		public double GetLineHeight (int line)
		{
			if (Parent == null)
				return LineHeight;
			return Parent.GetLineHeight (line);
		}

		void HandleDocLineChanged (object sender, LineEventArgs e)
		{
			e.Line.WasChanged = true;
		}

		
		public TextDocument Document {
			get {
				return document;
			}
		}

		void HandleTextReplaced (object sender, DocumentChangeEventArgs e)
		{
			caret.UpdateCaretPosition (e);
		}


		/// <value>
		/// The eol mark used in this document - it's taken from the first line in the document,
		/// if no eol mark is found it's using the default (Environment.NewLine).
		/// The value is saved, even when all lines are deleted the eol marker will still be the old eol marker.
		/// </value>
		public string EolMarker {
			get {
				if (Options.OverrideDocumentEolMarker)
					return Options.DefaultEolMarker;
				string eol = null;
				if (Document.LineCount > 0) {
					DocumentLine line = Document.GetLine (DocumentLocation.MinLine);
					if (line.DelimiterLength > 0) 
						eol = Document.GetTextAt (line.Length, line.DelimiterLength);
				}
				return !String.IsNullOrEmpty (eol) ? eol : Options.DefaultEolMarker;
			}
		}
		
		public ITextEditorOptions Options {
			get {
				return options;
			}
			set {
				options = value;
			}
		}
		
		public Mono.TextEditor.Caret Caret {
			get {
				return caret;
			}
		}
		
		ColorScheme colorStyle;
		public ColorScheme ColorStyle {
			get {
				return colorStyle ?? SyntaxModeService.DefaultColorStyle;
			}
			set {
				colorStyle = value;
			}
		}

		string ConvertToPangoMarkup (string str, bool replaceTabs = true)
		{
			if (str == null)
				throw new ArgumentNullException ("str");
			var result = new StringBuilder ();
			foreach (char ch in str) {
				switch (ch) {
				case '&':
					result.Append ("&amp;");
					break;
				case '<':
					result.Append ("&lt;");
					break;
				case '>':
					result.Append ("&gt;");
					break;
				case '\t':
					if (replaceTabs) {
						result.Append (new string (' ', options.TabSize));
					} else {
						result.Append ('\t');
					}
					break;
				default:
					result.Append (ch);
					break;
				}
			}
			return result.ToString ();
		}
		
		public string GetMarkup (int offset, int length, bool removeIndent, bool useColors = true, bool replaceTabs = true)
		{
			ISyntaxMode mode = Document.SyntaxMode;
			var style = ColorStyle;

			if (style == null) {
				var str = Document.GetTextAt (offset, length);
				if (removeIndent)
					str = str.TrimStart (' ', '\t');
				return ConvertToPangoMarkup (str, replaceTabs);
			}

			int indentLength = SyntaxMode.GetIndentLength (Document, offset, length, false);
			int curOffset = offset;

			StringBuilder result = new StringBuilder ();
			while (curOffset < offset + length && curOffset < Document.TextLength) {
				DocumentLine line = Document.GetLineByOffset (curOffset);
				int toOffset = System.Math.Min (line.Offset + line.Length, offset + length);
				var styleStack = new Stack<ChunkStyle> ();

				foreach (var chunk in mode.GetChunks (style, line, curOffset, toOffset - curOffset)) {
					var chunkStyle = style.GetChunkStyle (chunk);
					bool setBold = (styleStack.Count > 0 && styleStack.Peek ().FontWeight != chunkStyle.FontWeight) || 
						chunkStyle.FontWeight != FontWeight.Normal;
					bool setItalic = (styleStack.Count > 0 && styleStack.Peek ().FontStyle != chunkStyle.FontStyle) || 
						chunkStyle.FontStyle != FontStyle.Normal;
					bool setUnderline = chunkStyle.Underline && (styleStack.Count == 0 || !styleStack.Peek ().Underline) ||
							!chunkStyle.Underline && (styleStack.Count == 0 || styleStack.Peek ().Underline);
					bool setColor = styleStack.Count == 0 || TextViewMargin.GetPixel (styleStack.Peek ().Foreground) != TextViewMargin.GetPixel (chunkStyle.Foreground);
					if (setColor || setBold || setItalic || setUnderline) {
						if (styleStack.Count > 0) {
							result.Append ("</span>");
							styleStack.Pop ();
						}
						result.Append ("<span");
						if (useColors) {
							result.Append (" foreground=\"");
							result.Append (SyntaxMode.ColorToPangoMarkup (chunkStyle.Foreground));
							result.Append ("\"");
						}
						if (chunkStyle.FontWeight != Xwt.Drawing.FontWeight.Normal)
							result.Append (" weight=\"" + chunkStyle.FontWeight + "\"");
						if (chunkStyle.FontStyle != Xwt.Drawing.FontStyle.Normal)
							result.Append (" style=\"" + chunkStyle.FontStyle + "\"");
						if (chunkStyle.Underline)
							result.Append (" underline=\"single\"");
						result.Append (">");
						styleStack.Push (chunkStyle);
					}
					result.Append (ConvertToPangoMarkup (Document.GetTextBetween (chunk.Offset, System.Math.Min (chunk.EndOffset, Document.TextLength)), replaceTabs));
				}
				while (styleStack.Count > 0) {
					result.Append ("</span>");
					styleStack.Pop ();
				}

				curOffset = line.EndOffsetIncludingDelimiter;
				if (removeIndent)
					curOffset += indentLength;
				if (result.Length > 0 && curOffset < offset + length)
					result.AppendLine ();
			}
			return result.ToString ();
		}

		public IEnumerable<Chunk> GetChunks (DocumentLine line, int offset, int length)
		{
			return document.SyntaxMode.GetChunks (ColorStyle, line, offset, length);
		}		
	
		public int Insert (int offset, string value)
		{
			return Replace (offset, 0, value);
		}
		
		public void Remove (int offset, int count)
		{
			Replace (offset, count, null);
		}
		
		public void Remove (TextSegment removeSegment)
		{
			Remove (removeSegment.Offset, removeSegment.Length);
		}
		
		public void Remove (DocumentRegion region)
		{
			Remove (region.GetSegment (document));
		}

		public string FormatString (DocumentLocation loc, string str)
		{
			if (string.IsNullOrEmpty (str))
				return "";
			StringBuilder sb = new StringBuilder ();
			bool convertTabs = TabsToSpaces;
			var tabSize = Options.TabSize;
			for (int i = 0; i < str.Length; i++) {
				char ch = str [i];
				switch (ch) {
				case '\u00A0': // convert non breaking spaces to standard spaces.
					sb.Append (' ');
					break;
				case '\t':
					if (convertTabs) {
						int tabWidth = TextViewMargin.GetNextTabstop (this, loc.Column, tabSize) - loc.Column;
						sb.Append (new string (' ', tabWidth));
						loc = new DocumentLocation (loc.Line, loc.Column + tabWidth);
					} else 
						goto default;
					break;
				case '\r':
					if (i + 1 < str.Length && str [i + 1] == '\n')
						i++;
					goto case '\n';
				case '\n':
					sb.Append (EolMarker);
					loc = new DocumentLocation (loc.Line + 1, 1);
					break;
				default:
					sb.Append (ch);
					loc = new DocumentLocation (loc.Line, loc.Column + 1);
					break;
				}
			}
			return sb.ToString ();
		}
		
		public string FormatString (int offset, string str)
		{
			return FormatString (Document.OffsetToLocation (offset), str);
		}
		
		public int Replace (int offset, int count, string value)
		{
			string formattedString = FormatString (offset, value);
			document.Replace (offset, count, formattedString);
			return formattedString.Length;
		}
			
		public void InsertAtCaret (string text)
		{
			if (String.IsNullOrEmpty (text))
				return;
			using (var undo = OpenUndoGroup ()) {
				DeleteSelectedText (IsSomethingSelected ? MainSelection.SelectionMode != SelectionMode.Block : true);
				// Needs to be called after delete text, delete text handles virtual caret postitions itself,
				// but afterwards the virtual position may need to be restored.
				EnsureCaretIsNotVirtual ();

				if (IsSomethingSelected && MainSelection.SelectionMode == SelectionMode.Block) {
					var visualInsertLocation = LogicalToVisualLocation (MainSelection.Anchor);
					var selection = MainSelection;
					Caret.PreserveSelection = true;
					for (int lineNumber = selection.MinLine; lineNumber <= selection.MaxLine; lineNumber++) {
						var lineSegment = GetLine (lineNumber);
						int insertOffset = lineSegment.GetLogicalColumn (this, visualInsertLocation.Column) - 1;
						string textToInsert;
						if (lineSegment.Length < insertOffset) {
							int visualLastColumn = lineSegment.GetVisualColumn (this, lineSegment.Length + 1);
							int charsToInsert = visualInsertLocation.Column - visualLastColumn;
							int spaceCount = charsToInsert % Options.TabSize;
							textToInsert = new string ('\t', (charsToInsert - spaceCount) / Options.TabSize) + new string (' ', spaceCount) + text;
							insertOffset = lineSegment.Length;
						} else {
							textToInsert = text;
						}
						Insert (lineSegment.Offset + insertOffset, textToInsert);
					}
					var visualColumn = GetLine (Caret.Location.Line).GetVisualColumn (this, Caret.Column);
					MainSelection = new Selection (
						new DocumentLocation (selection.Anchor.Line, GetLine (selection.Anchor.Line).GetLogicalColumn (this, visualColumn)),
						new DocumentLocation (selection.Lead.Line, GetLine (selection.Lead.Line).GetLogicalColumn (this, visualColumn)),
						SelectionMode.Block
					);
					Caret.PreserveSelection = false;
					Document.CommitMultipleLineUpdate (selection.MinLine, selection.MaxLine);
				} else {
					EnsureCaretIsNotVirtual ();
					Insert (Caret.Offset, text);
				}
			}
		}

		void DetachDocument ()
		{
			if (document == null)
				return;
			document.BeginUndo -= OnBeginUndo;
			document.EndUndo -= OnEndUndo;

			document.Undone -= DocumentHandleUndone;
			document.Redone -= DocumentHandleRedone;
			document.LineChanged -= HandleDocLineChanged;
			document.TextReplaced -= HandleTextReplaced;

			document.TextSet -= HandleDocTextSet;
			document.Folded -= HandleTextEditorDataDocumentFolded;
			document.FoldTreeUpdated -= HandleFoldTreeUpdated;
			document = null;
		}

		public void Dispose ()
		{
			if (IsDisposed)
				return;
			document.WaitForFoldUpdateFinished ();
			IsDisposed = true;
			options = options.Kill ();
			HeightTree.Dispose ();
			DetachDocument ();
			ClearTooltipProviders ();
			tooltipProviders = null;
		}

		/// <summary>
		/// Removes the indent on the caret line, if the indent mode is set to virtual and the indent matches
		/// the current virtual indent in that line.
		/// </summary>
		public void FixVirtualIndentation ()
		{
			if (!HasIndentationTracker || Options.IndentStyle != IndentStyle.Virtual)
				return;
			var line = Document.GetLine (Caret.Line);
			if (line != null && line.Length > 0 && GetIndentationString (caret.Line - 1, int.MaxValue) == Document.GetTextAt (line.Offset, line.Length))
				Remove (line.Offset, line.Length);
		}

		public void FixVirtualIndentation (int lineNumber)
		{
			if (!HasIndentationTracker || Options.IndentStyle != IndentStyle.Virtual)
				return;
			var line = Document.GetLine (lineNumber);
			if (line != null && line.Length > 0 && GetIndentationString (lineNumber, line.Length + 1) == Document.GetTextAt (line.Offset, line.Length))
				Remove (line.Offset, line.Length);
		}

		void CaretPositionChanged (object sender, DocumentLocationEventArgs args)
		{
			if (!caret.PreserveSelection)
				this.ClearSelection ();
		}
		
		public bool CanEdit (int line)
		{
			if (document.ReadOnlyCheckDelegate != null)
				return document.ReadOnlyCheckDelegate (line);
			return !document.ReadOnly;
		}

		public int FindNextWordOffset (int offset)
		{
			return options.WordFindStrategy.FindNextWordOffset (Document, offset);
		}
		
		public int FindPrevWordOffset (int offset)
		{
			return options.WordFindStrategy.FindPrevWordOffset (Document, offset);
		}
		
		public int FindNextSubwordOffset (int offset)
		{
			return options.WordFindStrategy.FindNextSubwordOffset (Document, offset);
		}

		public int FindPrevSubwordOffset (int offset)
		{
			return options.WordFindStrategy.FindPrevSubwordOffset (Document, offset);
		}
		
		public int FindCurrentWordEnd (int offset)
		{
			return Options.WordFindStrategy.FindCurrentWordEnd (Document, offset);
		}
		
		public int FindCurrentWordStart (int offset)
		{
			return Options.WordFindStrategy.FindCurrentWordStart (Document, offset);
		}

		#region undo/redo handling
		DocumentLocation savedCaretPos;
		Selection savedSelection;
		//List<TextEditorDataState> states = new List<TextEditorDataState> ();

		void OnBeginUndo (object sender, EventArgs args)
		{
			savedCaretPos  = Caret.Location;
			savedSelection = MainSelection;
		}

		void OnEndUndo (object sender, TextDocument.UndoOperationEventArgs e)
		{
			if (e == null)
				return;
			e.Operation.Tag = new TextEditorDataState (this, savedCaretPos, savedSelection);
		}

		void DocumentHandleUndone (object sender, TextDocument.UndoOperationEventArgs e)
		{
			var state = e.Operation.Tag as TextEditorDataState;
			if (state != null)
				state.UndoState ();
		}

		void DocumentHandleRedone (object sender, TextDocument.UndoOperationEventArgs e)
		{
			var state = e.Operation.Tag as TextEditorDataState;
			if (state != null)
				state.RedoState ();
		}

		class TextEditorDataState
		{
			DocumentLocation undoCaretPos;
			Selection undoSelection;

			DocumentLocation redoCaretPos;
			Selection redoSelection;
			
			TextEditorData editor;
			
			public TextEditorDataState (TextEditorData editor, DocumentLocation caretPos, Selection selection)
			{
				this.editor        = editor;
				undoCaretPos  = caretPos;
				undoSelection = selection;
				
				redoCaretPos  = editor.Caret.Location;
				redoSelection = editor.MainSelection;
			}
			
			public void UndoState ()
			{
				editor.Caret.Location = undoCaretPos;
				editor.MainSelection = undoSelection;
			}
			
			public void RedoState ()
			{
				editor.Caret.Location = redoCaretPos;
				editor.MainSelection = redoSelection;
			}
		}
		#endregion
		
		#region Selection management
		public bool IsSomethingSelected {
			get {
				return !MainSelection.IsEmpty && MainSelection.Anchor != MainSelection.Lead; 
			}
		}
		
		public bool IsMultiLineSelection {
			get {
				return IsSomethingSelected && MainSelection.Anchor.Line - MainSelection.Lead.Line != 0;
			}
		}

		public bool CanEditSelection {
			get {
				// To be improved when we support read-only regions
				if (IsSomethingSelected)
					return !document.ReadOnly;
				return CanEdit (caret.Line);
			}
		}
		class TextEditorDataEventArgs : EventArgs
		{
			TextEditorData data;
			public TextEditorData TextEditorData {
				get {
					return data;
				}
			}
			public TextEditorDataEventArgs (TextEditorData data)
			{
				this.data = data;
			}
		}
		
		public event EventHandler SelectionChanging;
		
		protected virtual void OnSelectionChanging (EventArgs e)
		{
			var handler = SelectionChanging;
			if (handler != null)
				handler (this, e);
		}
		
		public SelectionMode SelectionMode {
			get {
				return !MainSelection.IsEmpty ? MainSelection.SelectionMode : SelectionMode.Normal;
			}
			set {
				if (MainSelection.IsEmpty)
					return;
				MainSelection = MainSelection.WithSelectionMode (value);
			}
		}
		
		Selection mainSelection = Selection.Empty;
		public Selection MainSelection {
			get {
				return mainSelection;
			}
			set {
				if (mainSelection.IsEmpty && value.IsEmpty)
					return;
				if (mainSelection.IsEmpty && !value.IsEmpty || !mainSelection.IsEmpty && value.IsEmpty || !mainSelection.Equals (value)) {
					OnSelectionChanging (EventArgs.Empty);
					mainSelection = value;
					OnSelectionChanged (EventArgs.Empty);
				}
			}
		}

		public IEnumerable<Selection> Selections {
			get {
				yield return MainSelection;
			}
		}
		
//		public DocumentLocation LogicalToVisualLocation (DocumentLocation location)
//		{
//			return LogicalToVisualLocation (this, location);
//		}
//		
//		public DocumentLocation VisualToLogicalLocation (DocumentLocation location)
//		{
//			int line = VisualToLogicalLine (location.Line);
//			int column = Document.GetLine (line).GetVisualColumn (this, location.Column);
//			return new DocumentLocation (line, column);
//		}
		public int SelectionAnchor {
			get {
				if (MainSelection.IsEmpty)
					return -1;
				return MainSelection.GetAnchorOffset (this);
			}
			set {
				DocumentLocation location = Document.OffsetToLocation (value);
				if (mainSelection.IsEmpty) {
					MainSelection = new Selection (location, location);
				} else {
					if (MainSelection.Lead == location) {
						MainSelection = MainSelection.WithLead (MainSelection.Anchor);
					} else {
						MainSelection = MainSelection.WithAnchor (location);
					}
				}
			}
		}

		/// <summary>
		/// Gets or sets the selection range. If nothing is selected (Caret.Offset, 0) is returned.
		/// </summary>
		public TextSegment SelectionRange {
			get {
				return !MainSelection.IsEmpty ? MainSelection.GetSelectionRange (this) : new TextSegment (Caret.Offset, 0);
			}
			set {
				if (SelectionRange != value) {
					OnSelectionChanging (EventArgs.Empty);
					if (value.IsEmpty) {
						MainSelection = Selection.Empty;
					} else {
						DocumentLocation loc1 = document.OffsetToLocation (value.Offset);
						DocumentLocation loc2 = document.OffsetToLocation (value.EndOffset);
						if (MainSelection.IsEmpty) {
							MainSelection = new Selection (loc1, loc2);
						} else {
							if (MainSelection.Anchor == loc1) {
								MainSelection = MainSelection.WithLead (loc2);
							} else if (MainSelection.Anchor == loc2) {
								MainSelection = MainSelection.WithLead (loc1);
							} else {
								MainSelection = new Selection (loc1, loc2);
							}
						}
						
					}
				}
			}
		}
		
		public string SelectedText {
			get {
				if (!IsSomethingSelected)
					return null;
				return Document.GetTextAt (SelectionRange);
			}
			set {
				if (!IsSomethingSelected)
					return;
				var selection = SelectionRange;
				Replace (selection.Offset, selection.Length, value);
				if (Caret.Offset > selection.Offset)
					Caret.Offset = selection.Offset + value.Length;
				SelectionRange = new TextSegment (selection.Offset, value.Length);
			}
		}
		
		
		public IEnumerable<DocumentLine> SelectedLines {
			get {
				if (!IsSomethingSelected) 
					return document.GetLinesBetween (caret.Line, caret.Line);
				var selection = MainSelection;
				int startLineNr = selection.MinLine;
				int endLineNr = selection.MaxLine;
						
				bool skipEndLine = selection.Anchor < selection.Lead ? selection.Lead.Column == DocumentLocation.MinColumn : selection.Anchor.Column == DocumentLocation.MinColumn;
				if (skipEndLine)
					endLineNr--;
				return document.GetLinesBetween (startLineNr, endLineNr);
			}
		}
		
		public void ClearSelection ()
		{
			if (!IsSomethingSelected)
				return;
			MainSelection = Selection.Empty;
		}
		
		public void ExtendSelectionTo (DocumentLocation location)
		{
			if (MainSelection.IsEmpty) {
				MainSelection = new Selection (location, location);
			} else {
				MainSelection = MainSelection.WithLead (location);
			}
		}
		
		public void SetSelection (int anchorOffset, int leadOffset)
		{
			var anchor = document.OffsetToLocation (anchorOffset);
			var lead = document.OffsetToLocation (leadOffset);
			MainSelection = new Selection (anchor, lead);
		}

		public void SetSelection (DocumentLocation anchor, DocumentLocation lead)
		{
			MainSelection = new Selection (anchor, lead);
		}

		public void SetSelection (int anchorLine, int anchorColumn, int leadLine, int leadColumn)
		{
			SetSelection (new DocumentLocation (anchorLine, anchorColumn), new DocumentLocation (leadLine, leadColumn));
		}

		public void ExtendSelectionTo (int offset)
		{
			ExtendSelectionTo (document.OffsetToLocation (offset));
		}
		
		public void SetSelectLines (int from, int to)
		{
			MainSelection = new Selection (document.OffsetToLocation (Document.GetLine (from).Offset), 
			                               document.OffsetToLocation (Document.GetLine (to).EndOffsetIncludingDelimiter));
		}

		internal void DeleteSelection (Selection selection)
		{
			if (selection.IsEmpty)
				throw new ArgumentNullException ("selection was empty.");
			switch (selection.SelectionMode) {
			case SelectionMode.Normal:
				var segment = selection.GetSelectionRange (this);
				int len = System.Math.Min (segment.Length, Document.TextLength - segment.Offset);
				var loc = selection.Anchor < selection.Lead ? selection.Anchor : selection.Lead;
				caret.Location = loc;
				EnsureCaretIsNotVirtual ();
				if (len > 0)
					Remove (segment.Offset, len);
				caret.Location = loc;
				break;
			case SelectionMode.Block:
				DocumentLocation visStart = LogicalToVisualLocation (selection.Anchor);
				DocumentLocation visEnd = LogicalToVisualLocation (selection.Lead);
				int startCol = System.Math.Min (visStart.Column, visEnd.Column);
				int endCol = System.Math.Max (visStart.Column, visEnd.Column);
				bool preserve = Caret.PreserveSelection;
				Caret.PreserveSelection = true;
				for (int lineNr = selection.MinLine; lineNr <= selection.MaxLine; lineNr++) {
					DocumentLine curLine = Document.GetLine (lineNr);
					int col1 = curLine.GetLogicalColumn (this, startCol) - 1;
					int col2 = System.Math.Min (curLine.GetLogicalColumn (this, endCol) - 1, curLine.Length);
					if (col1 >= col2)
						continue;
					Remove (curLine.Offset + col1, col2 - col1);
					
					if (Caret.Line == lineNr && Caret.Column >= col1)
						Caret.Column = col1 + 1;
				}
				int column = System.Math.Min (selection.Anchor.Column, selection.Lead.Column);
				MainSelection = selection.WithRange (
					new DocumentLocation (selection.Anchor.Line, column),
					new DocumentLocation (selection.Lead.Line, column)
				);
				Caret.PreserveSelection = preserve;
				break;
			}
			FixVirtualIndentation ();
		}
		
		public void DeleteSelectedText ()
		{
			DeleteSelectedText (true);
		}
		
		public void DeleteSelectedText (bool clearSelection)
		{
			if (!IsSomethingSelected)
				return;
			bool needUpdate = false;
			using (var undo = OpenUndoGroup ()) {
				EnsureCaretIsNotVirtual ();
				foreach (Selection selection in Selections) {
					EnsureIsNotVirtual (selection.Anchor);
					EnsureIsNotVirtual (selection.Lead);
					var segment = selection.GetSelectionRange (this);
					needUpdate |= Document.OffsetToLineNumber (segment.Offset) != Document.OffsetToLineNumber (segment.EndOffset);
					DeleteSelection (selection);
				}
				if (clearSelection)
					ClearSelection ();
				FixVirtualIndentation ();
			}
			if (needUpdate)
				Document.CommitDocumentUpdate ();
		}
		
		public event EventHandler SelectionChanged;
		protected virtual void OnSelectionChanged (EventArgs args)
		{
//			Console.WriteLine ("----");
//			Console.WriteLine (Environment.StackTrace);
			if (SelectionChanged != null) 
				SelectionChanged (this, args);
		}
		#endregion

		
		#region Search & Replace
		ISearchEngine searchEngine;
		public ISearchEngine SearchEngine {
			get {
				return searchEngine;
			}
			set {
				if (searchEngine != value) {
					value.TextEditorData = this;
					value.SearchRequest = SearchRequest;
					searchEngine = value;
					OnSearchChanged (EventArgs.Empty);
				}
			}
		}
		
		protected virtual void OnSearchChanged (EventArgs args)
		{
			if (SearchChanged != null)
				SearchChanged (this, args);
		}
		
		public event EventHandler SearchChanged;

		SearchRequest currentSearchRequest;
		
		public SearchRequest SearchRequest {
			get {
				if (currentSearchRequest == null) {
					currentSearchRequest = new SearchRequest ();
					currentSearchRequest.Changed += delegate {
						OnSearchChanged (EventArgs.Empty);
					};
				}
				return currentSearchRequest;
			}
		}
		
		public bool IsMatchAt (int offset)
		{
			return searchEngine.IsMatchAt (offset);
		}
		
		public SearchResult GetMatchAt (int offset)
		{
			return searchEngine.GetMatchAt (offset);
		}
			
		public SearchResult SearchForward (int fromOffset)
		{
			return searchEngine.SearchForward (fromOffset);
		}
		
		public SearchResult SearchBackward (int fromOffset)
		{
			return searchEngine.SearchBackward (fromOffset);
		}
		
		public SearchResult FindNext (bool setSelection)
		{
			if (SearchEngine.SearchRequest == null || string.IsNullOrEmpty (SearchEngine.SearchRequest.SearchPattern))
				return null;

			int startOffset = Caret.Offset;
			if (IsSomethingSelected && IsMatchAt (startOffset)) {
				startOffset = MainSelection.GetLeadOffset (this);
			}
			
			SearchResult result = SearchForward (startOffset);
			if (result != null) {
				Caret.Offset = result.Offset + result.Length;
				if (setSelection)
					MainSelection = new Selection (Document.OffsetToLocation (result.Offset), Caret.Location);
			}
			return result;
		}
		
		public SearchResult FindPrevious (bool setSelection)
		{
			if (SearchEngine.SearchRequest == null || string.IsNullOrEmpty (SearchEngine.SearchRequest.SearchPattern))
				return null;
			int startOffset = Caret.Offset - SearchEngine.SearchRequest.SearchPattern.Length;
			if (IsSomethingSelected && IsMatchAt (MainSelection.GetAnchorOffset (this))) 
				startOffset = MainSelection.GetAnchorOffset (this);
			
			int searchOffset;
			if (startOffset < 0) {
				searchOffset = Document.TextLength - 1;
			} else {
				searchOffset = (startOffset + Document.TextLength - 1) % Document.TextLength;
			}
			SearchResult result = SearchBackward (searchOffset);
			if (result != null) {
				result.SearchWrapped = result.EndOffset > startOffset;
				Caret.Offset = result.Offset + result.Length;
				if (setSelection)
					MainSelection = new Selection (Document.OffsetToLocation (result.Offset), Caret.Location);
			}
			return result;
		}
		
		public bool SearchReplace (string withPattern, bool setSelection)
		{
			bool result = false;
			if (IsSomethingSelected) {
				var selection = MainSelection.GetSelectionRange (this);
				SearchResult match = searchEngine.GetMatchAt (selection.Offset, selection.Length);
				if (match != null) {
					searchEngine.Replace (match, withPattern);
					ClearSelection ();
					Caret.Offset = selection.Offset + withPattern.Length;
					result = true;
				}
			}
			return FindNext (setSelection) != null || result;
		}
		
		public int SearchReplaceAll (string withPattern)
		{
			return searchEngine.ReplaceAll (withPattern);
		}
		#endregion
		
		#region VirtualSpace Manager
		IIndentationTracker indentationTracker = null;
		public bool HasIndentationTracker {
			get {
				return indentationTracker != null;	
			}	
		}

		public IIndentationTracker IndentationTracker {
			get {
				if (!HasIndentationTracker)
					throw new InvalidOperationException ("Indentation tracker not installed.");
				return indentationTracker;
			}
			set {
				indentationTracker = value;
			}
		}
		
		public string GetIndentationString (DocumentLocation loc)
		{
			return IndentationTracker.GetIndentationString (loc.Line, loc.Column);
		}
		
		public string GetIndentationString (int lineNumber, int column)
		{
			return IndentationTracker.GetIndentationString (lineNumber, column);
		}
		
		public string GetIndentationString (int offset)
		{
			return IndentationTracker.GetIndentationString (offset);
		}
		
		public int GetVirtualIndentationColumn (DocumentLocation loc)
		{
			return IndentationTracker.GetVirtualIndentationColumn (loc.Line, loc.Column);
		}
		
		public int GetVirtualIndentationColumn (int lineNumber, int column)
		{
			return IndentationTracker.GetVirtualIndentationColumn (lineNumber, column);
		}
		
		public int GetVirtualIndentationColumn (int offset)
		{
			return IndentationTracker.GetVirtualIndentationColumn (offset);
		}
		
		/// <summary>
		/// Ensures the caret is not in a virtual position by adding whitespaces up to caret position.
		/// That method should always be called in an undo group.
		/// </summary>
		public int EnsureCaretIsNotVirtual ()
		{
			return EnsureIsNotVirtual (Caret.Location);
		}

		public bool IsCaretInVirtualLocation {
			get {
				DocumentLine documentLine = Document.GetLine (Caret.Line);
				if (documentLine == null)
					return true;
				return Caret.Column > documentLine.Length + 1;
			}
		}

		int EnsureIsNotVirtual (DocumentLocation loc)
		{
			return EnsureIsNotVirtual (loc.Line, loc.Column);
		}

		int EnsureIsNotVirtual (int line, int column)
		{
			DocumentLine documentLine = Document.GetLine (line);
			if (documentLine == null)
				return 0;
			if (column > documentLine.Length + 1) {
				string virtualSpace;
				if (HasIndentationTracker && documentLine.Length == 0) {
					virtualSpace = GetIndentationString (line, column);
				} else {
					virtualSpace = new string (' ', column - 1 - documentLine.Length);
				}
				var oldPreserve = Caret.PreserveSelection;
				Caret.PreserveSelection = true;
				Insert (documentLine.Offset, virtualSpace);
				Caret.PreserveSelection = oldPreserve;
				
				// No need to reposition the caret, because it's already at the correct position
				// The only difference is that the position is not virtual anymore.
				return virtualSpace.Length;
			}
			return 0;
		}

		#endregion
		
		public Stream OpenStream ()
		{
			return new MemoryStream (Encoding.UTF8.GetBytes (Document.Text), false);
		}
		
		public void RaiseUpdateAdjustmentsRequested ()
		{
			OnUpdateAdjustmentsRequested (EventArgs.Empty);
		}
		
		protected virtual void OnUpdateAdjustmentsRequested (EventArgs e)
		{
			var handler = UpdateAdjustmentsRequested;
			if (handler != null)
				handler (this, e);
		}
		
		public event EventHandler UpdateAdjustmentsRequested;

		public void RequestRecenter ()
		{
			var handler = RecenterEditor;
			if (handler != null)
				handler (this, EventArgs.Empty);
		}
		public event EventHandler RecenterEditor;

		#region Text Paste
		/// <summary>
		/// Gets or sets the text paste handler.
		/// </summary>
		public ITextPasteHandler TextPasteHandler {
			get;
			set;
		}

		public int PasteText (int offset, string text, byte[] copyData, ref IDisposable undoGroup)
		{
			if (TextPasteHandler != null) {
				string newText;
				try {
					newText = TextPasteHandler.FormatPlainText (offset, text, copyData);
				} catch (Exception e) {
					Console.WriteLine ("Text paste handler exception:" + e);
					newText = text;
				}
				if (newText != text) {
					var inserted = Insert (offset, text);
					if (options.GenerateFormattingUndoStep) {
						undoGroup.Dispose ();
						undoGroup = OpenUndoGroup ();
					}
					var result = Replace (offset, inserted, newText);
					if (Paste != null)
						Paste (offset, text, result);
					return result;
				}
			}
			var insertedChars = Insert (offset, text);
			if (options.GenerateFormattingUndoStep) {
				undoGroup.Dispose ();
				undoGroup = OpenUndoGroup ();
			}
			if (Paste != null)
				Paste (offset, text, insertedChars);
			return insertedChars;
		}

		public delegate void PasteCallback (int insertionOffset, string text, int insertedChars);
		
		public event PasteCallback Paste;
		#endregion

		#region Document delegation
		public int Length {
			get {
				return document.TextLength;
			}
		}

		public string Text {
			get {
				return document.Text;
			}
			set {
				document.Text = value;
			}
		}

		public ITextSourceVersion Version {
			get {
				return document.Version;
			}
		}

		public string GetTextBetween (int startOffset, int endOffset)
		{
			return document.GetTextBetween (startOffset, endOffset);
		}
		
		public string GetTextBetween (DocumentLocation start, DocumentLocation end)
		{
			return document.GetTextBetween (start, end);
		}
		
		public string GetTextBetween (int startLine, int startColumn, int endLine, int endColumn)
		{
			return document.GetTextBetween (startLine, startColumn, endLine, endColumn);
		}

		public string GetTextAt (int offset, int count)
		{
			return document.GetTextAt (offset, count);
		}
		
		public string GetTextAt (DocumentRegion region)
		{
			return document.GetTextAt (region);
		}

		public string GetTextAt (TextSegment segment)
		{
			return document.GetTextAt (segment);
		}
		
		public char GetCharAt (int offset)
		{
			return document.GetCharAt (offset);
		}
		
		public char GetCharAt (DocumentLocation location)
		{
			return document.GetCharAt (location);
		}

		public char GetCharAt (int line, int column)
		{
			return document.GetCharAt (line, column);
		}

		public string GetLineText (int line)
		{
			return Document.GetLineText (line);
		}
		
		public string GetLineText (int line, bool includeDelimiter)
		{
			return Document.GetLineText (line, includeDelimiter);
		}

		public IEnumerable<DocumentLine> Lines {
			get {
				return Document.Lines;
			}
		}
		
		public int LineCount {
			get {
				return Document != null ? Document.LineCount : 0;
			}
		}
		
		public int LocationToOffset (int line, int column)
		{
			return Document.LocationToOffset (line, column);
		}
		
		public int LocationToOffset (DocumentLocation location)
		{
			return Document.LocationToOffset (location);
		}
		
		public DocumentLocation OffsetToLocation (int offset)
		{
			return Document.OffsetToLocation (offset);
		}

		public string GetLineIndent (int lineNumber)
		{
			return Document.GetLineIndent (lineNumber);
		}
		
		public string GetLineIndent (DocumentLine segment)
		{
			return Document.GetLineIndent (segment);
		}
		
		public DocumentLine GetLine (int lineNumber)
		{
			return Document.GetLine (lineNumber);
		}
		
		public DocumentLine GetLineByOffset (int offset)
		{
			return Document.GetLineByOffset (offset);
		}
		
		public int OffsetToLineNumber (int offset)
		{
			return Document.OffsetToLineNumber (offset);
		}
		
		public IDisposable OpenUndoGroup()
		{
			return Document.OpenUndoGroup ();
		}

		public IDisposable OpenUndoGroup(OperationType operationType)
		{
			return Document.OpenUndoGroup (operationType);
		}
		#endregion
		
		#region Parent functions

		public void ScrollToCaret ()
		{
			if (Parent != null)
				Parent.ScrollToCaret ();
		}
		
		public void ScrollTo (int offset)
		{
			if (Parent != null)
				Parent.ScrollTo (offset);
		}
		
		public void ScrollTo (int line, int column)
		{
			if (Parent != null)
				Parent.ScrollTo (line, column);
		}

		public void ScrollTo (DocumentLocation loc)
		{
			if (Parent != null)
				Parent.ScrollTo (loc);
		}
		
		public void CenterToCaret ()
		{
			if (Parent != null)
				Parent.CenterToCaret ();
		}
		
		public void CenterTo (DocumentLocation p)
		{
			if (Parent != null)
				Parent.CenterTo (p);
		}
		
		public void CenterTo (int offset)
		{
			if (Parent != null)
				Parent.CenterTo (offset);
		}
		
		public void CenterTo (int line, int column)
		{
			if (Parent != null)
				Parent.CenterTo (line, column);
		}
		
		public void SetCaretTo (int line, int column)
		{
			SetCaretTo (line, column, true);
		}
		
		public void SetCaretTo (int line, int column, bool highlight)
		{
			SetCaretTo (line, column, highlight, true);
		}
		
		public void SetCaretTo (int line, int column, bool highlight, bool centerCaret)
		{
			if (Parent != null) {
				Parent.SetCaretTo (line, column, highlight, centerCaret);
			} else {
				Caret.Location = new DocumentLocation (line, column);
			}
		}
		#endregion
		
		#region folding
		
		public double LineHeight {
			get;
			internal set;
		}
		
		public int VisibleLineCount {
			get {
				return HeightTree.VisibleLineCount;
			}
		}	
		
		
		public double TotalHeight {
			get {
				return HeightTree.TotalHeight;
			}
		}
		
		public readonly HeightTree HeightTree;
		
		public DocumentLocation LogicalToVisualLocation (DocumentLocation location)
		{
			int line = LogicalToVisualLine (location.Line);
			var lineSegment = GetLine (location.Line);
			int column = lineSegment != null ? lineSegment.GetVisualColumn (this, location.Column) : location.Column;
			return new DocumentLocation (line, column);
		}

		public DocumentLocation LogicalToVisualLocation (int line, int column)
		{
			return LogicalToVisualLocation (new DocumentLocation (line, column));
		}

		public int LogicalToVisualLine (int logicalLine)
		{
			return HeightTree.LogicalToVisualLine (logicalLine);
		}

		public int VisualToLogicalLine (int visualLineNumber)
		{
			return HeightTree.VisualToLogicalLine (visualLineNumber);
		}
		

		void HandleTextEditorDataDocumentFolded (object sender, FoldSegmentEventArgs e)
		{
			int start = e.FoldSegment.StartLine.LineNumber;
			int end = e.FoldSegment.EndLine.LineNumber;
			
			if (e.FoldSegment.IsFolded) {
				if (e.FoldSegment.Marker != null)
					HeightTree.Unfold (e.FoldSegment.Marker, start, end - start);
				e.FoldSegment.Marker = HeightTree.Fold (start, end - start);
			} else {
				HeightTree.Unfold (e.FoldSegment.Marker, start, end - start);
				e.FoldSegment.Marker = null;
			}
		}
		
		#endregion

		#region SkipChars
		public class SkipChar
		{
			
			public int Start { get; set; }
			
			public int Offset { get; set; }

			public char Char  { get; set; }

			public override string ToString ()
			{
				return string.Format ("[SkipChar: Start={0}, Offset={1}, Char={2}]", Start, Offset, Char);
			}
		}
		
		List<SkipChar> skipChars = new List<SkipChar> ();
		
		public List<SkipChar> SkipChars {
			get {
				return skipChars;
			}
		}
		
		public void SetSkipChar (int offset, char ch)
		{
			skipChars.Add (new SkipChar () {
				Start = offset - 1,
				Offset = offset,
				Char = ch
			});
		}

		#endregion

		/// <summary>
		/// Creates the a text editor data object which document can't be changed. This is useful for 'view' only
		/// documents.
		/// </summary>
		/// <remarks>
		/// The Document itself is very fast because it uses a special case buffer and line splitter implementation.
		/// Additionally highlighting is turned off as default.
		/// </remarks>
		public static TextEditorData CreateImmutable (string input, bool suppressHighlighting = true)
		{
			return new TextEditorData (TextDocument.CreateImmutableDocument (input, suppressHighlighting));
		}
	}
}