In System.Windows.Forms:
[mono.git] / mcs / class / Managed.Windows.Forms / System.Windows.Forms / TextControl.cs
1 // Permission is hereby granted, free of charge, to any person obtaining
2 // a copy of this software and associated documentation files (the
3 // "Software"), to deal in the Software without restriction, including
4 // without limitation the rights to use, copy, modify, merge, publish,
5 // distribute, sublicense, and/or sell copies of the Software, and to
6 // permit persons to whom the Software is furnished to do so, subject to
7 // the following conditions:
8 // 
9 // The above copyright notice and this permission notice shall be
10 // included in all copies or substantial portions of the Software.
11 // 
12 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
13 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
14 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
15 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
16 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
17 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
18 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
19 //
20 // Copyright (c) 2004-2006 Novell, Inc. (http://www.novell.com)
21 //
22 // Authors:
23 //      Peter Bartok    pbartok@novell.com
24 //
25 //
26
27 // NOT COMPLETE
28
29 // There's still plenty of things missing, I've got most of it planned, just hadn't had
30 // the time to write it all yet.
31 // Stuff missing (in no particular order):
32 // - Align text after RecalculateLine
33 // - Implement tag types for hotlinks, etc.
34 // - Implement CaretPgUp/PgDown
35
36 // NOTE:
37 // selection_start.pos and selection_end.pos are 0-based
38 // selection_start.pos = first selected char
39 // selection_end.pos = first NOT-selected char
40 //
41 // FormatText methods are 1-based (as are all tags, LineTag.Start is 1 for 
42 // the first character on a line; the reason is that 0 is the position 
43 // *before* the first character on a line
44
45
46 #undef Debug
47
48 using System;
49 using System.Collections;
50 using System.Drawing;
51 using System.Drawing.Text;
52 using System.Text;
53 using RTF=System.Windows.Forms.RTF;
54
55 namespace System.Windows.Forms {
56         internal enum LineColor {
57                 Red     = 0,
58                 Black   = 1
59         }
60
61         internal enum CaretSelection {
62                 Position,       // Selection=Caret
63                 Word,           // Selection=Word under caret
64                 Line            // Selection=Line under caret
65         }
66
67         [Flags]
68         internal enum FormatSpecified {
69                 None,
70
71                 BackColor = 2,
72                 Font = 4,
73                 Color = 8,
74         }
75
76         internal enum CaretDirection {
77                 CharForward,    // Move a char to the right
78                 CharBack,       // Move a char to the left
79                 LineUp,         // Move a line up
80                 LineDown,       // Move a line down
81                 Home,           // Move to the beginning of the line
82                 End,            // Move to the end of the line
83                 PgUp,           // Move one page up
84                 PgDn,           // Move one page down
85                 CtrlPgUp,       // Move caret to the first visible char in the viewport
86                 CtrlPgDn,       // Move caret to the last visible char in the viewport
87                 CtrlHome,       // Move to the beginning of the document
88                 CtrlEnd,        // Move to the end of the document
89                 WordBack,       // Move to the beginning of the previous word (or beginning of line)
90                 WordForward,    // Move to the beginning of the next word (or end of line)
91                 SelectionStart, // Move to the beginning of the current selection
92                 SelectionEnd,   // Move to the end of the current selection
93                 CharForwardNoWrap,   // Move a char forward, but don't wrap onto the next line
94                 CharBackNoWrap      // Move a char backward, but don't wrap onto the previous line
95         }
96
97         internal enum LineEnding {
98                 Wrap,    // line wraps to the next line
99                 Limp,    // \r
100                 Hard,    // \r\n
101                 Soft,    // \r\r\n
102                 Rich,    // \n
103
104                 None
105         }
106         
107         // Being cloneable should allow for nice line and document copies...
108         internal class Line : ICloneable, IComparable {
109                 #region Local Variables
110
111                 internal Document document;
112
113                 // Stuff that matters for our line
114                 internal StringBuilder          text;                   // Characters for the line
115                 internal float[]                widths;                 // Width of each character; always one larger than text.Length
116                 internal int                    space;                  // Number of elements in text and widths
117                 internal int                    line_no;                // Line number
118                 internal LineTag                tags;                   // Tags describing the text
119                 internal int                    offset;                 // Baseline can be on the X or Y axis depending if we are in multiline mode or not
120                 internal int                    height;                 // Height of the line (height of tallest tag)
121                 internal int                    ascent;                 // Ascent of the line (ascent of the tallest tag)
122                 internal HorizontalAlignment    alignment;              // Alignment of the line
123                 internal int                    align_shift;            // Pixel shift caused by the alignment
124                 internal int                    indent;                 // Left indent for the first line
125                 internal int                    hanging_indent;         // Hanging indent (left indent for all but the first line)
126                 internal int                    right_indent;           // Right indent for all lines
127                 internal LineEnding ending;
128
129
130                 // Stuff that's important for the tree
131                 internal Line                   parent;                 // Our parent line
132                 internal Line                   left;                   // Line with smaller line number
133                 internal Line                   right;                  // Line with higher line number
134                 internal LineColor              color;                  // We're doing a black/red tree. this is the node color
135                 internal int                    DEFAULT_TEXT_LEN;       // 
136                 internal bool                   recalc;                 // Line changed
137                 #endregion      // Local Variables
138
139                 #region Constructors
140                 internal Line (Document document, LineEnding ending)
141                 {
142                         this.document = document; 
143                         color = LineColor.Red;
144                         left = null;
145                         right = null;
146                         parent = null;
147                         text = null;
148                         recalc = true;
149                         alignment = document.alignment;
150
151                         this.ending = ending;
152                 }
153
154                 internal Line(Document document, int LineNo, string Text, Font font, SolidBrush color, LineEnding ending) : this (document, ending)
155                 {
156                         space = Text.Length > DEFAULT_TEXT_LEN ? Text.Length+1 : DEFAULT_TEXT_LEN;
157
158                         text = new StringBuilder(Text, space);
159                         line_no = LineNo;
160                         this.ending = ending;
161
162                         widths = new float[space + 1];
163
164                         
165                         tags = new LineTag(this, 1);
166                         tags.font = font;
167                         tags.color = color;                             
168                 }
169
170                 internal Line(Document document, int LineNo, string Text, HorizontalAlignment align, Font font, SolidBrush color, LineEnding ending) : this(document, ending)
171                 {
172                         space = Text.Length > DEFAULT_TEXT_LEN ? Text.Length+1 : DEFAULT_TEXT_LEN;
173
174                         text = new StringBuilder(Text, space);
175                         line_no = LineNo;
176                         this.ending = ending;
177                         alignment = align;
178
179                         widths = new float[space + 1];
180
181                         
182                         tags = new LineTag(this, 1);
183                         tags.font = font;
184                         tags.color = color;
185                 }
186
187                 internal Line(Document document, int LineNo, string Text, LineTag tag, LineEnding ending) : this(document, ending)
188                 {
189                         space = Text.Length > DEFAULT_TEXT_LEN ? Text.Length+1 : DEFAULT_TEXT_LEN;
190
191                         text = new StringBuilder(Text, space);
192                         this.ending = ending;
193                         line_no = LineNo;
194
195                         widths = new float[space + 1];
196                         tags = tag;
197                 }
198
199                 #endregion      // Constructors
200
201                 #region Internal Properties
202
203                 internal int Y {
204                         get {
205                                 if (!document.multiline)
206                                         return document.top_margin;
207                                 return document.top_margin + offset;
208                         }
209                 }
210
211                 internal int X {
212                         get {
213                                 if (document.multiline)
214                                         return align_shift;
215                                 return offset + align_shift;
216                         }
217                 }
218
219                 internal int Width {
220                         get {
221                                 int res = (int) widths [text.Length];
222                                 if (!document.multiline) {
223
224                                 }
225                                 return res;
226                         }
227                 }
228
229                 internal int Indent {
230                         get {
231                                 return indent;
232                         }
233
234                         set {
235                                 indent = value;
236                                 recalc = true;
237                         }
238                 }
239
240                 internal int HangingIndent {
241                         get {
242                                 return hanging_indent;
243                         }
244
245                         set {
246                                 hanging_indent = value;
247                                 recalc = true;
248                         }
249                 }
250
251                 internal int RightIndent {
252                         get {
253                                 return right_indent;
254                         }
255
256                         set {
257                                 right_indent = value;
258                                 recalc = true;
259                         }
260                 }
261                         
262
263                 internal int Height {
264                         get {
265                                 return height;
266                         }
267
268                         set {
269                                 height = value;
270                         }
271                 }
272
273                 internal int LineNo {
274                         get {
275                                 return line_no;
276                         }
277
278                         set {
279                                 line_no = value;
280                         }
281                 }
282
283                 internal string Text {
284                         get {
285                                 return text.ToString();
286                         }
287
288                         set {
289                                 text = new StringBuilder(value, value.Length > DEFAULT_TEXT_LEN ? value.Length : DEFAULT_TEXT_LEN);
290                         }
291                 }
292
293                 internal HorizontalAlignment Alignment {
294                         get {
295                                 return alignment;
296                         }
297
298                         set {
299                                 if (alignment != value) {
300                                         alignment = value;
301                                         recalc = true;
302                                 }
303                         }
304                 }
305 #if no
306                 internal StringBuilder Text {
307                         get {
308                                 return text;
309                         }
310
311                         set {
312                                 text = value;
313                         }
314                 }
315 #endif
316                 #endregion      // Internal Properties
317
318                 #region Internal Methods
319
320                 // This doesn't do exactly what you would think, it just pulls of the \n part of the ending
321                 internal string TextWithoutEnding ()
322                 {
323                         return text.ToString (0, text.Length - document.LineEndingLength (ending));
324                 }
325
326                 internal int TextLengthWithoutEnding ()
327                 {
328                         return text.Length - document.LineEndingLength (ending);
329                 }
330
331                 internal void DrawEnding (Graphics dc, float y)
332                 {
333                         if (document.multiline)
334                                 return;
335                         LineTag last = tags;
336                         while (last.next != null)
337                                 last = last.next;
338
339                         string end_str = null;
340                         switch (document.LineEndingLength (ending)) {
341                         case 0:
342                                 return;
343                         case 1:
344                                 end_str = "\u0013";
345                                 break;
346                         case 2:
347                                 end_str = "\u0013\u0013";
348                                 break;
349                         case 3:
350                                 end_str = "\u0013\u0013\u0013";
351                                 break;
352                         }
353                         dc.DrawString (end_str, last.font, last.color,  X + widths [TextLengthWithoutEnding ()] - document.viewport_x,
354                                         y, Document.string_format);
355                 }
356
357                 
358                 // Make sure we always have enoughs space in text and widths
359                 internal void Grow(int minimum) {
360                         int     length;
361                         float[] new_widths;
362
363                         length = text.Length;
364
365                         if ((length + minimum) > space) {
366                                 // We need to grow; double the size
367
368                                 if ((length + minimum) > (space * 2)) {
369                                         new_widths = new float[length + minimum * 2 + 1];
370                                         space = length + minimum * 2;
371                                 } else {                                
372                                         new_widths = new float[space * 2 + 1];
373                                         space *= 2;
374                                 }
375                                 widths.CopyTo(new_widths, 0);
376
377                                 widths = new_widths;
378                         }
379                 }
380
381                 internal void Streamline(int lines) {
382                         LineTag current;
383                         LineTag next;
384
385                         current = this.tags;
386                         next = current.next;
387
388                         //
389                         // Catch what the loop below wont; eliminate 0 length 
390                         // tags, but only if there are other tags after us
391                         // We only eliminate text tags if there is another text tag
392                         // after it.  Otherwise we wind up trying to type on picture tags
393                         //
394                         while ((current.length == 0) && (next != null) && (next.IsTextTag)) {
395                                 tags = next;
396                                 tags.previous = null;
397                                 current = next;
398                                 next = current.next;
399                         }
400                         
401
402                         if (next == null) {
403                                 return;
404                         }
405
406                         while (next != null) {
407                                 // Take out 0 length tags unless it's the last tag in the document
408                                 if (current.IsTextTag && next.length == 0 && next.IsTextTag) {
409                                         if ((next.next != null) || (line_no != lines)) {
410                                                 current.next = next.next;
411                                                 if (current.next != null) {
412                                                         current.next.previous = current;
413                                                 }
414                                                 next = current.next;
415                                                 continue;
416                                         }
417                                 }
418                                 if (current.Combine(next)) {
419                                         next = current.next;
420                                         continue;
421                                 }
422
423                                 current = current.next;
424                                 next = current.next;
425                         }
426                 }
427
428                 /// <summary> Find the tag on a line based on the character position, pos is 0-based</summary>
429                 internal LineTag FindTag(int pos) {
430                         LineTag tag;
431
432                         if (pos == 0) {
433                                 return tags;
434                         }
435
436                         tag = this.tags;
437
438                         if (pos >= text.Length) {
439                                 pos = text.Length - 1;
440                         }
441
442                         while (tag != null) {
443                                 if (((tag.start - 1) <= pos) && (pos < (tag.start + tag.length - 1))) {
444                                         return LineTag.GetFinalTag (tag);
445                                 }
446                                 tag = tag.next;
447                         }
448                         return null;
449                 }
450
451                 /// <summary>
452                 /// Recalculate a single line using the same char for every character in the line
453                 /// </summary>
454                 
455                 internal bool RecalculatePasswordLine(Graphics g, Document doc) {
456                         LineTag tag;
457                         int     pos;
458                         int     len;
459                         float   w;
460                         bool    ret;
461                         int     descent;
462
463                         pos = 0;
464                         len = this.text.Length;
465                         tag = this.tags;
466                         ascent = 0;
467                         tag.shift = 0;
468
469                         this.recalc = false;
470                         widths[0] = document.left_margin + indent;
471
472                         w = g.MeasureString(doc.password_char, tags.font, 10000, Document.string_format).Width;
473
474                         if (this.height != (int)tag.font.Height) {
475                                 ret = true;
476                         } else {
477                                 ret = false;
478                         }
479
480                         this.height = (int)tag.font.Height;
481                         tag.height = this.height;
482
483                         XplatUI.GetFontMetrics(g, tag.font, out tag.ascent, out descent);
484                         this.ascent = tag.ascent;
485
486                         while (pos < len) {
487                                 pos++;
488                                 widths[pos] = widths[pos-1] + w;
489                         }
490
491                         return ret;
492                 }
493
494                 /// <summary>
495                 /// Go through all tags on a line and recalculate all size-related values;
496                 /// returns true if lineheight changed
497                 /// </summary>
498                 internal bool RecalculateLine(Graphics g, Document doc) {
499                         LineTag tag;
500                         int     pos;
501                         int     len;
502                         SizeF   size;
503                         float   w;
504                         int     prev_offset;
505                         bool    retval;
506                         bool    wrapped;
507                         Line    line;
508                         int     wrap_pos;
509
510                         pos = 0;
511                         len = this.text.Length;
512                         tag = this.tags;
513                         prev_offset = this.offset;      // For drawing optimization calculations
514                         this.height = 0;                // Reset line height
515                         this.ascent = 0;                // Reset the ascent for the line
516                         tag.shift = 0;
517
518                         if (ending == LineEnding.Wrap) {
519                                 widths[0] = document.left_margin + hanging_indent;
520                         } else {
521                                 widths[0] = document.left_margin + indent;
522                         }
523
524                         this.recalc = false;
525                         retval = false;
526                         wrapped = false;
527
528                         wrap_pos = 0;
529
530                         while (pos < len) {
531
532                                 while (tag.length == 0) {       // We should always have tags after a tag.length==0 unless len==0
533                                         tag.ascent = 0;
534                                         tag.shift = 0;
535                                         tag = tag.next;
536                                 }
537
538                                 size = tag.SizeOfPosition (g, pos);
539                                 w = size.Width;
540
541                                 if (Char.IsWhiteSpace(text[pos])) {
542                                         wrap_pos = pos + 1;
543                                 }
544
545                                 if (doc.wrap) {
546                                         if ((wrap_pos > 0) && (wrap_pos != len) && (widths[pos] + w) + 5 > (doc.viewport_width - this.right_indent)) {
547                                                 // Make sure to set the last width of the line before wrapping
548                                                 widths [pos + 1] = widths [pos] + w;
549
550                                                 pos = wrap_pos;
551                                                 len = text.Length;
552                                                 doc.Split(this, tag, pos);
553                                                 ending = LineEnding.Wrap;
554                                                 len = this.text.Length;
555                                                 
556                                                 retval = true;
557                                                 wrapped = true;
558                                         }  else if (pos > 1 && (widths[pos] + w) > (doc.viewport_width - this.right_indent)) {
559                                                 // No suitable wrap position was found so break right in the middle of a word
560
561                                                 // Make sure to set the last width of the line before wrapping
562                                                 widths [pos + 1] = widths [pos] + w;
563
564                                                 doc.Split(this, tag, pos);
565                                                 ending = LineEnding.Wrap;
566                                                 len = this.text.Length;
567                                                 retval = true;
568                                                 wrapped = true;
569                                         }
570                                 }
571
572                                 // Contract all wrapped lines that follow back into our line
573                                 if (!wrapped) {
574                                         pos++;
575
576                                         widths[pos] = widths[pos-1] + w;
577
578                                         if (pos == len) {
579                                                 line = doc.GetLine(this.line_no + 1);
580                                                 if ((line != null) && (ending == LineEnding.Wrap || ending == LineEnding.None)) {
581                                                         // Pull the two lines together
582                                                         doc.Combine(this.line_no, this.line_no + 1);
583                                                         len = this.text.Length;
584                                                         retval = true;
585                                                 }
586                                         }
587                                 }
588
589                                 if (pos == (tag.start-1 + tag.length)) {
590                                         // We just found the end of our current tag
591                                         tag.height = tag.MaxHeight ();
592
593                                         // Check if we're the tallest on the line (so far)
594                                         if (tag.height > this.height) {
595                                                 this.height = tag.height;               // Yep; make sure the line knows
596                                         }
597
598                                         if (tag.ascent == 0) {
599                                                 int     descent;
600
601                                                 XplatUI.GetFontMetrics(g, tag.font, out tag.ascent, out descent);
602                                         }
603
604                                         if (tag.ascent > this.ascent) {
605                                                 LineTag         t;
606
607                                                 // We have a tag that has a taller ascent than the line;
608                                                 t = tags;
609                                                 while (t != null && t != tag) {
610                                                         t.shift = tag.ascent - t.ascent;
611                                                         t = t.next;
612                                                 }
613
614                                                 // Save on our line
615                                                 this.ascent = tag.ascent;
616                                         } else {
617                                                 tag.shift = this.ascent - tag.ascent;
618                                         }
619
620                                         tag = tag.next;
621                                         if (tag != null) {
622                                                 tag.shift = 0;
623                                                 wrap_pos = pos;
624                                         }
625                                 }
626                         }
627
628                         if (this.height == 0) {
629                                 this.height = tags.font.Height;
630                                 tag.height = this.height;
631                         }
632
633                         if (prev_offset != offset) {
634                                 retval = true;
635                         }
636                         return retval;
637                 }
638                 #endregion      // Internal Methods
639
640                 #region Administrative
641                 public int CompareTo(object obj) {
642                         if (obj == null) {
643                                 return 1;
644                         }
645
646                         if (! (obj is Line)) {
647                                 throw new ArgumentException("Object is not of type Line", "obj");
648                         }
649
650                         if (line_no < ((Line)obj).line_no) {
651                                 return -1;
652                         } else if (line_no > ((Line)obj).line_no) {
653                                 return 1;
654                         } else {
655                                 return 0;
656                         }
657                 }
658
659                 public object Clone() {
660                         Line    clone;
661
662                         clone = new Line (document, ending);
663
664                         clone.text = text;
665
666                         if (left != null) {
667                                 clone.left = (Line)left.Clone();
668                         }
669
670                         if (left != null) {
671                                 clone.left = (Line)left.Clone();
672                         }
673
674                         return clone;
675                 }
676
677                 internal object CloneLine() {
678                         Line    clone;
679
680                         clone = new Line (document, ending);
681
682                         clone.text = text;
683
684                         return clone;
685                 }
686
687                 public override bool Equals(object obj) {
688                         if (obj == null) {
689                                 return false;
690                         }
691
692                         if (!(obj is Line)) {
693                                 return false;
694                         }
695
696                         if (obj == this) {
697                                 return true;
698                         }
699
700                         if (line_no == ((Line)obj).line_no) {
701                                 return true;
702                         }
703
704                         return false;
705                 }
706
707                 public override int GetHashCode() {
708                         return base.GetHashCode ();
709                 }
710
711                 public override string ToString() {
712                         return "Line " + line_no;
713                 }
714
715                 #endregion      // Administrative
716         }
717
718         internal class Document : ICloneable, IEnumerable {
719                 #region Structures
720                 // FIXME - go through code and check for places where
721                 // we do explicit comparisons instead of using the compare overloads
722                 internal struct Marker {
723                         internal Line           line;
724                         internal LineTag        tag;
725                         internal int            pos;
726                         internal int            height;
727
728                         public static bool operator<(Marker lhs, Marker rhs) {
729                                 if (lhs.line.line_no < rhs.line.line_no) {
730                                         return true;
731                                 }
732
733                                 if (lhs.line.line_no == rhs.line.line_no) {
734                                         if (lhs.pos < rhs.pos) {
735                                                 return true;
736                                         }
737                                 }
738                                 return false;
739                         }
740
741                         public static bool operator>(Marker lhs, Marker rhs) {
742                                 if (lhs.line.line_no > rhs.line.line_no) {
743                                         return true;
744                                 }
745
746                                 if (lhs.line.line_no == rhs.line.line_no) {
747                                         if (lhs.pos > rhs.pos) {
748                                                 return true;
749                                         }
750                                 }
751                                 return false;
752                         }
753
754                         public static bool operator==(Marker lhs, Marker rhs) {
755                                 if ((lhs.line.line_no == rhs.line.line_no) && (lhs.pos == rhs.pos)) {
756                                         return true;
757                                 }
758                                 return false;
759                         }
760
761                         public static bool operator!=(Marker lhs, Marker rhs) {
762                                 if ((lhs.line.line_no != rhs.line.line_no) || (lhs.pos != rhs.pos)) {
763                                         return true;
764                                 }
765                                 return false;
766                         }
767
768                         public void Combine(Line move_to_line, int move_to_line_length) {
769                                 line = move_to_line;
770                                 pos += move_to_line_length;
771                                 tag = LineTag.FindTag(line, pos);
772                         }
773
774                         // This is for future use, right now Document.Split does it by hand, with some added shortcut logic
775                         public void Split(Line move_to_line, int split_at) {
776                                 line = move_to_line;
777                                 pos -= split_at;
778                                 tag = LineTag.FindTag(line, pos);
779                         }
780
781                         public override bool Equals(object obj) {
782                                    return this==(Marker)obj;
783                         }
784
785                         public override int GetHashCode() {
786                                 return base.GetHashCode ();
787                         }
788
789                         public override string ToString() {
790                                 return "Marker Line " + line + ", Position " + pos;
791                         }
792
793                 }
794                 #endregion Structures
795
796                 #region Local Variables
797                 private Line            document;
798                 private int             lines;
799                 private Line            sentinel;
800                 private int             document_id;
801                 private Random          random = new Random();
802                 internal string         password_char;
803                 private StringBuilder   password_cache;
804                 private bool            calc_pass;
805                 private int             char_count;
806
807                 // For calculating widths/heights
808                 public static readonly StringFormat string_format = new StringFormat (StringFormat.GenericTypographic);
809
810                 private int             recalc_suspended;
811                 private bool            recalc_pending;
812                 private int             recalc_start = 1;   // This starts at one, since lines are 1 based
813                 private int             recalc_end;
814                 private bool            recalc_optimize;
815
816                 private int             update_suspended;
817                 private bool update_pending;
818                 private int update_start = 1;
819
820                 internal bool           multiline;
821                 internal HorizontalAlignment alignment;
822                 internal bool           wrap;
823
824                 internal UndoManager    undo;
825
826                 internal Marker         caret;
827                 internal Marker         selection_start;
828                 internal Marker         selection_end;
829                 internal bool           selection_visible;
830                 internal Marker         selection_anchor;
831                 internal Marker         selection_prev;
832                 internal bool           selection_end_anchor;
833
834                 internal int            viewport_x;
835                 internal int            viewport_y;             // The visible area of the document
836                 internal int            viewport_width;
837                 internal int            viewport_height;
838
839                 internal int            document_x;             // Width of the document
840                 internal int            document_y;             // Height of the document
841
842                 internal Rectangle      invalid;
843
844                 internal int            crlf_size;              // 1 or 2, depending on whether we use \r\n or just \n
845
846                 internal TextBoxBase    owner;                  // Who's owning us?
847                 static internal int     caret_width = 1;
848                 static internal int     caret_shift = 1;
849
850                 internal int left_margin = 2;  // A left margin for all lines
851                 internal int top_margin = 2;
852                 internal int right_margin = 2;
853                 #endregion      // Local Variables
854
855                 #region Constructors
856                 internal Document (TextBoxBase owner)
857                 {
858                         lines = 0;
859
860                         this.owner = owner;
861
862                         multiline = true;
863                         password_char = "";
864                         calc_pass = false;
865                         recalc_pending = false;
866
867                         // Tree related stuff
868                         sentinel = new Line (this, LineEnding.None);
869                         sentinel.color = LineColor.Black;
870
871                         document = sentinel;
872
873                         // We always have a blank line
874                         owner.HandleCreated += new EventHandler(owner_HandleCreated);
875                         owner.VisibleChanged += new EventHandler(owner_VisibleChanged);
876
877                         Add (1, String.Empty, owner.Font, ThemeEngine.Current.ResPool.GetSolidBrush (owner.ForeColor), LineEnding.None);
878
879                         undo = new UndoManager (this);
880
881                         selection_visible = false;
882                         selection_start.line = this.document;
883                         selection_start.pos = 0;
884                         selection_start.tag = selection_start.line.tags;
885                         selection_end.line = this.document;
886                         selection_end.pos = 0;
887                         selection_end.tag = selection_end.line.tags;
888                         selection_anchor.line = this.document;
889                         selection_anchor.pos = 0;
890                         selection_anchor.tag = selection_anchor.line.tags;
891                         caret.line = this.document;
892                         caret.pos = 0;
893                         caret.tag = caret.line.tags;
894
895                         viewport_x = 0;
896                         viewport_y = 0;
897
898                         crlf_size = 2;
899
900                         // Default selection is empty
901
902                         document_id = random.Next();
903
904                         string_format.Trimming = StringTrimming.None;
905                         string_format.FormatFlags = StringFormatFlags.DisplayFormatControl;
906
907                         UpdateMargins ();
908                 }
909                 #endregion
910
911                 #region Internal Properties
912                 internal Line Root {
913                         get {
914                                 return document;
915                         }
916
917                         set {
918                                 document = value;
919                         }
920                 }
921
922                 internal int Lines {
923                         get {
924                                 return lines;
925                         }
926                 }
927
928                 internal Line CaretLine {
929                         get {
930                                 return caret.line;
931                         }
932                 }
933
934                 internal int CaretPosition {
935                         get {
936                                 return caret.pos;
937                         }
938                 }
939
940                 internal Point Caret {
941                         get {
942                                 return new Point((int)caret.tag.line.widths[caret.pos] + caret.line.X, caret.line.Y);
943                         }
944                 }
945
946                 internal LineTag CaretTag {
947                         get {
948                                 return caret.tag;
949                         }
950
951                         set {
952                                 caret.tag = value;
953                         }
954                 }
955
956                 internal int CRLFSize {
957                         get {
958                                 return crlf_size;
959                         }
960
961                         set {
962                                 crlf_size = value;
963                         }
964                 }
965
966                 internal string PasswordChar {
967                         get {
968                                 return password_char;
969                         }
970
971                         set {
972                                 password_char = value;
973                                 PasswordCache.Length = 0;
974                                 if ((password_char.Length != 0) && (password_char[0] != '\0')) {
975                                         calc_pass = true;
976                                 } else {
977                                         calc_pass = false;
978                                 }
979                         }
980                 }
981
982                 private StringBuilder PasswordCache {
983                         get { 
984                                 if (password_cache == null) 
985                                           password_cache = new StringBuilder(); 
986                                 return password_cache;
987                         }
988                 }
989
990                 internal int ViewPortX {
991                         get {
992                                 return viewport_x;
993                         }
994
995                         set {
996                                 viewport_x = value;
997                         }
998                 }
999
1000                 internal int Length {
1001                         get {
1002                                 return char_count + lines - 1;  // Add \n for each line but the last
1003                         }
1004                 }
1005
1006                 private int CharCount {
1007                         get {
1008                                 return char_count;
1009                         }
1010
1011                         set {
1012                                 char_count = value;
1013
1014                                 if (LengthChanged != null) {
1015                                         LengthChanged(this, EventArgs.Empty);
1016                                 }
1017                         }
1018                 }
1019
1020                 internal int ViewPortY {
1021                         get {
1022                                 return viewport_y;
1023                         }
1024
1025                         set {
1026                                 viewport_y = value;
1027                         }
1028                 }
1029
1030                 internal int ViewPortWidth {
1031                         get {
1032                                 return viewport_width;
1033                         }
1034
1035                         set {
1036                                 viewport_width = value;
1037                         }
1038                 }
1039
1040                 internal int ViewPortHeight {
1041                         get {
1042                                 return viewport_height;
1043                         }
1044
1045                         set {
1046                                 viewport_height = value;
1047                         }
1048                 }
1049
1050
1051                 internal int Width {
1052                         get {
1053                                 return this.document_x;
1054                         }
1055                 }
1056
1057                 internal int Height {
1058                         get {
1059                                 return this.document_y;
1060                         }
1061                 }
1062
1063                 internal bool SelectionVisible {
1064                         get {
1065                                 return selection_visible;
1066                         }
1067                 }
1068
1069                 internal bool Wrap {
1070                         get {
1071                                 return wrap;
1072                         }
1073
1074                         set {
1075                                 wrap = value;
1076                         }
1077                 }
1078
1079                 #endregion      // Internal Properties
1080
1081                 #region Private Methods
1082
1083                 internal void UpdateMargins ()
1084                 {
1085                         switch (owner.actual_border_style) {
1086                                 case BorderStyle.None:
1087                                         left_margin = 0;
1088                                         top_margin = 0;
1089                                         right_margin = 1;
1090                                         break;
1091                                 case BorderStyle.FixedSingle:
1092                                         left_margin = 2;
1093                                         top_margin = 2;
1094                                         right_margin = 3;
1095                                         break;
1096                                 case BorderStyle.Fixed3D:
1097                                         left_margin = 1;
1098                                         top_margin = 1;
1099                                         right_margin = 2;
1100                                         break;
1101                         }
1102                 }
1103
1104                 internal void SuspendRecalc ()
1105                 {
1106                         recalc_suspended++;
1107                 }
1108
1109                 internal void ResumeRecalc (bool immediate_update)
1110                 {
1111                         if (recalc_suspended > 0)
1112                                 recalc_suspended--;
1113
1114                         if (immediate_update && recalc_suspended == 0 && recalc_pending) {
1115                                 RecalculateDocument (owner.CreateGraphicsInternal(), recalc_start, recalc_end, recalc_optimize);
1116                                 recalc_pending = false;
1117                         }
1118                 }
1119
1120                 internal void SuspendUpdate ()
1121                 {
1122                         update_suspended++;
1123                 }
1124
1125                 internal void ResumeUpdate (bool immediate_update)
1126                 {
1127                         if (update_suspended > 0)
1128                                 update_suspended--;
1129
1130                         if (immediate_update && update_suspended == 0 && update_pending) {
1131                                 UpdateView (GetLine (update_start), 0);
1132                                 update_pending = false;
1133                         }
1134                 }
1135
1136                 // For debugging
1137                 internal int DumpTree(Line line, bool with_tags) {
1138                         int     total;
1139
1140                         total = 1;
1141
1142                         Console.Write("Line {0} [# {1}], Y: {2}, ending style: {3},  Text: '{4}'",
1143                                         line.line_no, line.GetHashCode(), line.Y, line.ending,
1144                                         line.text != null ? line.text.ToString() : "undefined");
1145
1146                         if (line.left == sentinel) {
1147                                 Console.Write(", left = sentinel");
1148                         } else if (line.left == null) {
1149                                 Console.Write(", left = NULL");
1150                         }
1151
1152                         if (line.right == sentinel) {
1153                                 Console.Write(", right = sentinel");
1154                         } else if (line.right == null) {
1155                                 Console.Write(", right = NULL");
1156                         }
1157
1158                         Console.WriteLine("");
1159
1160                         if (with_tags) {
1161                                 LineTag tag;
1162                                 int     count;
1163                                 int     length;
1164
1165                                 tag = line.tags;
1166                                 count = 1;
1167                                 length = 0;
1168                                 Console.Write("   Tags: ");
1169                                 while (tag != null) {
1170                                         Console.Write("{0} <{1}>-<{2}>", count++, tag.start, tag.end
1171                                                         /*line.text.ToString (tag.start - 1, tag.length)*/);
1172                                         length += tag.length;
1173
1174                                         if (tag.line != line) {
1175                                                 Console.Write("BAD line link");
1176                                                 throw new Exception("Bad line link in tree");
1177                                         }
1178                                         tag = tag.next;
1179                                         if (tag != null) {
1180                                                 Console.Write(", ");
1181                                         }
1182                                 }
1183                                 if (length > line.text.Length) {
1184                                         throw new Exception(String.Format("Length of tags more than length of text on line (expected {0} calculated {1})", line.text.Length, length));
1185                                 } else if (length < line.text.Length) {
1186                                         throw new Exception(String.Format("Length of tags less than length of text on line (expected {0} calculated {1})", line.text.Length, length));
1187                                 }
1188                                 Console.WriteLine("");
1189                         }
1190                         if (line.left != null) {
1191                                 if (line.left != sentinel) {
1192                                         total += DumpTree(line.left, with_tags);
1193                                 }
1194                         } else {
1195                                 if (line != sentinel) {
1196                                         throw new Exception("Left should not be NULL");
1197                                 }
1198                         }
1199
1200                         if (line.right != null) {
1201                                 if (line.right != sentinel) {
1202                                         total += DumpTree(line.right, with_tags);
1203                                 }
1204                         } else {
1205                                 if (line != sentinel) {
1206                                         throw new Exception("Right should not be NULL");
1207                                 }
1208                         }
1209
1210                         for (int i = 1; i <= this.lines; i++) {
1211                                 if (GetLine(i) == null) {
1212                                         throw new Exception(String.Format("Hole in line order, missing {0}", i));
1213                                 }
1214                         }
1215
1216                         if (line == this.Root) {
1217                                 if (total < this.lines) {
1218                                         throw new Exception(String.Format("Not enough nodes in tree, found {0}, expected {1}", total, this.lines));
1219                                 } else if (total > this.lines) {
1220                                         throw new Exception(String.Format("Too many nodes in tree, found {0}, expected {1}", total, this.lines));
1221                                 }
1222                         }
1223
1224                         return total;
1225                 }
1226
1227                 private void SetSelectionVisible (bool value)
1228                 {
1229                         selection_visible = value;
1230
1231                         // cursor and selection are enemies, we can't have both in the same room at the same time
1232                         if (owner.IsHandleCreated && !owner.show_caret_w_selection)
1233                                 XplatUI.CaretVisible (owner.Handle, !selection_visible);
1234                 }
1235
1236                 private void DecrementLines(int line_no) {
1237                         int     current;
1238
1239                         current = line_no;
1240                         while (current <= lines) {
1241                                 GetLine(current).line_no--;
1242                                 current++;
1243                         }
1244                         return;
1245                 }
1246
1247                 private void IncrementLines(int line_no) {
1248                         int     current;
1249
1250                         current = this.lines;
1251                         while (current >= line_no) {
1252                                 GetLine(current).line_no++;
1253                                 current--;
1254                         }
1255                         return;
1256                 }
1257
1258                 private void RebalanceAfterAdd(Line line1) {
1259                         Line    line2;
1260
1261                         while ((line1 != document) && (line1.parent.color == LineColor.Red)) {
1262                                 if (line1.parent == line1.parent.parent.left) {
1263                                         line2 = line1.parent.parent.right;
1264
1265                                         if ((line2 != null) && (line2.color == LineColor.Red)) {
1266                                                 line1.parent.color = LineColor.Black;
1267                                                 line2.color = LineColor.Black;
1268                                                 line1.parent.parent.color = LineColor.Red;
1269                                                 line1 = line1.parent.parent;
1270                                         } else {
1271                                                 if (line1 == line1.parent.right) {
1272                                                         line1 = line1.parent;
1273                                                         RotateLeft(line1);
1274                                                 }
1275
1276                                                 line1.parent.color = LineColor.Black;
1277                                                 line1.parent.parent.color = LineColor.Red;
1278
1279                                                 RotateRight(line1.parent.parent);
1280                                         }
1281                                 } else {
1282                                         line2 = line1.parent.parent.left;
1283
1284                                         if ((line2 != null) && (line2.color == LineColor.Red)) {
1285                                                 line1.parent.color = LineColor.Black;
1286                                                 line2.color = LineColor.Black;
1287                                                 line1.parent.parent.color = LineColor.Red;
1288                                                 line1 = line1.parent.parent;
1289                                         } else {
1290                                                 if (line1 == line1.parent.left) {
1291                                                         line1 = line1.parent;
1292                                                         RotateRight(line1);
1293                                                 }
1294
1295                                                 line1.parent.color = LineColor.Black;
1296                                                 line1.parent.parent.color = LineColor.Red;
1297                                                 RotateLeft(line1.parent.parent);
1298                                         }
1299                                 }
1300                         }
1301                         document.color = LineColor.Black;
1302                 }
1303
1304                 private void RebalanceAfterDelete(Line line1) {
1305                         Line line2;
1306
1307                         while ((line1 != document) && (line1.color == LineColor.Black)) {
1308                                 if (line1 == line1.parent.left) {
1309                                         line2 = line1.parent.right;
1310                                         if (line2.color == LineColor.Red) { 
1311                                                 line2.color = LineColor.Black;
1312                                                 line1.parent.color = LineColor.Red;
1313                                                 RotateLeft(line1.parent);
1314                                                 line2 = line1.parent.right;
1315                                         }
1316                                         if ((line2.left.color == LineColor.Black) && (line2.right.color == LineColor.Black)) { 
1317                                                 line2.color = LineColor.Red;
1318                                                 line1 = line1.parent;
1319                                         } else {
1320                                                 if (line2.right.color == LineColor.Black) {
1321                                                         line2.left.color = LineColor.Black;
1322                                                         line2.color = LineColor.Red;
1323                                                         RotateRight(line2);
1324                                                         line2 = line1.parent.right;
1325                                                 }
1326                                                 line2.color = line1.parent.color;
1327                                                 line1.parent.color = LineColor.Black;
1328                                                 line2.right.color = LineColor.Black;
1329                                                 RotateLeft(line1.parent);
1330                                                 line1 = document;
1331                                         }
1332                                 } else { 
1333                                         line2 = line1.parent.left;
1334                                         if (line2.color == LineColor.Red) {
1335                                                 line2.color = LineColor.Black;
1336                                                 line1.parent.color = LineColor.Red;
1337                                                 RotateRight(line1.parent);
1338                                                 line2 = line1.parent.left;
1339                                         }
1340                                         if ((line2.right.color == LineColor.Black) && (line2.left.color == LineColor.Black)) {
1341                                                 line2.color = LineColor.Red;
1342                                                 line1 = line1.parent;
1343                                         } else {
1344                                                 if (line2.left.color == LineColor.Black) {
1345                                                         line2.right.color = LineColor.Black;
1346                                                         line2.color = LineColor.Red;
1347                                                         RotateLeft(line2);
1348                                                         line2 = line1.parent.left;
1349                                                 }
1350                                                 line2.color = line1.parent.color;
1351                                                 line1.parent.color = LineColor.Black;
1352                                                 line2.left.color = LineColor.Black;
1353                                                 RotateRight(line1.parent);
1354                                                 line1 = document;
1355                                         }
1356                                 }
1357                         }
1358                         line1.color = LineColor.Black;
1359                 }
1360
1361                 private void RotateLeft(Line line1) {
1362                         Line    line2 = line1.right;
1363
1364                         line1.right = line2.left;
1365
1366                         if (line2.left != sentinel) {
1367                                 line2.left.parent = line1;
1368                         }
1369
1370                         if (line2 != sentinel) {
1371                                 line2.parent = line1.parent;
1372                         }
1373
1374                         if (line1.parent != null) {
1375                                 if (line1 == line1.parent.left) {
1376                                         line1.parent.left = line2;
1377                                 } else {
1378                                         line1.parent.right = line2;
1379                                 }
1380                         } else {
1381                                 document = line2;
1382                         }
1383
1384                         line2.left = line1;
1385                         if (line1 != sentinel) {
1386                                 line1.parent = line2;
1387                         }
1388                 }
1389
1390                 private void RotateRight(Line line1) {
1391                         Line line2 = line1.left;
1392
1393                         line1.left = line2.right;
1394
1395                         if (line2.right != sentinel) {
1396                                 line2.right.parent = line1;
1397                         }
1398
1399                         if (line2 != sentinel) {
1400                                 line2.parent = line1.parent;
1401                         }
1402
1403                         if (line1.parent != null) {
1404                                 if (line1 == line1.parent.right) {
1405                                         line1.parent.right = line2;
1406                                 } else {
1407                                         line1.parent.left = line2;
1408                                 }
1409                         } else {
1410                                 document = line2;
1411                         }
1412
1413                         line2.right = line1;
1414                         if (line1 != sentinel) {
1415                                 line1.parent = line2;
1416                         }
1417                 }        
1418
1419
1420                 internal void UpdateView(Line line, int pos) {
1421                         if (!owner.IsHandleCreated) {
1422                                 return;
1423                         }
1424
1425                         if (update_suspended > 0) {
1426                                 update_start = Math.Min (update_start, line.line_no);
1427                                 // update_end = Math.Max (update_end, line.line_no);
1428                                 // recalc_optimize = true;
1429                                 update_pending = true;
1430                                 return;
1431                         }
1432
1433                         // Optimize invalidation based on Line alignment
1434                         if (RecalculateDocument(owner.CreateGraphicsInternal(), line.line_no, line.line_no, true)) {
1435                                 // Lineheight changed, invalidate the rest of the document
1436                                 if ((line.Y - viewport_y) >=0 ) {
1437                                         // We formatted something that's in view, only draw parts of the screen
1438                                         owner.Invalidate(new Rectangle(0, line.Y - viewport_y, viewport_width, owner.Height - line.Y - viewport_y));
1439                                 } else {
1440                                         // The tag was above the visible area, draw everything
1441                                         owner.Invalidate();
1442                                 }
1443                         } else {
1444                                 switch(line.alignment) {
1445                                         case HorizontalAlignment.Left: {
1446                                                 owner.Invalidate(new Rectangle(line.X + (int)line.widths[pos] - viewport_x - 1, line.Y - viewport_y, viewport_width, line.height + 1));
1447                                                 break;
1448                                         }
1449
1450                                         case HorizontalAlignment.Center: {
1451                                                 owner.Invalidate(new Rectangle(line.X, line.Y - viewport_y, viewport_width, line.height + 1));
1452                                                 break;
1453                                         }
1454
1455                                         case HorizontalAlignment.Right: {
1456                                                 owner.Invalidate(new Rectangle(line.X, line.Y - viewport_y, (int)line.widths[pos + 1] - viewport_x + line.X, line.height + 1));
1457                                                 break;
1458                                         }
1459                                 }
1460                         }
1461                 }
1462
1463
1464                 // Update display from line, down line_count lines; pos is unused, but required for the signature
1465                 internal void UpdateView(Line line, int line_count, int pos) {
1466                         if (!owner.IsHandleCreated) {
1467                                 return;
1468                         }
1469
1470                         if (recalc_suspended > 0) {
1471                                 recalc_start = Math.Min (recalc_start, line.line_no);
1472                                 recalc_end = Math.Max (recalc_end, line.line_no + line_count);
1473                                 recalc_optimize = true;
1474                                 recalc_pending = true;
1475                                 return;
1476                         }
1477
1478                         int start_line_top = line.Y;                    
1479
1480                         int end_line_bottom;
1481                         Line end_line;
1482
1483                         end_line = GetLine (line.line_no + line_count);
1484                         if (end_line == null)
1485                                 end_line = GetLine (lines);
1486
1487
1488                         end_line_bottom = end_line.Y + end_line.height;
1489                         
1490                         if (RecalculateDocument(owner.CreateGraphicsInternal(), line.line_no, line.line_no + line_count, true)) {
1491                                 // Lineheight changed, invalidate the rest of the document
1492                                 if ((line.Y - viewport_y) >=0 ) {
1493                                         // We formatted something that's in view, only draw parts of the screen
1494                                         owner.Invalidate(new Rectangle(0, line.Y - viewport_y, viewport_width, owner.Height - line.Y - viewport_y));
1495                                 } else {
1496                                         // The tag was above the visible area, draw everything
1497                                         owner.Invalidate();
1498                                 }
1499                         } else {
1500                                 int x = 0 - viewport_x;
1501                                 int w = viewport_width;
1502                                 int y = Math.Min (start_line_top - viewport_y, line.Y - viewport_y);
1503                                 int h = Math.Max (end_line_bottom - y, end_line.Y + end_line.height - y);
1504
1505                                 owner.Invalidate (new Rectangle (x, y, w, h));
1506                         }
1507                 }
1508                 #endregion      // Private Methods
1509
1510                 #region Internal Methods
1511                 // Clear the document and reset state
1512                 internal void Empty() {
1513
1514                         document = sentinel;
1515                         lines = 0;
1516
1517                         // We always have a blank line
1518                         Add (1, String.Empty, owner.Font, ThemeEngine.Current.ResPool.GetSolidBrush (owner.ForeColor), LineEnding.None);
1519                         
1520                         this.RecalculateDocument(owner.CreateGraphicsInternal());
1521                         PositionCaret(0, 0);
1522
1523                         SetSelectionVisible (false);
1524
1525                         selection_start.line = this.document;
1526                         selection_start.pos = 0;
1527                         selection_start.tag = selection_start.line.tags;
1528                         selection_end.line = this.document;
1529                         selection_end.pos = 0;
1530                         selection_end.tag = selection_end.line.tags;
1531                         char_count = 0;
1532
1533                         viewport_x = 0;
1534                         viewport_y = 0;
1535
1536                         document_x = 0;
1537                         document_y = 0;
1538
1539                         if (owner.IsHandleCreated)
1540                                 owner.Invalidate ();
1541                 }
1542
1543                 internal void PositionCaret(Line line, int pos) {
1544                         caret.tag = line.FindTag (pos);
1545
1546                         MoveCaretToTextTag ();
1547
1548                         caret.line = line;
1549                         caret.pos = pos;
1550
1551                         if (owner.IsHandleCreated) {
1552                                 if (owner.Focused) {
1553                                         if (caret.height != caret.tag.height)
1554                                                 XplatUI.CreateCaret (owner.Handle, caret_width, caret.height);
1555                                         XplatUI.SetCaretPos(owner.Handle, (int)caret.tag.line.widths[caret.pos] + caret.line.X - viewport_x, caret.line.Y + caret.tag.shift - viewport_y + caret_shift);
1556                                 }
1557
1558                                 if (CaretMoved != null) CaretMoved(this, EventArgs.Empty);
1559                         }
1560
1561                         // We set this at the end because we use the heights to determine whether or
1562                         // not we need to recreate the caret
1563                         caret.height = caret.tag.height;
1564
1565                 }
1566
1567                 internal void PositionCaret(int x, int y) {
1568                         if (!owner.IsHandleCreated) {
1569                                 return;
1570                         }
1571
1572                         caret.tag = FindCursor(x, y, out caret.pos);
1573
1574                         MoveCaretToTextTag ();
1575                         
1576                         caret.line = caret.tag.line;
1577                         caret.height = caret.tag.height;
1578
1579                         if (owner.ShowSelection && (!selection_visible || owner.show_caret_w_selection)) {
1580                                 XplatUI.CreateCaret (owner.Handle, caret_width, caret.height);
1581                                 XplatUI.SetCaretPos(owner.Handle, (int)caret.tag.line.widths[caret.pos] + caret.line.X - viewport_x, caret.line.Y + caret.tag.shift - viewport_y + caret_shift);
1582                         }
1583
1584                         if (CaretMoved != null) CaretMoved(this, EventArgs.Empty);
1585                 }
1586
1587                 internal void CaretHasFocus() {
1588                         if ((caret.tag != null) && owner.IsHandleCreated) {
1589                                 XplatUI.CreateCaret(owner.Handle, caret_width, caret.height);
1590                                 XplatUI.SetCaretPos(owner.Handle, (int)caret.tag.line.widths[caret.pos] + caret.line.X - viewport_x, caret.line.Y + caret.tag.shift - viewport_y + caret_shift);
1591
1592                                 DisplayCaret ();
1593                         }
1594
1595                         if (owner.IsHandleCreated && SelectionLength () > 0) {
1596                                 InvalidateSelectionArea ();
1597                         }
1598                 }
1599
1600                 internal void CaretLostFocus() {
1601                         if (!owner.IsHandleCreated) {
1602                                 return;
1603                         }
1604                         XplatUI.DestroyCaret(owner.Handle);
1605                 }
1606
1607                 internal void AlignCaret() {
1608                         if (!owner.IsHandleCreated) {
1609                                 return;
1610                         }
1611
1612                         caret.tag = LineTag.FindTag (caret.line, caret.pos);
1613
1614                         MoveCaretToTextTag ();
1615
1616                         caret.height = caret.tag.height;
1617
1618                         if (owner.Focused) {
1619                                 XplatUI.CreateCaret(owner.Handle, caret_width, caret.height);
1620                                 XplatUI.SetCaretPos(owner.Handle, (int)caret.tag.line.widths[caret.pos] + caret.line.X - viewport_x, caret.line.Y + caret.tag.shift - viewport_y + caret_shift);
1621                                 DisplayCaret ();
1622                         }
1623
1624                         if (CaretMoved != null) CaretMoved(this, EventArgs.Empty);
1625                 }
1626
1627                 internal void UpdateCaret() {
1628                         if (!owner.IsHandleCreated || caret.tag == null) {
1629                                 return;
1630                         }
1631
1632                         MoveCaretToTextTag ();
1633
1634                         if (caret.tag.height != caret.height) {
1635                                 caret.height = caret.tag.height;
1636                                 if (owner.Focused) {
1637                                         XplatUI.CreateCaret(owner.Handle, caret_width, caret.height);
1638                                 }
1639                         }
1640
1641                         if (owner.Focused) {
1642                                 XplatUI.SetCaretPos(owner.Handle, (int)caret.tag.line.widths[caret.pos] + caret.line.X - viewport_x, caret.line.Y + caret.tag.shift - viewport_y + caret_shift);
1643                                 DisplayCaret ();
1644                         }
1645                         
1646                         if (CaretMoved != null) CaretMoved(this, EventArgs.Empty);
1647                 }
1648
1649                 internal void DisplayCaret() {
1650                         if (!owner.IsHandleCreated) {
1651                                 return;
1652                         }
1653
1654                         if (owner.ShowSelection && (!selection_visible || owner.show_caret_w_selection)) {
1655                                 XplatUI.CaretVisible(owner.Handle, true);
1656                         }
1657                 }
1658
1659                 internal void HideCaret() {
1660                         if (!owner.IsHandleCreated) {
1661                                 return;
1662                         }
1663
1664                         if (owner.Focused) {
1665                                 XplatUI.CaretVisible(owner.Handle, false);
1666                         }
1667                 }
1668
1669                 
1670                 internal void MoveCaretToTextTag ()
1671                 {
1672                         if (caret.tag == null || caret.tag.IsTextTag)
1673                                 return;
1674
1675                         
1676
1677                         if (caret.pos < caret.tag.start) {
1678                                 caret.tag = caret.tag.previous;
1679                         } else {
1680                                 caret.tag = caret.tag.next;
1681                         }
1682                 }
1683
1684                 internal void MoveCaret(CaretDirection direction) {
1685                         // FIXME should we use IsWordSeparator to detect whitespace, instead 
1686                         // of looking for actual spaces in the Word move cases?
1687
1688                         bool nowrap = false;
1689                         switch(direction) {
1690                                 case CaretDirection.CharForwardNoWrap:
1691                                         nowrap = true;
1692                                         goto case CaretDirection.CharForward;
1693                                 case CaretDirection.CharForward: {
1694                                         caret.pos++;
1695                                         if (caret.pos > caret.line.TextLengthWithoutEnding ()) {
1696                                                 if (!nowrap) {
1697                                                         // Go into next line
1698                                                         if (caret.line.line_no < this.lines) {
1699                                                                 caret.line = GetLine(caret.line.line_no+1);
1700                                                                 caret.pos = 0;
1701                                                                 caret.tag = caret.line.tags;
1702                                                         } else {
1703                                                                 caret.pos--;
1704                                                         }
1705                                                 } else {
1706                                                         // Single line; we stay where we are
1707                                                         caret.pos--;
1708                                                 }
1709                                         } else {
1710                                                 if ((caret.tag.start - 1 + caret.tag.length) < caret.pos) {
1711                                                         caret.tag = caret.tag.next;
1712                                                 }
1713                                         }
1714                                         UpdateCaret();
1715                                         return;
1716                                 }
1717
1718                                 case CaretDirection.CharBackNoWrap:
1719                                         nowrap = true;
1720                                         goto case CaretDirection.CharBack;
1721                                 case CaretDirection.CharBack: {
1722                                         if (caret.pos > 0) {
1723                                                 // caret.pos--; // folded into the if below
1724                                                 
1725                                                 if (--caret.pos > 0) {
1726                                                         if (caret.tag.start > caret.pos) {
1727                                                                 caret.tag = caret.tag.previous;
1728                                                         }
1729                                                 }
1730                                         } else {
1731                                                 if (caret.line.line_no > 1 && !nowrap) {
1732                                                         caret.line = GetLine(caret.line.line_no - 1);
1733                                                         caret.pos = caret.line.TextLengthWithoutEnding ();
1734                                                         caret.tag = LineTag.FindTag(caret.line, caret.pos);
1735                                                 }
1736                                         }
1737                                         UpdateCaret();
1738                                         return;
1739                                 }
1740
1741                                 case CaretDirection.WordForward: {
1742                                         int len;
1743
1744                                         len = caret.line.text.Length;
1745                                         if (caret.pos < len) {
1746                                                 while ((caret.pos < len) && (caret.line.text[caret.pos] != ' ')) {
1747                                                         caret.pos++;
1748                                                 }
1749                                                 if (caret.pos < len) {
1750                                                         // Skip any whitespace
1751                                                         while ((caret.pos < len) && (caret.line.text[caret.pos] == ' ')) {
1752                                                                 caret.pos++;
1753                                                         }
1754                                                 }
1755                                                 caret.tag = LineTag.FindTag(caret.line, caret.pos);
1756                                         } else {
1757                                                 if (caret.line.line_no < this.lines) {
1758                                                         caret.line = GetLine(caret.line.line_no + 1);
1759                                                         caret.pos = 0;
1760                                                         caret.tag = caret.line.tags;
1761                                                 }
1762                                         }
1763                                         UpdateCaret();
1764                                         return;
1765                                 }
1766
1767                                 case CaretDirection.WordBack: {
1768                                         if (caret.pos > 0) {
1769                                                 caret.pos--;
1770
1771                                                 while ((caret.pos > 0) && (caret.line.text[caret.pos] == ' ')) {
1772                                                         caret.pos--;
1773                                                 }
1774
1775                                                 while ((caret.pos > 0) && (caret.line.text[caret.pos] != ' ')) {
1776                                                         caret.pos--;
1777                                                 }
1778
1779                                                 if (caret.line.text.ToString(caret.pos, 1) == " ") {
1780                                                         if (caret.pos != 0) {
1781                                                                 caret.pos++;
1782                                                         } else {
1783                                                                 caret.line = GetLine(caret.line.line_no - 1);
1784                                                                 caret.pos = caret.line.text.Length;
1785                                                         }
1786                                                 }
1787                                                 caret.tag = LineTag.FindTag(caret.line, caret.pos);
1788                                         } else {
1789                                                 if (caret.line.line_no > 1) {
1790                                                         caret.line = GetLine(caret.line.line_no - 1);
1791                                                         caret.pos = caret.line.text.Length;
1792                                                         caret.tag = LineTag.FindTag(caret.line, caret.pos);
1793                                                 }
1794                                         }
1795                                         UpdateCaret();
1796                                         return;
1797                                 }
1798
1799                                 case CaretDirection.LineUp: {
1800                                         if (caret.line.line_no > 1) {
1801                                                 int     pixel;
1802
1803                                                 pixel = (int)caret.line.widths[caret.pos];
1804                                                 PositionCaret(pixel, GetLine(caret.line.line_no - 1).Y);
1805
1806                                                 DisplayCaret ();
1807                                         }
1808                                         return;
1809                                 }
1810
1811                                 case CaretDirection.LineDown: {
1812                                         if (caret.line.line_no < lines) {
1813                                                 int     pixel;
1814
1815                                                 pixel = (int)caret.line.widths[caret.pos];
1816                                                 PositionCaret(pixel, GetLine(caret.line.line_no + 1).Y);
1817
1818                                                 DisplayCaret ();
1819                                         }
1820                                         return;
1821                                 }
1822
1823                                 case CaretDirection.Home: {
1824                                         if (caret.pos > 0) {
1825                                                 caret.pos = 0;
1826                                                 caret.tag = caret.line.tags;
1827                                                 UpdateCaret();
1828                                         }
1829                                         return;
1830                                 }
1831
1832                                 case CaretDirection.End: {
1833                                         if (caret.pos < caret.line.TextLengthWithoutEnding ()) {
1834                                                 caret.pos = caret.line.TextLengthWithoutEnding ();
1835                                                 caret.tag = LineTag.FindTag(caret.line, caret.pos);
1836                                                 UpdateCaret();
1837                                         }
1838                                         return;
1839                                 }
1840
1841                                 case CaretDirection.PgUp: {
1842
1843                                         if (viewport_y == 0 && owner.richtext) {
1844                                                 owner.vscroll.Value = 0;
1845                                                 Line line = GetLine (1);
1846                                                 PositionCaret (line, 0);
1847                                         }
1848
1849                                         int y_offset = caret.line.Y + caret.line.height - 1 - viewport_y;
1850                                         int index;
1851                                         LineTag top = FindCursor ((int) caret.line.widths [caret.pos],
1852                                                         viewport_y - viewport_height, out index);
1853
1854                                         owner.vscroll.Value = Math.Min (top.line.Y, owner.vscroll.Maximum - viewport_height);
1855                                         PositionCaret ((int) caret.line.widths [caret.pos], y_offset + viewport_y);
1856
1857                                         return;
1858                                 }
1859
1860                                 case CaretDirection.PgDn: {
1861
1862                                         if (viewport_y + viewport_height >= document_y && owner.richtext) {
1863                                                 owner.vscroll.Value = owner.vscroll.Maximum - viewport_height + 1;
1864                                                 Line line = GetLine (lines);
1865                                                 PositionCaret (line, line.Text.Length);
1866                                         }
1867
1868                                         int y_offset = caret.line.Y - viewport_y;
1869                                         int index;
1870                                         LineTag top = FindCursor ((int) caret.line.widths [caret.pos],
1871                                                         viewport_y + viewport_height, out index);
1872
1873                                         owner.vscroll.Value = Math.Min (top.line.Y, owner.vscroll.Maximum - viewport_height);
1874                                         PositionCaret ((int) caret.line.widths [caret.pos], y_offset + viewport_y);
1875                                         
1876                                         return;
1877                                 }
1878
1879                                 case CaretDirection.CtrlPgUp: {
1880                                         PositionCaret(0, viewport_y);
1881                                         DisplayCaret ();
1882                                         return;
1883                                 }
1884
1885                                 case CaretDirection.CtrlPgDn: {
1886                                         Line    line;
1887                                         LineTag tag;
1888                                         int     index;
1889
1890                                         tag = FindTag(0, viewport_y + viewport_height, out index, false);
1891                                         if (tag.line.line_no > 1) {
1892                                                 line = GetLine(tag.line.line_no - 1);
1893                                         } else {
1894                                                 line = tag.line;
1895                                         }
1896                                         PositionCaret(line, line.Text.Length);
1897                                         DisplayCaret ();
1898                                         return;
1899                                 }
1900
1901                                 case CaretDirection.CtrlHome: {
1902                                         caret.line = GetLine(1);
1903                                         caret.pos = 0;
1904                                         caret.tag = caret.line.tags;
1905
1906                                         UpdateCaret();
1907                                         return;
1908                                 }
1909
1910                                 case CaretDirection.CtrlEnd: {
1911                                         caret.line = GetLine(lines);
1912                                         caret.pos = caret.line.TextLengthWithoutEnding ();
1913                                         caret.tag = LineTag.FindTag(caret.line, caret.pos);
1914
1915                                         UpdateCaret();
1916                                         return;
1917                                 }
1918
1919                                 case CaretDirection.SelectionStart: {
1920                                         caret.line = selection_start.line;
1921                                         caret.pos = selection_start.pos;
1922                                         caret.tag = selection_start.tag;
1923
1924                                         UpdateCaret();
1925                                         return;
1926                                 }
1927
1928                                 case CaretDirection.SelectionEnd: {
1929                                         caret.line = selection_end.line;
1930                                         caret.pos = selection_end.pos;
1931                                         caret.tag = selection_end.tag;
1932
1933                                         UpdateCaret();
1934                                         return;
1935                                 }
1936                         }
1937                 }
1938
1939                 internal void DumpDoc ()
1940                 {
1941                         Console.WriteLine ("<doc lines='{0}'>", lines);
1942                         for (int i = 1; i <= lines ; i++) {
1943                                 Line line = GetLine (i);
1944                                 Console.WriteLine ("<line no='{0}' ending='{1}'>", line.line_no, line.ending);
1945
1946                                 LineTag tag = line.tags;
1947                                 while (tag != null) {
1948                                         Console.Write ("\t<tag type='{0}' span='{1}->{2}' font='{3}' color='{4}'>",
1949                                                         tag.GetType (), tag.start, tag.length, tag.font, tag.color.Color);
1950                                         Console.Write (tag.Text ());
1951                                         Console.WriteLine ("</tag>");
1952                                         tag = tag.next;
1953                                 }
1954                                 Console.WriteLine ("</line>");
1955                         }
1956                         Console.WriteLine ("</doc>");
1957                 }
1958
1959                 internal void Draw (Graphics g, Rectangle clip)
1960                 {
1961                         Line line;              // Current line being drawn
1962                         LineTag tag;            // Current tag being drawn
1963                         int start;              // First line to draw
1964                         int end;                // Last line to draw
1965                         StringBuilder text;     // String representing the current line
1966                         int line_no;
1967                         Brush tag_brush;
1968                         Brush current_brush;
1969                         Brush disabled_brush;
1970                         Brush readonly_brush;
1971                         Brush hilight;
1972                         Brush hilight_text;
1973
1974                         // First, figure out from what line to what line we need to draw
1975
1976                         if (multiline) {
1977                                 start = GetLineByPixel(clip.Top + viewport_y, false).line_no;
1978                                 end = GetLineByPixel(clip.Bottom + viewport_y, false).line_no;
1979                         } else {
1980                                 start = GetLineByPixel(clip.Left + viewport_x, false).line_no;
1981                                 end = GetLineByPixel(clip.Right + viewport_x, false).line_no;
1982                         }
1983
1984                         ///
1985                         /// We draw the single border ourself
1986                         ///
1987                         if (owner.actual_border_style == BorderStyle.FixedSingle) {
1988                                 ControlPaint.DrawBorder (g, owner.ClientRectangle, Color.Black, ButtonBorderStyle.Solid);
1989                         }
1990
1991                         /// Make sure that we aren't drawing one more line then we need to
1992                         line = GetLine (end - 1);
1993                         if (line != null && clip.Bottom == line.Y + line.height + viewport_y)
1994                                 end--;                  
1995
1996                         line_no = start;
1997
1998                         #if Debug
1999                                 DateTime        n = DateTime.Now;
2000                                 Console.WriteLine ("Started drawing: {0}s {1}ms", n.Second, n.Millisecond);
2001                                 Console.WriteLine ("CLIP:  {0}", clip);
2002                                 Console.WriteLine ("S: {0}", GetLine (start).text);
2003                                 Console.WriteLine ("E: {0}", GetLine (end).text);
2004                         #endif
2005
2006                         disabled_brush = ThemeEngine.Current.ResPool.GetSolidBrush(ThemeEngine.Current.ColorGrayText);
2007                         readonly_brush = ThemeEngine.Current.ResPool.GetSolidBrush (ThemeEngine.Current.ColorControlText);
2008                         hilight = ThemeEngine.Current.ResPool.GetSolidBrush(ThemeEngine.Current.ColorHighlight);
2009                         hilight_text = ThemeEngine.Current.ResPool.GetSolidBrush(ThemeEngine.Current.ColorHighlightText);
2010
2011                         // Non multiline selection can be handled outside of the loop
2012                         if (!multiline && selection_visible && owner.ShowSelection) {
2013                                 g.FillRectangle (hilight,
2014                                                 selection_start.line.widths [selection_start.pos] +
2015                                                 selection_start.line.X - viewport_x, 
2016                                                 selection_start.line.Y,
2017                                                 (selection_end.line.X + selection_end.line.widths [selection_end.pos]) -
2018                                                 (selection_start.line.X + selection_start.line.widths [selection_start.pos]), 
2019                                                 selection_start.line.height);
2020                         }
2021
2022                         while (line_no <= end) {
2023                                 line = GetLine (line_no);
2024                                 float line_y = line.Y - viewport_y;
2025                                 
2026                                 tag = line.tags;
2027                                 if (!calc_pass) {
2028                                         text = line.text;
2029                                 } else {
2030                                         if (PasswordCache.Length < line.text.Length)
2031                                                 PasswordCache.Append(Char.Parse(password_char), line.text.Length - PasswordCache.Length);
2032                                         else if (PasswordCache.Length > line.text.Length)
2033                                                 PasswordCache.Remove(line.text.Length, PasswordCache.Length - line.text.Length);
2034                                         text = PasswordCache;
2035                                 }
2036
2037                                 int line_selection_start = text.Length + 1;
2038                                 int line_selection_end = text.Length + 1;
2039                                 if (selection_visible && owner.ShowSelection &&
2040                                                 (line_no >= selection_start.line.line_no) &&
2041                                                 (line_no <= selection_end.line.line_no)) {
2042
2043                                         if (line_no == selection_start.line.line_no)
2044                                                 line_selection_start = selection_start.pos + 1;
2045                                         else
2046                                                 line_selection_start = 1;
2047
2048                                         if (line_no == selection_end.line.line_no)
2049                                                 line_selection_end = selection_end.pos + 1;
2050                                         else
2051                                                 line_selection_end = text.Length + 1;
2052
2053                                         if (line_selection_end == line_selection_start) {
2054                                                 // There isn't really selection
2055                                                 line_selection_start = text.Length + 1;
2056                                                 line_selection_end = line_selection_start;
2057                                         } else if (multiline) {
2058                                                 // lets draw some selection baby!!  (non multiline selection is drawn outside the loop)
2059                                                 g.FillRectangle (hilight,
2060                                                                 line.widths [line_selection_start - 1] + line.X - viewport_x, 
2061                                                                 line_y, line.widths [line_selection_end - 1] - line.widths [line_selection_start - 1], 
2062                                                                 line.height);
2063                                         }
2064                                 }
2065
2066                                 current_brush = line.tags.color;
2067                                 while (tag != null) {
2068
2069                                         // Skip empty tags
2070                                         if (tag.length == 0) {
2071                                                 tag = tag.next;
2072                                                 continue;
2073                                         }
2074
2075                                         if (((tag.X + tag.width) < (clip.Left - viewport_x)) && (tag.X > (clip.Right - viewport_x))) {
2076                                                 tag = tag.next;
2077                                                 continue;
2078                                         }
2079
2080                                         if (tag.back_color != null) {
2081                                                 g.FillRectangle (tag.back_color, tag.X + line.X - viewport_x,
2082                                                                 line_y + tag.shift, tag.width, line.height);
2083                                         }
2084
2085                                         tag_brush = tag.color;
2086                                         current_brush = tag_brush;
2087
2088                                         if (!owner.Enabled) {
2089                                                 Color a = ((SolidBrush) tag.color).Color;
2090                                                 Color b = ThemeEngine.Current.ColorWindowText;
2091
2092                                                 if ((a.R == b.R) && (a.G == b.G) && (a.B == b.B)) {
2093                                                         tag_brush = disabled_brush;
2094                                                 }
2095                                         } else if (owner.read_only && !owner.backcolor_set) {
2096                                                 tag_brush = readonly_brush;
2097                                         }
2098
2099                                         int tag_pos = tag.start;
2100                                         current_brush = tag_brush;
2101                                         while (tag_pos < tag.start + tag.length) {
2102                                                 int old_tag_pos = tag_pos;
2103
2104                                                 if (tag_pos >= line_selection_start && tag_pos < line_selection_end) {
2105                                                         current_brush = hilight_text;
2106                                                         tag_pos = Math.Min (tag.end, line_selection_end);
2107                                                 } else if (tag_pos < line_selection_start) {
2108                                                         current_brush = tag_brush;
2109                                                         tag_pos = Math.Min (tag.end, line_selection_start);
2110                                                 } else {
2111                                                         current_brush = tag_brush;
2112                                                         tag_pos = tag.end;
2113                                                 }
2114
2115                                                 tag.Draw (g, current_brush,
2116                                                                 line.X - viewport_x,
2117                                                                 line_y + tag.shift,
2118                                                                 old_tag_pos - 1, Math.Max (tag.length, tag_pos - old_tag_pos),
2119                                                                 text.ToString() );
2120                                         }
2121                                         tag = tag.next;
2122                                 }
2123
2124                                 line.DrawEnding (g, line_y);
2125                                 line_no++;
2126                         }
2127                 }
2128
2129                 internal int GetLineEnding (string line, int start, out LineEnding ending)
2130                 {
2131                         int res;
2132
2133                         res = line.IndexOf ('\r', start);
2134                         if (res != -1) {
2135                                 if (res + 2 < line.Length && line [res + 1] == '\r' && line [res + 2] == '\n') {
2136                                         ending = LineEnding.Soft;
2137                                         return res;
2138                                 }
2139                                 if (res + 1 < line.Length && line [res + 1] == '\n') {
2140                                         ending = LineEnding.Hard;
2141                                         return res;
2142                                 }
2143                                 ending = LineEnding.Limp;
2144                                 return res;
2145                         }
2146
2147                         res = line.IndexOf ('\n', start);
2148                         if (res != -1) {
2149                                 ending = LineEnding.Rich;
2150                                 return res;
2151                         }
2152
2153                         ending = LineEnding.Wrap;
2154                         return line.Length;
2155                 }
2156
2157                 internal int LineEndingLength (LineEnding ending)
2158                 {
2159                         int res = 0;
2160
2161                         switch (ending) {
2162                         case LineEnding.Limp:
2163                         case LineEnding.Rich:
2164                                 res = 1;
2165                                 break;
2166                         case LineEnding.Hard:
2167                                 res = 2;
2168                                 break;
2169                         case LineEnding.Soft:
2170                                 res = 3;
2171                                 break;
2172                         }
2173
2174                         return res;
2175                 }
2176
2177                 internal string LineEndingToString (LineEnding ending)
2178                 {
2179                         string res = String.Empty;
2180                         switch (ending) {
2181                         case LineEnding.Limp:
2182                                 res = "\r";
2183                                 break;
2184                         case LineEnding.Hard:
2185                                 res = "\r\n";
2186                                 break;
2187                         case LineEnding.Soft:
2188                                 res = "\r\r\n";
2189                                 break;
2190                         case LineEnding.Rich:
2191                                 res = "\n";
2192                                 break;
2193                         }
2194                         return res;
2195                 }
2196
2197                 
2198                 // Insert multi-line text at the given position; use formatting at insertion point for inserted text
2199                 internal void Insert(Line line, int pos, bool update_caret, string s) {
2200                         int break_index;
2201                         int base_line;
2202                         int old_line_count;
2203                         int count = 1;
2204                         LineEnding ending;
2205                         LineTag tag = LineTag.FindTag (line, pos);
2206                         
2207                         SuspendRecalc ();
2208                         
2209                         base_line = line.line_no;
2210                         old_line_count = lines;
2211
2212                         break_index = GetLineEnding (s, 0, out ending);
2213
2214                         // Bump the text at insertion point a line down if we're inserting more than one line
2215                         if (break_index != s.Length) {
2216                                 Split (line, pos);
2217                                 line.ending = ending;
2218                                 // Remainder of start line is now in base_line + 1
2219                         }
2220
2221                         InsertString (line, pos, s.Substring (0, break_index + LineEndingLength (ending)));
2222                         
2223                         break_index += LineEndingLength (ending);
2224                         while (break_index < s.Length) {
2225                                 int next_break = GetLineEnding (s, break_index, out ending);
2226                                 string line_text = s.Substring (break_index, next_break - break_index +
2227                                                 LineEndingLength (ending));
2228
2229                                 Add (base_line + count, line_text, line.alignment, tag.font, tag.color, ending);
2230
2231                                 Line last = GetLine (base_line + count);
2232                                 last.ending = ending;
2233
2234                                 count++;
2235                                 break_index = next_break + LineEndingLength (ending);
2236                         }
2237
2238                         ResumeRecalc (true);
2239
2240                         UpdateView(line, lines - old_line_count + 1, pos);
2241
2242                         if (update_caret) {
2243                                 // Move caret to the end of the inserted text
2244                                 Line l = GetLine (line.line_no + lines - old_line_count);
2245                                 PositionCaret(l, l.text.Length);
2246                                 DisplayCaret ();
2247                         }
2248                 }
2249
2250                 // Inserts a character at the given position
2251                 internal void InsertString(Line line, int pos, string s) {
2252                         InsertString(line.FindTag(pos), pos, s);
2253                 }
2254
2255                 // Inserts a string at the given position
2256                 internal void InsertString(LineTag tag, int pos, string s) {
2257                         Line    line;
2258                         int     len;
2259
2260                         len = s.Length;
2261
2262                         CharCount += len;
2263
2264                         line = tag.line;
2265                         line.text.Insert(pos, s);
2266
2267                         tag = tag.next;
2268                         while (tag != null) {
2269                                 tag.start += len;
2270                                 tag = tag.next;
2271                         }
2272                         line.Grow(len);
2273                         line.recalc = true;
2274
2275                         UpdateView(line, pos);
2276                 }
2277
2278                 // Inserts a string at the caret position
2279                 internal void InsertStringAtCaret(string s, bool move_caret) {
2280
2281                         InsertString (caret.tag, caret.pos, s);
2282
2283                         UpdateView(caret.line, caret.pos);
2284                         if (move_caret) {
2285                                 caret.pos += s.Length;
2286                                 UpdateCaret();
2287                         }
2288                 }
2289
2290
2291
2292                 // Inserts a character at the given position
2293                 internal void InsertChar(Line line, int pos, char ch) {
2294                         InsertChar(line.FindTag(pos), pos, ch);
2295                 }
2296
2297                 // Inserts a character at the given position
2298                 internal void InsertChar(LineTag tag, int pos, char ch) {
2299                         Line    line;
2300
2301                         CharCount++;
2302
2303                         line = tag.line;
2304                         line.text.Insert(pos, ch);
2305
2306                         tag = tag.next;
2307                         while (tag != null) {
2308                                 tag.start++;
2309                                 tag = tag.next;
2310                         }
2311                         line.Grow(1);
2312                         line.recalc = true;
2313
2314                         undo.RecordTyping (line, pos, ch);
2315                         UpdateView(line, pos);
2316                 }
2317
2318                 // Inserts a character at the current caret position
2319                 internal void InsertCharAtCaret(char ch, bool move_caret) {
2320                         /*
2321                         LineTag tag;
2322
2323                         CharCount++;
2324
2325                         caret.line.text.Insert(caret.pos, ch);
2326                         caret.tag.length++;
2327                         
2328                         if (caret.tag.next != null) {
2329                                 tag = caret.tag.next;
2330                                 while (tag != null) {
2331                                         tag.start++;
2332                                         tag = tag.next;
2333                                 }
2334                         }
2335                         caret.line.Grow(1);
2336                         caret.line.recalc = true;
2337                         */
2338                         InsertChar (caret.tag, caret.pos, ch);
2339
2340                         UpdateView(caret.line, caret.pos);
2341                         if (move_caret) {
2342                                 caret.pos++;
2343                                 UpdateCaret();
2344                                 SetSelectionToCaret(true);
2345                         }
2346
2347                 }
2348                 
2349                 internal void InsertPicture (Line line, int pos, RTF.Picture picture)
2350                 {
2351                         //LineTag next_tag;
2352                         LineTag tag;
2353                         int len;
2354
2355                         len = 1;
2356
2357                         // Just a place holder basically
2358                         line.text.Insert (pos, "I");
2359
2360                         PictureTag picture_tag = new PictureTag (line, pos + 1, picture);
2361
2362                         tag = LineTag.FindTag (line, pos);
2363                         picture_tag.CopyFormattingFrom (tag);
2364                         /*next_tag = */tag.Break (pos + 1);
2365                         picture_tag.previous = tag;
2366                         picture_tag.next = tag.next;
2367                         tag.next = picture_tag;
2368
2369                         //
2370                         // Picture tags need to be surrounded by text tags
2371                         //
2372                         if (picture_tag.next == null) {
2373                                 picture_tag.next = new LineTag (line, pos + 1);
2374                                 picture_tag.next.CopyFormattingFrom (tag);
2375                                 picture_tag.next.previous = picture_tag;
2376                         }
2377
2378                         tag = picture_tag.next;
2379                         while (tag != null) {
2380                                 tag.start += len;
2381                                 tag = tag.next;
2382                         }
2383
2384                         line.Grow (len);
2385                         line.recalc = true;
2386
2387                         UpdateView (line, pos);
2388                 }
2389
2390                 internal void DeleteMultiline (Line start_line, int pos, int length)
2391                 {
2392                         Marker start = new Marker ();
2393                         Marker end = new Marker ();
2394                         int start_index = LineTagToCharIndex (start_line, pos);
2395
2396                         start.line = start_line;
2397                         start.pos = pos;
2398                         start.tag = LineTag.FindTag (start_line, pos);
2399
2400                         CharIndexToLineTag (start_index + length, out end.line,
2401                                         out end.tag, out end.pos);
2402
2403                         SuspendUpdate ();
2404
2405                         if (start.line == end.line) {
2406                                 DeleteChars (start.tag, pos, end.pos - pos);
2407                         } else {
2408
2409                                 // Delete first and last lines
2410                                 DeleteChars (start.tag, start.pos, start.line.text.Length - start.pos);
2411                                 DeleteChars (end.line.tags, 0, end.pos);
2412
2413                                 int current = start.line.line_no + 1;
2414                                 if (current < end.line.line_no) {
2415                                         for (int i = end.line.line_no - 1; i >= current; i--) {
2416                                                 Delete (i);
2417                                         }
2418                                 }
2419
2420                                 // BIG FAT WARNING - selection_end.line might be stale due 
2421                                 // to the above Delete() call. DONT USE IT before hitting the end of this method!
2422
2423                                 // Join start and end
2424                                 Combine (start.line.line_no, current);
2425                         }
2426
2427                         ResumeUpdate (true);
2428                 }
2429
2430                 
2431                 // Deletes n characters at the given position; it will not delete past line limits
2432                 // pos is 0-based
2433                 internal void DeleteChars(LineTag tag, int pos, int count) {
2434                         Line    line;
2435                         bool    streamline;
2436
2437                         streamline = false;
2438                         line = tag.line;
2439
2440                         CharCount -= count;
2441
2442                         if (pos == line.text.Length) {
2443                                 return;
2444                         }
2445
2446                         line.text.Remove(pos, count);
2447
2448                         // Make sure the tag points to the right spot
2449                         while ((tag != null) && (tag.end) < pos) {
2450                                 tag = tag.next;
2451                         }
2452
2453                         if (tag == null) {
2454                                 goto Cleanup;
2455                         }
2456
2457                         // Check if we're crossing tag boundaries
2458                         if ((pos + count) > (tag.start + tag.length - 1)) {
2459                                 int     left;
2460
2461                                 // We have to delete cross tag boundaries
2462                                 streamline = true;
2463                                 left = count;
2464
2465                                 left -= tag.start + tag.length - pos - 1;
2466
2467                                 tag = tag.next;
2468                                 while ((tag != null) && (left > 0)) {
2469                                         tag.start -= count - left;
2470
2471                                         if (tag.length > left) {
2472                                                 left = 0;
2473                                         } else {
2474                                                 left -= tag.length;
2475                                                 tag = tag.next;
2476                                         }
2477
2478                                 }
2479                         } else {
2480                                 // We got off easy, same tag
2481
2482                                 if (tag.length == 0) {
2483                                         streamline = true;
2484                                 }
2485                         }
2486
2487                         // Delete empty orphaned tags at the end
2488                         LineTag walk = tag;
2489                         while (walk != null && walk.next != null && walk.next.length == 0) {
2490                                 LineTag t = walk;
2491                                 walk.next = walk.next.next;
2492                                 if (walk.next != null)
2493                                         walk.next.previous = t;
2494                                 walk = walk.next;
2495                         }
2496
2497                         // Adjust the start point of any tags following
2498                         if (tag != null) {
2499                                 tag = tag.next;
2500                                 while (tag != null) {
2501                                         tag.start -= count;
2502                                         tag = tag.next;
2503                                 }
2504                         }
2505
2506                         line.recalc = true;
2507                         if (streamline) {
2508                                 line.Streamline(lines);
2509                         }
2510
2511                 Cleanup:
2512                         if (pos >= line.TextLengthWithoutEnding ()) {
2513                                 LineEnding ending = line.ending;
2514                                 GetLineEnding (line.text.ToString (), 0, out ending);
2515                                 if (ending != line.ending) {
2516                                         line.ending = ending;
2517
2518                                         if (!multiline) {
2519                                                 UpdateView (line, lines, pos);
2520                                                 owner.Invalidate ();
2521                                                 return;
2522                                         }
2523                                 }
2524                         }
2525                         if (!multiline) {
2526                                 UpdateView (line, lines, pos);
2527                                 owner.Invalidate ();
2528                         } else 
2529                                 UpdateView(line, pos);
2530                 }
2531
2532                 // Deletes a character at or after the given position (depending on forward); it will not delete past line limits
2533                 internal void DeleteChar(LineTag tag, int pos, bool forward) {
2534                         Line    line;
2535                         bool    streamline;
2536
2537                         CharCount--;
2538
2539                         streamline = false;
2540                         line = tag.line;
2541
2542                         if ((pos == 0 && forward == false) || (pos == line.text.Length && forward == true)) {
2543                                 return;
2544                         }
2545
2546
2547                         if (forward) {
2548                                 line.text.Remove(pos, 1);
2549
2550                                 while ((tag != null) && (tag.start + tag.length - 1) <= pos) {
2551                                         tag = tag.next;
2552                                 }
2553
2554                                 if (tag == null) {
2555                                         goto Cleanup;
2556                                 }
2557
2558                                 //      tag.length--;
2559
2560                                 if (tag.length == 0) {
2561                                         streamline = true;
2562                                 }
2563                         } else {
2564                                 pos--;
2565                                 line.text.Remove(pos, 1);
2566                                 if (pos >= (tag.start - 1)) {
2567                                         //              tag.length--;
2568                                         if (tag.length == 0) {
2569                                                 streamline = true;
2570                                         }
2571                                 } else if (tag.previous != null) {
2572                                         //              tag.previous.length--;
2573                                         if (tag.previous.length == 0) {
2574                                                 streamline = true;
2575                                         }
2576                                 }
2577                         }
2578
2579                         // Delete empty orphaned tags at the end
2580                         LineTag walk = tag;
2581                         while (walk != null && walk.next != null && walk.next.length == 0) {
2582                                 LineTag t = walk;
2583                                 walk.next = walk.next.next;
2584                                 if (walk.next != null)
2585                                         walk.next.previous = t;
2586                                 walk = walk.next;
2587                         }
2588
2589                         tag = tag.next;
2590                         while (tag != null) {
2591                                 tag.start--;
2592                                 tag = tag.next;
2593                         }
2594                         line.recalc = true;
2595                         if (streamline) {
2596                                 line.Streamline(lines);
2597                         }
2598
2599                 Cleanup:
2600                         if (pos >= line.TextLengthWithoutEnding ()) {
2601                                 LineEnding ending = line.ending;
2602                                 GetLineEnding (line.text.ToString (), 0, out ending);
2603                                 if (ending != line.ending) {
2604                                         line.ending = ending;
2605
2606                                         if (!multiline) {
2607                                                 UpdateView (line, lines, pos);
2608                                                 owner.Invalidate ();
2609                                                 return;
2610                                         }
2611                                 }
2612                         }
2613                         if (!multiline) {
2614                                 UpdateView (line, lines, pos);
2615                                 owner.Invalidate ();
2616                         } else 
2617                                 UpdateView(line, pos);
2618                 }
2619
2620                 // Combine two lines
2621                 internal void Combine(int FirstLine, int SecondLine) {
2622                         Combine(GetLine(FirstLine), GetLine(SecondLine));
2623                 }
2624
2625                 internal void Combine(Line first, Line second) {
2626                         LineTag last;
2627                         int     shift;
2628
2629                         // strip the ending off of the first lines text
2630                         first.text.Length = first.text.Length - LineEndingLength (first.ending);
2631
2632                         // Combine the two tag chains into one
2633                         last = first.tags;
2634
2635                         // Maintain the line ending style
2636                         first.ending = second.ending;
2637
2638                         while (last.next != null) {
2639                                 last = last.next;
2640                         }
2641
2642                         // need to get the shift before setting the next tag since that effects length
2643                         shift = last.start + last.length - 1;
2644                         last.next = second.tags;
2645                         last.next.previous = last;
2646
2647                         // Fix up references within the chain
2648                         last = last.next;
2649                         while (last != null) {
2650                                 last.line = first;
2651                                 last.start += shift;
2652                                 last = last.next;
2653                         }
2654
2655                         // Combine both lines' strings
2656                         first.text.Insert(first.text.Length, second.text.ToString());
2657                         first.Grow(first.text.Length);
2658
2659                         // Remove the reference to our (now combined) tags from the doomed line
2660                         second.tags = null;
2661
2662                         // Renumber lines
2663                         DecrementLines(first.line_no + 2);      // first.line_no + 1 will be deleted, so we need to start renumbering one later
2664
2665                         // Mop up
2666                         first.recalc = true;
2667                         first.height = 0;       // This forces RecalcDocument/UpdateView to redraw from this line on
2668                         first.Streamline(lines);
2669
2670                         // Update Caret, Selection, etc
2671                         if (caret.line == second) {
2672                                 caret.Combine(first, shift);
2673                         }
2674                         if (selection_anchor.line == second) {
2675                                 selection_anchor.Combine(first, shift);
2676                         }
2677                         if (selection_start.line == second) {
2678                                 selection_start.Combine(first, shift);
2679                         }
2680                         if (selection_end.line == second) {
2681                                 selection_end.Combine(first, shift);
2682                         }
2683
2684                         #if Debug
2685                                 Line    check_first;
2686                                 Line    check_second;
2687
2688                                 check_first = GetLine(first.line_no);
2689                                 check_second = GetLine(check_first.line_no + 1);
2690
2691                                 Console.WriteLine("Pre-delete: Y of first line: {0}, second line: {1}", check_first.Y, check_second.Y);
2692                         #endif
2693
2694                         this.Delete(second);
2695
2696                         #if Debug
2697                                 check_first = GetLine(first.line_no);
2698                                 check_second = GetLine(check_first.line_no + 1);
2699
2700                                 Console.WriteLine("Post-delete Y of first line: {0}, second line: {1}", check_first.Y, check_second.Y);
2701                         #endif
2702                 }
2703
2704                 // Split the line at the position into two
2705                 internal void Split(int LineNo, int pos) {
2706                         Line    line;
2707                         LineTag tag;
2708
2709                         line = GetLine(LineNo);
2710                         tag = LineTag.FindTag(line, pos);
2711                         Split(line, tag, pos);
2712                 }
2713
2714                 internal void Split(Line line, int pos) {
2715                         LineTag tag;
2716
2717                         tag = LineTag.FindTag(line, pos);
2718                         Split(line, tag, pos);
2719                 }
2720
2721                 ///<summary>Split line at given tag and position into two lines</summary>
2722                 ///if more space becomes available on previous line</param>
2723                 internal void Split(Line line, LineTag tag, int pos) {
2724                         LineTag new_tag;
2725                         Line    new_line;
2726                         bool    move_caret;
2727                         bool    move_sel_start;
2728                         bool    move_sel_end;
2729
2730                         move_caret = false;
2731                         move_sel_start = false;
2732                         move_sel_end = false;
2733
2734                         // Adjust selection and cursors
2735                         if (caret.line == line && caret.pos >= pos) {
2736                                 move_caret = true;
2737                         }
2738                         if (selection_start.line == line && selection_start.pos > pos) {
2739                                 move_sel_start = true;
2740                         }
2741
2742                         if (selection_end.line == line && selection_end.pos > pos) {
2743                                 move_sel_end = true;
2744                         }
2745
2746                         // cover the easy case first
2747                         if (pos == line.text.Length) {
2748                                 Add (line.line_no + 1, String.Empty, line.alignment, tag.font, tag.color, line.ending);
2749
2750                                 new_line = GetLine (line.line_no + 1);
2751                                 
2752                                 if (move_caret) {
2753                                         caret.line = new_line;
2754                                         caret.tag = new_line.tags;
2755                                         caret.pos = 0;
2756                                 }
2757
2758                                 if (move_sel_start) {
2759                                         selection_start.line = new_line;
2760                                         selection_start.pos = 0;
2761                                         selection_start.tag = new_line.tags;
2762                                 }
2763
2764                                 if (move_sel_end) {
2765                                         selection_end.line = new_line;
2766                                         selection_end.pos = 0;
2767                                         selection_end.tag = new_line.tags;
2768                                 }
2769                                 return;
2770                         }
2771
2772                         // We need to move the rest of the text into the new line
2773                         Add (line.line_no + 1, line.text.ToString (pos, line.text.Length - pos), line.alignment, tag.font, tag.color, line.ending);
2774
2775                         // Now transfer our tags from this line to the next
2776                         new_line = GetLine(line.line_no + 1);
2777
2778                         line.recalc = true;
2779                         new_line.recalc = true;
2780
2781                         if ((tag.start - 1) == pos) {
2782                                 int     shift;
2783
2784                                 // We can simply break the chain and move the tag into the next line
2785                                 if (tag == line.tags) {
2786                                         new_tag = new LineTag(line, 1);
2787                                         new_tag.CopyFormattingFrom (tag);
2788                                         line.tags = new_tag;
2789                                 }
2790
2791                                 if (tag.previous != null) {
2792                                         tag.previous.next = null;
2793                                 }
2794                                 new_line.tags = tag;
2795                                 tag.previous = null;
2796                                 tag.line = new_line;
2797
2798                                 // Walk the list and correct the start location of the tags we just bumped into the next line
2799                                 shift = tag.start - 1;
2800
2801                                 new_tag = tag;
2802                                 while (new_tag != null) {
2803                                         new_tag.start -= shift;
2804                                         new_tag.line = new_line;
2805                                         new_tag = new_tag.next;
2806                                 }
2807                         } else {
2808                                 int     shift;
2809
2810                                 new_tag = new LineTag (new_line, 1);                    
2811                                 new_tag.next = tag.next;
2812                                 new_tag.CopyFormattingFrom (tag);
2813                                 new_line.tags = new_tag;
2814                                 if (new_tag.next != null) {
2815                                         new_tag.next.previous = new_tag;
2816                                 }
2817                                 tag.next = null;
2818
2819                                 shift = pos;
2820                                 new_tag = new_tag.next;
2821                                 while (new_tag != null) {
2822                                         new_tag.start -= shift;
2823                                         new_tag.line = new_line;
2824                                         new_tag = new_tag.next;
2825
2826                                 }
2827                         }
2828
2829                         if (move_caret) {
2830                                 caret.line = new_line;
2831                                 caret.pos = caret.pos - pos;
2832                                 caret.tag = caret.line.FindTag(caret.pos);
2833                         }
2834
2835                         if (move_sel_start) {
2836                                 selection_start.line = new_line;
2837                                 selection_start.pos = selection_start.pos - pos;
2838                                 selection_start.tag = new_line.FindTag(selection_start.pos);
2839                         }
2840
2841                         if (move_sel_end) {
2842                                 selection_end.line = new_line;
2843                                 selection_end.pos = selection_end.pos - pos;
2844                                 selection_end.tag = new_line.FindTag(selection_end.pos);
2845                         }
2846
2847                         CharCount -= line.text.Length - pos;
2848                         line.text.Remove(pos, line.text.Length - pos);
2849                 }
2850
2851                 // Adds a line of text, with given font.
2852                 // Bumps any line at that line number that already exists down
2853                 internal void Add (int LineNo, string Text, Font font, SolidBrush color, LineEnding ending)
2854                 {
2855                         Add (LineNo, Text, alignment, font, color, ending);
2856                 }
2857
2858                 internal void Add (int LineNo, string Text, HorizontalAlignment align, Font font, SolidBrush color, LineEnding ending)
2859                 {
2860                         Line    add;
2861                         Line    line;
2862                         int     line_no;
2863
2864                         CharCount += Text.Length;
2865
2866                         if (LineNo<1 || Text == null) {
2867                                 if (LineNo<1) {
2868                                         throw new ArgumentNullException("LineNo", "Line numbers must be positive");
2869                                 } else {
2870                                         throw new ArgumentNullException("Text", "Cannot insert NULL line");
2871                                 }
2872                         }
2873
2874                         add = new Line (this, LineNo, Text, align, font, color, ending);
2875
2876                         line = document;
2877                         while (line != sentinel) {
2878                                 add.parent = line;
2879                                 line_no = line.line_no;
2880
2881                                 if (LineNo > line_no) {
2882                                         line = line.right;
2883                                 } else if (LineNo < line_no) {
2884                                         line = line.left;
2885                                 } else {
2886                                         // Bump existing line numbers; walk all nodes to the right of this one and increment line_no
2887                                         IncrementLines(line.line_no);
2888                                         line = line.left;
2889                                 }
2890                         }
2891
2892                         add.left = sentinel;
2893                         add.right = sentinel;
2894
2895                         if (add.parent != null) {
2896                                 if (LineNo > add.parent.line_no) {
2897                                         add.parent.right = add;
2898                                 } else {
2899                                         add.parent.left = add;
2900                                 }
2901                         } else {
2902                                 // Root node
2903                                 document = add;
2904                         }
2905
2906                         RebalanceAfterAdd(add);
2907
2908                         lines++;
2909                 }
2910
2911                 internal virtual void Clear() {
2912                         lines = 0;
2913                         CharCount = 0;
2914                         document = sentinel;
2915                 }
2916
2917                 public virtual object Clone() {
2918                         Document clone;
2919
2920                         clone = new Document(null);
2921
2922                         clone.lines = this.lines;
2923                         clone.document = (Line)document.Clone();
2924
2925                         return clone;
2926                 }
2927
2928                 internal void Delete(int LineNo) {
2929                         Line    line;
2930
2931                         if (LineNo>lines) {
2932                                 return;
2933                         }
2934
2935                         line = GetLine(LineNo);
2936
2937                         CharCount -= line.text.Length;
2938
2939                         DecrementLines(LineNo + 1);
2940                         Delete(line);
2941                 }
2942
2943                 internal void Delete(Line line1) {
2944                         Line    line2;// = new Line();
2945                         Line    line3;
2946
2947                         if ((line1.left == sentinel) || (line1.right == sentinel)) {
2948                                 line3 = line1;
2949                         } else {
2950                                 line3 = line1.right;
2951                                 while (line3.left != sentinel) {
2952                                         line3 = line3.left;
2953                                 }
2954                         }
2955
2956                         if (line3.left != sentinel) {
2957                                 line2 = line3.left;
2958                         } else {
2959                                 line2 = line3.right;
2960                         }
2961
2962                         line2.parent = line3.parent;
2963                         if (line3.parent != null) {
2964                                 if(line3 == line3.parent.left) {
2965                                         line3.parent.left = line2;
2966                                 } else {
2967                                         line3.parent.right = line2;
2968                                 }
2969                         } else {
2970                                 document = line2;
2971                         }
2972
2973                         if (line3 != line1) {
2974                                 LineTag tag;
2975
2976                                 if (selection_start.line == line3) {
2977                                         selection_start.line = line1;
2978                                 }
2979
2980                                 if (selection_end.line == line3) {
2981                                         selection_end.line = line1;
2982                                 }
2983
2984                                 if (selection_anchor.line == line3) {
2985                                         selection_anchor.line = line1;
2986                                 }
2987
2988                                 if (caret.line == line3) {
2989                                         caret.line = line1;
2990                                 }
2991
2992
2993                                 line1.alignment = line3.alignment;
2994                                 line1.ascent = line3.ascent;
2995                                 line1.hanging_indent = line3.hanging_indent;
2996                                 line1.height = line3.height;
2997                                 line1.indent = line3.indent;
2998                                 line1.line_no = line3.line_no;
2999                                 line1.recalc = line3.recalc;
3000                                 line1.right_indent = line3.right_indent;
3001                                 line1.ending = line3.ending;
3002                                 line1.space = line3.space;
3003                                 line1.tags = line3.tags;
3004                                 line1.text = line3.text;
3005                                 line1.widths = line3.widths;
3006                                 line1.offset = line3.offset;
3007
3008                                 tag = line1.tags;
3009                                 while (tag != null) {
3010                                         tag.line = line1;
3011                                         tag = tag.next;
3012                                 }
3013                         }
3014
3015                         if (line3.color == LineColor.Black)
3016                                 RebalanceAfterDelete(line2);
3017
3018                         this.lines--;
3019                 }
3020
3021                 // Invalidate a section of the document to trigger redraw
3022                 internal void Invalidate(Line start, int start_pos, Line end, int end_pos) {
3023                         Line    l1;
3024                         Line    l2;
3025                         int     p1;
3026                         int     p2;
3027
3028                         if ((start == end) && (start_pos == end_pos)) {
3029                                 return;
3030                         }
3031
3032                         if (end_pos == -1) {
3033                                 end_pos = end.text.Length;
3034                         }
3035         
3036                         // figure out what's before what so the logic below is straightforward
3037                         if (start.line_no < end.line_no) {
3038                                 l1 = start;
3039                                 p1 = start_pos;
3040
3041                                 l2 = end;
3042                                 p2 = end_pos;
3043                         } else if (start.line_no > end.line_no) {
3044                                 l1 = end;
3045                                 p1 = end_pos;
3046
3047                                 l2 = start;
3048                                 p2 = start_pos;
3049                         } else {
3050                                 if (start_pos < end_pos) {
3051                                         l1 = start;
3052                                         p1 = start_pos;
3053
3054                                         l2 = end;
3055                                         p2 = end_pos;
3056                                 } else {
3057                                         l1 = end;
3058                                         p1 = end_pos;
3059
3060                                         l2 = start;
3061                                         p2 = start_pos;
3062                                 }
3063
3064                                 int endpoint = (int) l1.widths [p2];
3065                                 if (p2 == l1.text.Length + 1) {
3066                                         endpoint = (int) viewport_width;
3067                                 }
3068
3069                                 #if Debug
3070                                         Console.WriteLine("Invaliding backwards from {0}:{1} to {2}:{3}   {4}",
3071                                                         l1.line_no, p1, l2.line_no, p2,
3072                                                         new Rectangle(
3073                                                                 (int)l1.widths[p1] + l1.X - viewport_x, 
3074                                                                 l1.Y - viewport_y, 
3075                                                                 (int)l1.widths[p2], 
3076                                                                 l1.height
3077                                                                 )
3078                                                 );
3079                                 #endif
3080
3081                                 owner.Invalidate(new Rectangle (
3082                                         (int)l1.widths[p1] + l1.X - viewport_x, 
3083                                         l1.Y - viewport_y, 
3084                                         endpoint - (int)l1.widths[p1] + 1, 
3085                                         l1.height));
3086                                 return;
3087                         }
3088
3089                         #if Debug
3090                                 Console.WriteLine("Invaliding from {0}:{1} to {2}:{3} Start  => x={4}, y={5}, {6}x{7}", l1.line_no, p1, l2.line_no, p2, (int)l1.widths[p1] + l1.X - viewport_x, l1.Y - viewport_y, viewport_width, l1.height);
3091                                 Console.WriteLine ("invalidate start line:  {0}  position:  {1}", l1.text, p1);
3092                         #endif
3093
3094                         // Three invalidates:
3095                         // First line from start
3096                         owner.Invalidate(new Rectangle((int)l1.widths[p1] + l1.X - viewport_x, l1.Y - viewport_y, viewport_width, l1.height));
3097
3098                         
3099                         // lines inbetween
3100                         if ((l1.line_no + 1) < l2.line_no) {
3101                                 int     y;
3102
3103                                 y = GetLine(l1.line_no + 1).Y;
3104                                 owner.Invalidate(new Rectangle(0, y - viewport_y, viewport_width, l2.Y - y));
3105
3106                                 #if Debug
3107                                         Console.WriteLine("Invaliding from {0}:{1} to {2}:{3} Middle => x={4}, y={5}, {6}x{7}", l1.line_no, p1, l2.line_no, p2, 0, y - viewport_y, viewport_width, l2.Y - y);
3108                                 #endif
3109                         }
3110                         
3111
3112                         // Last line to end
3113                         owner.Invalidate(new Rectangle((int)l2.widths[0] + l2.X - viewport_x, l2.Y - viewport_y, (int)l2.widths[p2] + 1, l2.height));
3114                         #if Debug
3115                                 Console.WriteLine("Invaliding from {0}:{1} to {2}:{3} End    => x={4}, y={5}, {6}x{7}", l1.line_no, p1, l2.line_no, p2, (int)l2.widths[0] + l2.X - viewport_x, l2.Y - viewport_y, (int)l2.widths[p2] + 1, l2.height);
3116
3117                         #endif
3118                 }
3119
3120                 /// <summary>Select text around caret</summary>
3121                 internal void ExpandSelection(CaretSelection mode, bool to_caret) {
3122                         if (to_caret) {
3123                                 // We're expanding the selection to the caret position
3124                                 switch(mode) {
3125                                         case CaretSelection.Line: {
3126                                                 // Invalidate the selection delta
3127                                                 if (caret > selection_prev) {
3128                                                         Invalidate(selection_prev.line, 0, caret.line, caret.line.text.Length);
3129                                                 } else {
3130                                                         Invalidate(selection_prev.line, selection_prev.line.text.Length, caret.line, 0);
3131                                                 }
3132
3133                                                 if (caret.line.line_no <= selection_anchor.line.line_no) {
3134                                                         selection_start.line = caret.line;
3135                                                         selection_start.tag = caret.line.tags;
3136                                                         selection_start.pos = 0;
3137
3138                                                         selection_end.line = selection_anchor.line;
3139                                                         selection_end.tag = selection_anchor.tag;
3140                                                         selection_end.pos = selection_anchor.pos;
3141
3142                                                         selection_end_anchor = true;
3143                                                 } else {
3144                                                         selection_start.line = selection_anchor.line;
3145                                                         selection_start.pos = selection_anchor.height;
3146                                                         selection_start.tag = selection_anchor.line.FindTag(selection_anchor.height);
3147
3148                                                         selection_end.line = caret.line;
3149                                                         selection_end.tag = caret.line.tags;
3150                                                         selection_end.pos = caret.line.text.Length;
3151
3152                                                         selection_end_anchor = false;
3153                                                 }
3154                                                 selection_prev.line = caret.line;
3155                                                 selection_prev.tag = caret.tag;
3156                                                 selection_prev.pos = caret.pos;
3157
3158                                                 break;
3159                                         }
3160
3161                                         case CaretSelection.Word: {
3162                                                 int     start_pos;
3163                                                 int     end_pos;
3164
3165                                                 start_pos = FindWordSeparator(caret.line, caret.pos, false);
3166                                                 end_pos = FindWordSeparator(caret.line, caret.pos, true);
3167
3168                                                 
3169                                                 // Invalidate the selection delta
3170                                                 if (caret > selection_prev) {
3171                                                         Invalidate(selection_prev.line, selection_prev.pos, caret.line, end_pos);
3172                                                 } else {
3173                                                         Invalidate(selection_prev.line, selection_prev.pos, caret.line, start_pos);
3174                                                 }
3175                                                 if (caret < selection_anchor) {
3176                                                         selection_start.line = caret.line;
3177                                                         selection_start.tag = caret.line.FindTag(start_pos);
3178                                                         selection_start.pos = start_pos;
3179
3180                                                         selection_end.line = selection_anchor.line;
3181                                                         selection_end.tag = selection_anchor.tag;
3182                                                         selection_end.pos = selection_anchor.pos;
3183
3184                                                         selection_prev.line = caret.line;
3185                                                         selection_prev.tag = caret.tag;
3186                                                         selection_prev.pos = start_pos;
3187
3188                                                         selection_end_anchor = true;
3189                                                 } else {
3190                                                         selection_start.line = selection_anchor.line;
3191                                                         selection_start.pos = selection_anchor.height;
3192                                                         selection_start.tag = selection_anchor.line.FindTag(selection_anchor.height);
3193
3194                                                         selection_end.line = caret.line;
3195                                                         selection_end.tag = caret.line.FindTag(end_pos);
3196                                                         selection_end.pos = end_pos;
3197
3198                                                         selection_prev.line = caret.line;
3199                                                         selection_prev.tag = caret.tag;
3200                                                         selection_prev.pos = end_pos;
3201
3202                                                         selection_end_anchor = false;
3203                                                 }
3204                                                 break;
3205                                         }
3206
3207                                         case CaretSelection.Position: {
3208                                                 SetSelectionToCaret(false);
3209                                                 return;
3210                                         }
3211                                 }
3212                         } else {
3213                                 // We're setting the selection 'around' the caret position
3214                                 switch(mode) {
3215                                         case CaretSelection.Line: {
3216                                                 this.Invalidate(caret.line, 0, caret.line, caret.line.text.Length);
3217
3218                                                 selection_start.line = caret.line;
3219                                                 selection_start.tag = caret.line.tags;
3220                                                 selection_start.pos = 0;
3221
3222                                                 selection_end.line = caret.line;
3223                                                 selection_end.pos = caret.line.text.Length;
3224                                                 selection_end.tag = caret.line.FindTag(selection_end.pos);
3225
3226                                                 selection_anchor.line = selection_end.line;
3227                                                 selection_anchor.tag = selection_end.tag;
3228                                                 selection_anchor.pos = selection_end.pos;
3229                                                 selection_anchor.height = 0;
3230
3231                                                 selection_prev.line = caret.line;
3232                                                 selection_prev.tag = caret.tag;
3233                                                 selection_prev.pos = caret.pos;
3234
3235                                                 this.selection_end_anchor = true;
3236
3237                                                 break;
3238                                         }
3239
3240                                         case CaretSelection.Word: {
3241                                                 int     start_pos;
3242                                                 int     end_pos;
3243
3244                                                 start_pos = FindWordSeparator(caret.line, caret.pos, false);
3245                                                 end_pos = FindWordSeparator(caret.line, caret.pos, true);
3246
3247                                                 this.Invalidate(selection_start.line, start_pos, caret.line, end_pos);
3248
3249                                                 selection_start.line = caret.line;
3250                                                 selection_start.tag = caret.line.FindTag(start_pos);
3251                                                 selection_start.pos = start_pos;
3252
3253                                                 selection_end.line = caret.line;
3254                                                 selection_end.tag = caret.line.FindTag(end_pos);
3255                                                 selection_end.pos = end_pos;
3256
3257                                                 selection_anchor.line = selection_end.line;
3258                                                 selection_anchor.tag = selection_end.tag;
3259                                                 selection_anchor.pos = selection_end.pos;
3260                                                 selection_anchor.height = start_pos;
3261
3262                                                 selection_prev.line = caret.line;
3263                                                 selection_prev.tag = caret.tag;
3264                                                 selection_prev.pos = caret.pos;
3265
3266                                                 this.selection_end_anchor = true;
3267
3268                                                 break;
3269                                         }
3270                                 }
3271                         }
3272
3273                         SetSelectionVisible (!(selection_start == selection_end));
3274                 }
3275
3276                 internal void SetSelectionToCaret(bool start) {
3277                         if (start) {
3278                                 // Invalidate old selection; selection is being reset to empty
3279                                 this.Invalidate(selection_start.line, selection_start.pos, selection_end.line, selection_end.pos);
3280
3281                                 selection_start.line = caret.line;
3282                                 selection_start.tag = caret.tag;
3283                                 selection_start.pos = caret.pos;
3284
3285                                 // start always also selects end
3286                                 selection_end.line = caret.line;
3287                                 selection_end.tag = caret.tag;
3288                                 selection_end.pos = caret.pos;
3289
3290                                 selection_anchor.line = caret.line;
3291                                 selection_anchor.tag = caret.tag;
3292                                 selection_anchor.pos = caret.pos;
3293                         } else {
3294                                 // Invalidate from previous end to caret (aka new end)
3295                                 if (selection_end_anchor) {
3296                                         if (selection_start != caret) {
3297                                                 this.Invalidate(selection_start.line, selection_start.pos, caret.line, caret.pos);
3298                                         }
3299                                 } else {
3300                                         if (selection_end != caret) {
3301                                                 this.Invalidate(selection_end.line, selection_end.pos, caret.line, caret.pos);
3302                                         }
3303                                 }
3304
3305                                 if (caret < selection_anchor) {
3306                                         selection_start.line = caret.line;
3307                                         selection_start.tag = caret.tag;
3308                                         selection_start.pos = caret.pos;
3309
3310                                         selection_end.line = selection_anchor.line;
3311                                         selection_end.tag = selection_anchor.tag;
3312                                         selection_end.pos = selection_anchor.pos;
3313
3314                                         selection_end_anchor = true;
3315                                 } else {
3316                                         selection_start.line = selection_anchor.line;
3317                                         selection_start.tag = selection_anchor.tag;
3318                                         selection_start.pos = selection_anchor.pos;
3319
3320                                         selection_end.line = caret.line;
3321                                         selection_end.tag = caret.tag;
3322                                         selection_end.pos = caret.pos;
3323
3324                                         selection_end_anchor = false;
3325                                 }
3326                         }
3327
3328                         SetSelectionVisible (!(selection_start == selection_end));
3329                 }
3330
3331                 internal void SetSelection(Line start, int start_pos, Line end, int end_pos) {
3332                         if (selection_visible) {
3333                                 Invalidate(selection_start.line, selection_start.pos, selection_end.line, selection_end.pos);
3334                         }
3335
3336                         if ((end.line_no < start.line_no) || ((end == start) && (end_pos <= start_pos))) {
3337                                 selection_start.line = end;
3338                                 selection_start.tag = LineTag.FindTag(end, end_pos);
3339                                 selection_start.pos = end_pos;
3340
3341                                 selection_end.line = start;
3342                                 selection_end.tag = LineTag.FindTag(start, start_pos);
3343                                 selection_end.pos = start_pos;
3344
3345                                 selection_end_anchor = true;
3346                         } else {
3347                                 selection_start.line = start;
3348                                 selection_start.tag = LineTag.FindTag(start, start_pos);
3349                                 selection_start.pos = start_pos;
3350
3351                                 selection_end.line = end;
3352                                 selection_end.tag = LineTag.FindTag(end, end_pos);
3353                                 selection_end.pos = end_pos;
3354
3355                                 selection_end_anchor = false;
3356                         }
3357
3358                         selection_anchor.line = start;
3359                         selection_anchor.tag = selection_start.tag;
3360                         selection_anchor.pos = start_pos;
3361
3362                         if (((start == end) && (start_pos == end_pos)) || start == null || end == null) {
3363                                 SetSelectionVisible (false);
3364                         } else {
3365                                 SetSelectionVisible (true);
3366                                 Invalidate(selection_start.line, selection_start.pos, selection_end.line, selection_end.pos);
3367                         }
3368                 }
3369
3370                 internal void SetSelectionStart(Line start, int start_pos, bool invalidate) {
3371                         // Invalidate from the previous to the new start pos
3372                         if (invalidate)
3373                                 Invalidate(selection_start.line, selection_start.pos, start, start_pos);
3374
3375                         selection_start.line = start;
3376                         selection_start.pos = start_pos;
3377                         selection_start.tag = LineTag.FindTag(start, start_pos);
3378
3379                         selection_anchor.line = start;
3380                         selection_anchor.pos = start_pos;
3381                         selection_anchor.tag = selection_start.tag;
3382
3383                         selection_end_anchor = false;
3384
3385                         
3386                         if ((selection_end.line != selection_start.line) || (selection_end.pos != selection_start.pos)) {
3387                                 SetSelectionVisible (true);
3388                         } else {
3389                                 SetSelectionVisible (false);
3390                         }
3391
3392                         if (invalidate)
3393                                 Invalidate(selection_start.line, selection_start.pos, selection_end.line, selection_end.pos);
3394                 }
3395
3396                 internal void SetSelectionStart(int character_index, bool invalidate) {
3397                         Line    line;
3398                         LineTag tag;
3399                         int     pos;
3400
3401                         if (character_index < 0) {
3402                                 return;
3403                         }
3404
3405                         CharIndexToLineTag(character_index, out line, out tag, out pos);
3406                         SetSelectionStart(line, pos, invalidate);
3407                 }
3408
3409                 internal void SetSelectionEnd(Line end, int end_pos, bool invalidate) {
3410
3411                         if (end == selection_end.line && end_pos == selection_start.pos) {
3412                                 selection_anchor.line = selection_start.line;
3413                                 selection_anchor.tag = selection_start.tag;
3414                                 selection_anchor.pos = selection_start.pos;
3415
3416                                 selection_end.line = selection_start.line;
3417                                 selection_end.tag = selection_start.tag;
3418                                 selection_end.pos = selection_start.pos;
3419
3420                                 selection_end_anchor = false;
3421                         } else if ((end.line_no < selection_anchor.line.line_no) || ((end == selection_anchor.line) && (end_pos <= selection_anchor.pos))) {
3422                                 selection_start.line = end;
3423                                 selection_start.tag = LineTag.FindTag(end, end_pos);
3424                                 selection_start.pos = end_pos;
3425
3426                                 selection_end.line = selection_anchor.line;
3427                                 selection_end.tag = selection_anchor.tag;
3428                                 selection_end.pos = selection_anchor.pos;
3429
3430                                 selection_end_anchor = true;
3431                         } else {
3432                                 selection_start.line = selection_anchor.line;
3433                                 selection_start.tag = selection_anchor.tag;
3434                                 selection_start.pos = selection_anchor.pos;
3435
3436                                 selection_end.line = end;
3437                                 selection_end.tag = LineTag.FindTag(end, end_pos);
3438                                 selection_end.pos = end_pos;
3439
3440                                 selection_end_anchor = false;
3441                         }
3442
3443                         if ((selection_end.line != selection_start.line) || (selection_end.pos != selection_start.pos)) {
3444                                 SetSelectionVisible (true);
3445                                 if (invalidate)
3446                                         Invalidate(selection_start.line, selection_start.pos, selection_end.line, selection_end.pos);
3447                         } else {
3448                                 SetSelectionVisible (false);
3449                                 // ?? Do I need to invalidate here, tests seem to work without it, but I don't think they should :-s
3450                         }
3451                 }
3452
3453                 internal void SetSelectionEnd(int character_index, bool invalidate) {
3454                         Line    line;
3455                         LineTag tag;
3456                         int     pos;
3457
3458                         if (character_index < 0) {
3459                                 return;
3460                         }
3461
3462                         CharIndexToLineTag(character_index, out line, out tag, out pos);
3463                         SetSelectionEnd(line, pos, invalidate);
3464                 }
3465
3466                 internal void SetSelection(Line start, int start_pos) {
3467                         if (selection_visible) {
3468                                 Invalidate(selection_start.line, selection_start.pos, selection_end.line, selection_end.pos);
3469                         }
3470
3471                         selection_start.line = start;
3472                         selection_start.pos = start_pos;
3473                         selection_start.tag = LineTag.FindTag(start, start_pos);
3474
3475                         selection_end.line = start;
3476                         selection_end.tag = selection_start.tag;
3477                         selection_end.pos = start_pos;
3478
3479                         selection_anchor.line = start;
3480                         selection_anchor.tag = selection_start.tag;
3481                         selection_anchor.pos = start_pos;
3482
3483                         selection_end_anchor = false;
3484                         SetSelectionVisible (false);
3485                 }
3486
3487                 internal void InvalidateSelectionArea() {
3488                         Invalidate (selection_start.line, selection_start.pos, selection_end.line, selection_end.pos);
3489                 }
3490
3491                 // Return the current selection, as string
3492                 internal string GetSelection() {
3493                         // We return String.Empty if there is no selection
3494                         if ((selection_start.pos == selection_end.pos) && (selection_start.line == selection_end.line)) {
3495                                 return string.Empty;
3496                         }
3497
3498                         if (selection_start.line == selection_end.line) {
3499                                 return selection_start.line.text.ToString (selection_start.pos, selection_end.pos - selection_start.pos);
3500                         } else {
3501                                 StringBuilder   sb;
3502                                 int             i;
3503                                 int             start;
3504                                 int             end;
3505
3506                                 sb = new StringBuilder();
3507                                 start = selection_start.line.line_no;
3508                                 end = selection_end.line.line_no;
3509
3510                                 sb.Append(selection_start.line.text.ToString(selection_start.pos, selection_start.line.text.Length - selection_start.pos) + Environment.NewLine);
3511
3512                                 if ((start + 1) < end) {
3513                                         for (i = start + 1; i < end; i++) {
3514                                                 sb.Append(GetLine(i).text.ToString() + Environment.NewLine);
3515                                         }
3516                                 }
3517
3518                                 sb.Append(selection_end.line.text.ToString(0, selection_end.pos));
3519
3520                                 return sb.ToString();
3521                         }
3522                 }
3523
3524                 internal void ReplaceSelection(string s, bool select_new) {
3525                         int             i;
3526
3527                         int selection_pos_on_line = selection_start.pos;
3528                         int selection_start_pos = LineTagToCharIndex (selection_start.line, selection_start.pos);
3529                         SuspendRecalc ();
3530
3531                         // First, delete any selected text
3532                         if ((selection_start.pos != selection_end.pos) || (selection_start.line != selection_end.line)) {
3533                                 if (selection_start.line == selection_end.line) {
3534                                         undo.RecordDeleteString (selection_start.line, selection_start.pos, selection_end.line, selection_end.pos);
3535
3536                                         DeleteChars(selection_start.tag, selection_start.pos, selection_end.pos - selection_start.pos);
3537
3538                                         // The tag might have been removed, we need to recalc it
3539                                         selection_start.tag = selection_start.line.FindTag(selection_start.pos);
3540                                 } else {
3541                                         int             start;
3542                                         int             end;
3543
3544                                         start = selection_start.line.line_no;
3545                                         end = selection_end.line.line_no;
3546
3547                                         undo.RecordDeleteString (selection_start.line, selection_start.pos, selection_end.line, selection_end.pos);
3548
3549                                         InvalidateSelectionArea ();
3550
3551                                         // Delete first line
3552                                         DeleteChars(selection_start.tag, selection_start.pos, selection_start.line.text.Length - selection_start.pos);
3553                                         selection_start.line.recalc = true;
3554
3555                                         // Delete last line
3556                                         DeleteChars(selection_end.line.tags, 0, selection_end.pos);
3557
3558                                         start++;
3559                                         if (start < end) {
3560                                                 for (i = end - 1; i >= start; i--) {
3561                                                         Delete(i);
3562                                                 }
3563                                         }
3564
3565                                         // BIG FAT WARNING - selection_end.line might be stale due 
3566                                         // to the above Delete() call. DONT USE IT before hitting the end of this method!
3567
3568                                         // Join start and end
3569                                         Combine(selection_start.line.line_no, start);
3570                                 }
3571                         }
3572
3573
3574                         Insert(selection_start.line, selection_start.pos, false, s);
3575                         undo.RecordInsertString (selection_start.line, selection_start.pos, s);
3576                         ResumeRecalc (false);
3577
3578                         if (!select_new) {
3579                                 CharIndexToLineTag(selection_start_pos + s.Length, out selection_start.line,
3580                                                 out selection_start.tag, out selection_start.pos);
3581
3582                                 selection_end.line = selection_start.line;
3583                                 selection_end.pos = selection_start.pos;
3584                                 selection_end.tag = selection_start.tag;
3585                                 selection_anchor.line = selection_start.line;
3586                                 selection_anchor.pos = selection_start.pos;
3587                                 selection_anchor.tag = selection_start.tag;
3588
3589                                 SetSelectionVisible (false);
3590                         } else {
3591                                 CharIndexToLineTag(selection_start_pos, out selection_start.line,
3592                                                 out selection_start.tag, out selection_start.pos);
3593
3594                                 CharIndexToLineTag(selection_start_pos + s.Length, out selection_end.line,
3595                                                 out selection_end.tag, out selection_end.pos);
3596
3597                                 selection_anchor.line = selection_start.line;
3598                                 selection_anchor.pos = selection_start.pos;
3599                                 selection_anchor.tag = selection_start.tag;
3600
3601                                 SetSelectionVisible (true);
3602                         }
3603
3604                         PositionCaret (selection_start.line, selection_start.pos);
3605                         UpdateView (selection_start.line, selection_pos_on_line);
3606                 }
3607
3608                 internal void CharIndexToLineTag(int index, out Line line_out, out LineTag tag_out, out int pos) {
3609                         Line    line;
3610                         LineTag tag;
3611                         int     i;
3612                         int     chars;
3613                         int     start;
3614
3615                         chars = 0;
3616
3617                         for (i = 1; i <= lines; i++) {
3618                                 line = GetLine(i);
3619
3620                                 start = chars;
3621                                 chars += line.text.Length;
3622
3623                                 if (index <= chars) {
3624                                         // we found the line
3625                                         tag = line.tags;
3626
3627                                         while (tag != null) {
3628                                                 if (index < (start + tag.start + tag.length - 1)) {
3629                                                         line_out = line;
3630                                                         tag_out = LineTag.GetFinalTag (tag);
3631                                                         pos = index - start;
3632                                                         return;
3633                                                 }
3634                                                 if (tag.next == null) {
3635                                                         Line    next_line;
3636
3637                                                         next_line = GetLine(line.line_no + 1);
3638
3639                                                         if (next_line != null) {
3640                                                                 line_out = next_line;
3641                                                                 tag_out = LineTag.GetFinalTag (next_line.tags);
3642                                                                 pos = 0;
3643                                                                 return;
3644                                                         } else {
3645                                                                 line_out = line;
3646                                                                 tag_out = LineTag.GetFinalTag (tag);
3647                                                                 pos = line_out.text.Length;
3648                                                                 return;
3649                                                         }
3650                                                 }
3651                                                 tag = tag.next;
3652                                         }
3653                                 }
3654                         }
3655
3656                         line_out = GetLine(lines);
3657                         tag = line_out.tags;
3658                         while (tag.next != null) {
3659                                 tag = tag.next;
3660                         }
3661                         tag_out = tag;
3662                         pos = line_out.text.Length;
3663                 }
3664
3665                 internal int LineTagToCharIndex(Line line, int pos) {
3666                         int     i;
3667                         int     length;
3668
3669                         // Count first and last line
3670                         length = 0;
3671
3672                         // Count the lines in the middle
3673
3674                         for (i = 1; i < line.line_no; i++) {
3675                                 length += GetLine(i).text.Length;
3676                         }
3677
3678                         length += pos;
3679
3680                         return length;
3681                 }
3682
3683                 internal int SelectionLength() {
3684                         if ((selection_start.pos == selection_end.pos) && (selection_start.line == selection_end.line)) {
3685                                 return 0;
3686                         }
3687
3688                         if (selection_start.line == selection_end.line) {
3689                                 return selection_end.pos - selection_start.pos;
3690                         } else {
3691                                 int     i;
3692                                 int     start;
3693                                 int     end;
3694                                 int     length;
3695
3696                                 // Count first and last line
3697                                 length = selection_start.line.text.Length - selection_start.pos + selection_end.pos + crlf_size;
3698
3699                                 // Count the lines in the middle
3700                                 start = selection_start.line.line_no + 1;
3701                                 end = selection_end.line.line_no;
3702
3703                                 if (start < end) {
3704                                         for (i = start; i < end; i++) {
3705                                                 Line line = GetLine (i);
3706                                                 length += line.text.Length + LineEndingLength (line.ending);
3707                                         }
3708                                 }
3709
3710                                 return length;
3711                         }
3712
3713                         
3714                 }
3715
3716
3717                 /// <summary>Give it a Line number and it returns the Line object at with that line number</summary>
3718                 internal Line GetLine(int LineNo) {
3719                         Line    line = document;
3720
3721                         while (line != sentinel) {
3722                                 if (LineNo == line.line_no) {
3723                                         return line;
3724                                 } else if (LineNo < line.line_no) {
3725                                         line = line.left;
3726                                 } else {
3727                                         line = line.right;
3728                                 }
3729                         }
3730
3731                         return null;
3732                 }
3733
3734                 /// <summary>Retrieve the previous tag; walks line boundaries</summary>
3735                 internal LineTag PreviousTag(LineTag tag) {
3736                         Line l; 
3737
3738                         if (tag.previous != null) {
3739                                 return tag.previous;
3740                         }
3741
3742                         // Next line 
3743                         if (tag.line.line_no == 1) {
3744                                 return null;
3745                         }
3746
3747                         l = GetLine(tag.line.line_no - 1);
3748                         if (l != null) {
3749                                 LineTag t;
3750
3751                                 t = l.tags;
3752                                 while (t.next != null) {
3753                                         t = t.next;
3754                                 }
3755                                 return t;
3756                         }
3757
3758                         return null;
3759                 }
3760
3761                 /// <summary>Retrieve the next tag; walks line boundaries</summary>
3762                 internal LineTag NextTag(LineTag tag) {
3763                         Line l;
3764
3765                         if (tag.next != null) {
3766                                 return tag.next;
3767                         }
3768
3769                         // Next line
3770                         l = GetLine(tag.line.line_no + 1);
3771                         if (l != null) {
3772                                 return l.tags;
3773                         }
3774
3775                         return null;
3776                 }
3777
3778                 internal Line ParagraphStart(Line line) {
3779                         while (line.ending == LineEnding.Wrap) {
3780                                 line = GetLine(line.line_no - 1);
3781                         }
3782                         return line;
3783                 }       
3784
3785                 internal Line ParagraphEnd(Line line) {
3786                         Line    l;
3787    
3788                         while (line.ending == LineEnding.Wrap) {
3789                                 l = GetLine(line.line_no + 1);
3790                                 if ((l == null) || (l.ending != LineEnding.Wrap)) {
3791                                         break;
3792                                 }
3793                                 line = l;
3794                         }
3795                         return line;
3796                 }
3797
3798                 /// <summary>Give it a pixel offset coordinate and it returns the Line covering that are (offset
3799                 /// is either X or Y depending on if we are multiline
3800                 /// </summary>
3801                 internal Line GetLineByPixel (int offset, bool exact)
3802                 {
3803                         Line    line = document;
3804                         Line    last = null;
3805
3806                         if (multiline) {
3807                                 while (line != sentinel) {
3808                                         last = line;
3809                                         if ((offset >= line.Y) && (offset < (line.Y+line.height))) {
3810                                                 return line;
3811                                         } else if (offset < line.Y) {
3812                                                 line = line.left;
3813                                         } else {
3814                                                 line = line.right;
3815                                         }
3816                                 }
3817                         } else {
3818                                 while (line != sentinel) {
3819                                         last = line;
3820                                         if ((offset >= line.X) && (offset < (line.X + line.Width)))
3821                                                 return line;
3822                                         else if (offset < line.X)
3823                                                 line = line.left;
3824                                         else
3825                                                 line = line.right;
3826                                 }
3827                         }
3828
3829                         if (exact) {
3830                                 return null;
3831                         }
3832                         return last;
3833                 }
3834
3835                 // Give it x/y pixel coordinates and it returns the Tag at that position; optionally the char position is returned in index
3836                 internal LineTag FindTag(int x, int y, out int index, bool exact) {
3837                         Line    line;
3838                         LineTag tag;
3839
3840                         line = GetLineByPixel(y, exact);
3841                         if (line == null) {
3842                                 index = 0;
3843                                 return null;
3844                         }
3845                         tag = line.tags;
3846
3847                         // Alignment adjustment
3848                         x += line.X;
3849
3850                         while (true) {
3851                                 if (x >= tag.X && x < (tag.X+tag.width)) {
3852                                         int     end;
3853
3854                                         end = tag.start + tag.length - 1;
3855
3856                                         for (int pos = tag.start; pos < end; pos++) {
3857                                                 if (x < line.widths[pos]) {
3858                                                         index = pos;
3859                                                         return LineTag.GetFinalTag (tag);
3860                                                 }
3861                                         }
3862                                         index=end;
3863                                         return LineTag.GetFinalTag (tag);
3864                                 }
3865                                 if (tag.next != null) {
3866                                         tag = tag.next;
3867                                 } else {
3868                                         if (exact) {
3869                                                 index = 0;
3870                                                 return null;
3871                                         }
3872
3873                                         index = line.text.Length;
3874                                         return LineTag.GetFinalTag (tag);
3875                                 }
3876                         }
3877                 }
3878
3879                 // Give it x/y pixel coordinates and it returns the Tag at that position; optionally the char position is returned in index
3880                 internal LineTag FindCursor(int x, int y, out int index) {
3881                         Line    line;
3882                         LineTag tag;
3883
3884                         line = GetLineByPixel(multiline ? y : x, false);
3885                         tag = line.tags;
3886
3887                         /// Special case going leftwards of the first tag
3888                         if (x < tag.X) {
3889                                 index = 0;
3890                                 return LineTag.GetFinalTag (tag);
3891                         }
3892
3893                         while (true) {
3894                                 if (x >= tag.X && x < (tag.X+tag.width)) {
3895                                         int     end;
3896
3897                                         end = tag.TextEnd;
3898
3899                                         for (int pos = tag.start - 1; pos < end; pos++) {
3900                                                 // When clicking on a character, we position the cursor to whatever edge
3901                                                 // of the character the click was closer
3902                                                 if (x < (line.X + line.widths[pos] + ((line.widths[pos+1]-line.widths[pos])/2))) {
3903                                                         index = pos;
3904                                                         return LineTag.GetFinalTag (tag);
3905                                                 }
3906                                         }
3907                                         index=end;
3908                                         return LineTag.GetFinalTag (tag);
3909                                 }
3910                                 if (tag.next != null) {
3911                                         tag = tag.next;
3912                                 } else {
3913                                         index = line.TextLengthWithoutEnding ();
3914                                         return LineTag.GetFinalTag (tag);
3915                                 }
3916                         }
3917                 }
3918
3919                 /// <summary>Format area of document in specified font and color</summary>
3920                 /// <param name="start_pos">1-based start position on start_line</param>
3921                 /// <param name="end_pos">1-based end position on end_line </param>
3922                 internal void FormatText (Line start_line, int start_pos, Line end_line, int end_pos, Font font,
3923                                 SolidBrush color, SolidBrush back_color, FormatSpecified specified)
3924                 {
3925                         Line    l;
3926
3927                         // First, format the first line
3928                         if (start_line != end_line) {
3929                                 // First line
3930                                 LineTag.FormatText(start_line, start_pos, start_line.text.Length - start_pos + 1, font, color, back_color, specified);
3931
3932                                 // Format last line
3933                                 LineTag.FormatText(end_line, 1, end_pos, font, color, back_color, specified);
3934
3935                                 // Now all the lines inbetween
3936                                 for (int i = start_line.line_no + 1; i < end_line.line_no; i++) {
3937                                         l = GetLine(i);
3938                                         LineTag.FormatText(l, 1, l.text.Length, font, color, back_color, specified);
3939                                 }
3940                         } else {
3941                                 // Special case, single line
3942                                 LineTag.FormatText(start_line, start_pos, end_pos - start_pos, font, color, back_color, specified);
3943                         }
3944                 }
3945
3946                 internal void RecalculateAlignments ()
3947                 {
3948                         Line    line;
3949                         int     line_no;
3950
3951                         line_no = 1;
3952
3953
3954
3955                         while (line_no <= lines) {
3956                                 line = GetLine(line_no);
3957
3958                                 if (line != null) {
3959                                         switch (line.alignment) {
3960                                         case HorizontalAlignment.Left:
3961                                                 line.align_shift = 0;
3962                                                 break;
3963                                         case HorizontalAlignment.Center:
3964                                                 line.align_shift = (viewport_width - (int)line.widths[line.text.Length]) / 2;
3965                                                 break;
3966                                         case HorizontalAlignment.Right:
3967                                                 line.align_shift = viewport_width - (int)line.widths[line.text.Length] - right_margin;
3968                                                 break;
3969                                         }
3970                                 }
3971
3972                                 line_no++;
3973                         }
3974                         return;
3975                 }
3976
3977                 /// <summary>Calculate formatting for the whole document</summary>
3978                 internal bool RecalculateDocument(Graphics g) {
3979                         return RecalculateDocument(g, 1, this.lines, false);
3980                 }
3981
3982                 /// <summary>Calculate formatting starting at a certain line</summary>
3983                 internal bool RecalculateDocument(Graphics g, int start) {
3984                         return RecalculateDocument(g, start, this.lines, false);
3985                 }
3986
3987                 /// <summary>Calculate formatting within two given line numbers</summary>
3988                 internal bool RecalculateDocument(Graphics g, int start, int end) {
3989                         return RecalculateDocument(g, start, end, false);
3990                 }
3991
3992                 /// <summary>With optimize on, returns true if line heights changed</summary>
3993                 internal bool RecalculateDocument(Graphics g, int start, int end, bool optimize) {
3994                         Line    line;
3995                         int     line_no;
3996                         int     offset;
3997                         int     new_width;
3998                         bool    changed;
3999                         int     shift;
4000
4001                         if (recalc_suspended > 0) {
4002                                 recalc_pending = true;
4003                                 recalc_start = Math.Min (recalc_start, start);
4004                                 recalc_end = Math.Max (recalc_end, end);
4005                                 recalc_optimize = optimize;
4006                                 return false;
4007                         }
4008
4009                         // Fixup the positions, they can go kinda nuts
4010                         start = Math.Max (start, 1);
4011                         end = Math.Min (end, lines);
4012
4013                         offset = GetLine(start).offset;
4014                         line_no = start;
4015                         new_width = 0;
4016                         shift = this.lines;
4017                         if (!optimize) {
4018                                 changed = true;         // We always return true if we run non-optimized
4019                         } else {
4020                                 changed = false;
4021                         }
4022
4023                         while (line_no <= (end + this.lines - shift)) {
4024                                 line = GetLine(line_no++);
4025                                 line.offset = offset;
4026
4027                                 if (!calc_pass) {
4028                                         if (!optimize) {
4029                                                 line.RecalculateLine(g, this);
4030                                         } else {
4031                                                 if (line.recalc && line.RecalculateLine(g, this)) {
4032                                                         changed = true;
4033                                                         // If the height changed, all subsequent lines change
4034                                                         end = this.lines;
4035                                                         shift = this.lines;
4036                                                 }
4037                                         }
4038                                 } else {
4039                                         if (!optimize) {
4040                                                 line.RecalculatePasswordLine(g, this);
4041                                         } else {
4042                                                 if (line.recalc && line.RecalculatePasswordLine(g, this)) {
4043                                                         changed = true;
4044                                                         // If the height changed, all subsequent lines change
4045                                                         end = this.lines;
4046                                                         shift = this.lines;
4047                                                 }
4048                                         }
4049                                 }
4050
4051                                 if (line.widths[line.text.Length] > new_width) {
4052                                         new_width = (int)line.widths[line.text.Length];
4053                                 }
4054
4055                                 // Calculate alignment
4056                                 if (line.alignment != HorizontalAlignment.Left) {
4057                                         if (line.alignment == HorizontalAlignment.Center) {
4058                                                 line.align_shift = (viewport_width - (int)line.widths[line.text.Length]) / 2;
4059                                         } else {
4060                                                 line.align_shift = viewport_width - (int)line.widths[line.text.Length] - 1;
4061                                         }
4062                                 }
4063
4064                                 if (multiline)
4065                                         offset += line.height;
4066                                 else
4067                                         offset += (int) line.widths [line.text.Length];
4068
4069                                 if (line_no > lines) {
4070                                         break;
4071                                 }
4072                         }
4073
4074                         if (document_x != new_width) {
4075                                 document_x = new_width;
4076                                 if (WidthChanged != null) {
4077                                         WidthChanged(this, null);
4078                                 }
4079                         }
4080
4081                         RecalculateAlignments();
4082
4083                         line = GetLine(lines);
4084
4085                         if (document_y != line.Y + line.height) {
4086                                 document_y = line.Y + line.height;
4087                                 if (HeightChanged != null) {
4088                                         HeightChanged(this, null);
4089                                 }
4090                         }
4091                         UpdateCaret();
4092                         return changed;
4093                 }
4094
4095                 internal int Size() {
4096                         return lines;
4097                 }
4098
4099                 private void owner_HandleCreated(object sender, EventArgs e) {
4100                         RecalculateDocument(owner.CreateGraphicsInternal());
4101                         AlignCaret();
4102                 }
4103
4104                 private void owner_VisibleChanged(object sender, EventArgs e) {
4105                         if (owner.Visible) {
4106                                 RecalculateDocument(owner.CreateGraphicsInternal());
4107                         }
4108                 }
4109
4110                 internal static bool IsWordSeparator (char ch)
4111                 {
4112                         switch (ch) {
4113                         case ' ':
4114                         case '\t':
4115                         case '(':
4116                         case ')':
4117                         case '\r':
4118                         case '\n':
4119                                 return true;
4120                         default:
4121                                 return false;
4122                         }
4123                 }
4124
4125                 internal int FindWordSeparator(Line line, int pos, bool forward) {
4126                         int len;
4127
4128                         len = line.text.Length;
4129
4130                         if (forward) {
4131                                 for (int i = pos + 1; i < len; i++) {
4132                                         if (IsWordSeparator(line.Text[i])) {
4133                                                 return i + 1;
4134                                         }
4135                                 }
4136                                 return len;
4137                         } else {
4138                                 for (int i = pos - 1; i > 0; i--) {
4139                                         if (IsWordSeparator(line.Text[i - 1])) {
4140                                                 return i;
4141                                         }
4142                                 }
4143                                 return 0;
4144                         }
4145                 }
4146
4147                 /* Search document for text */
4148                 internal bool FindChars(char[] chars, Marker start, Marker end, out Marker result) {
4149                         Line    line;
4150                         int     line_no;
4151                         int     pos;
4152                         int     line_len;
4153
4154                         // Search for occurence of any char in the chars array
4155                         result = new Marker();
4156
4157                         line = start.line;
4158                         line_no = start.line.line_no;
4159                         pos = start.pos;
4160                         while (line_no <= end.line.line_no) {
4161                                 line_len = line.text.Length;
4162                                 while (pos < line_len) {
4163                                         for (int i = 0; i < chars.Length; i++) {
4164                                                 if (line.text[pos] == chars[i]) {
4165                                                         // Special case
4166                                                         if ((line.line_no == end.line.line_no) && (pos >= end.pos)) {
4167                                                                 return false;
4168                                                         }
4169
4170                                                         result.line = line;
4171                                                         result.pos = pos;
4172                                                         return true;
4173                                                 }
4174                                         }
4175                                         pos++;
4176                                 }
4177
4178                                 pos = 0;
4179                                 line_no++;
4180                                 line = GetLine(line_no);
4181                         }
4182
4183                         return false;
4184                 }
4185
4186                 // This version does not build one big string for searching, instead it handles 
4187                 // line-boundaries, which is faster and less memory intensive
4188                 // FIXME - Depending on culture stuff we might have to create a big string and use culturespecific 
4189                 // search stuff and change it to accept and return positions instead of Markers (which would match 
4190                 // RichTextBox behaviour better but would be inconsistent with the rest of TextControl)
4191                 internal bool Find(string search, Marker start, Marker end, out Marker result, RichTextBoxFinds options) {
4192                         Marker  last;
4193                         string  search_string;
4194                         Line    line;
4195                         int     line_no;
4196                         int     pos;
4197                         int     line_len;
4198                         int     current;
4199                         bool    word;
4200                         bool    word_option;
4201                         bool    ignore_case;
4202                         bool    reverse;
4203                         char    c;
4204
4205                         result = new Marker();
4206                         word_option = ((options & RichTextBoxFinds.WholeWord) != 0);
4207                         ignore_case = ((options & RichTextBoxFinds.MatchCase) == 0);
4208                         reverse = ((options & RichTextBoxFinds.Reverse) != 0);
4209
4210                         line = start.line;
4211                         line_no = start.line.line_no;
4212                         pos = start.pos;
4213                         current = 0;
4214
4215                         // Prep our search string, lowercasing it if we do case-independent matching
4216                         if (ignore_case) {
4217                                 StringBuilder   sb;
4218                                 sb = new StringBuilder(search);
4219                                 for (int i = 0; i < sb.Length; i++) {
4220                                         sb[i] = Char.ToLower(sb[i]);
4221                                 }
4222                                 search_string = sb.ToString();
4223                         } else {
4224                                 search_string = search;
4225                         }
4226
4227                         // We need to check if the character before our start position is a wordbreak
4228                         if (word_option) {
4229                                 if (line_no == 1) {
4230                                         if ((pos == 0) || (IsWordSeparator(line.text[pos - 1]))) {
4231                                                 word = true;
4232                                         } else {
4233                                                 word = false;
4234                                         }
4235                                 } else {
4236                                         if (pos > 0) {
4237                                                 if (IsWordSeparator(line.text[pos - 1])) {
4238                                                         word = true;
4239                                                 } else {
4240                                                         word = false;
4241                                                 }
4242                                         } else {
4243                                                 // Need to check the end of the previous line
4244                                                 Line    prev_line;
4245
4246                                                 prev_line = GetLine(line_no - 1);
4247                                                 if (prev_line.ending == LineEnding.Wrap) {
4248                                                         if (IsWordSeparator(prev_line.text[prev_line.text.Length - 1])) {
4249                                                                 word = true;
4250                                                         } else {
4251                                                                 word = false;
4252                                                         }
4253                                                 } else {
4254                                                         word = true;
4255                                                 }
4256                                         }
4257                                 }
4258                         } else {
4259                                 word = false;
4260                         }
4261
4262                         // To avoid duplication of this loop with reverse logic, we search
4263                         // through the document, remembering the last match and when returning
4264                         // report that last remembered match
4265
4266                         last = new Marker();
4267                         last.height = -1;       // Abused - we use it to track change
4268
4269                         while (line_no <= end.line.line_no) {
4270                                 if (line_no != end.line.line_no) {
4271                                         line_len = line.text.Length;
4272                                 } else {
4273                                         line_len = end.pos;
4274                                 }
4275
4276                                 while (pos < line_len) {
4277
4278                                         if (word_option && (current == search_string.Length)) {
4279                                                 if (IsWordSeparator(line.text[pos])) {
4280                                                         if (!reverse) {
4281                                                                 goto FindFound;
4282                                                         } else {
4283                                                                 last = result;
4284                                                                 current = 0;
4285                                                         }
4286                                                 } else {
4287                                                         current = 0;
4288                                                 }
4289                                         }
4290
4291                                         if (ignore_case) {
4292                                                 c = Char.ToLower(line.text[pos]);
4293                                         } else {
4294                                                 c = line.text[pos];
4295                                         }
4296
4297                                         if (c == search_string[current]) {
4298                                                 
4299                                                 if (current == 0) {
4300                                                         result.line = line;
4301                                                         result.pos = pos;
4302                                                 }
4303                                                 if (!word_option || (word_option && (word || (current > 0)))) {
4304                                                         current++;
4305                                                 }
4306
4307                                                 if (!word_option && (current == search_string.Length)) {
4308                                                         if (!reverse) {
4309                                                                 goto FindFound;
4310                                                         } else {
4311                                                                 last = result;
4312                                                                 current = 0;
4313                                                         }
4314                                                 }
4315                                         } else {
4316                                                 current = 0;
4317                                         }
4318                                         pos++;
4319
4320                                         if (!word_option) {
4321                                                 continue;
4322                                         }
4323
4324                                         if (IsWordSeparator(c)) {
4325                                                 word = true;
4326                                         } else {
4327                                                 word = false;
4328                                         }
4329                                 }
4330
4331                                 if (word_option) {
4332                                         // Mark that we just saw a word boundary
4333                                         if (line.ending != LineEnding.Wrap || line.line_no == lines - 1) {
4334                                                 word = true;
4335                                         }
4336
4337                                         if (current == search_string.Length) {
4338                                                 if (word) {
4339                                                         if (!reverse) {
4340                                                                 goto FindFound;
4341                                                         } else {
4342                                                                 last = result;
4343                                                                 current = 0;
4344                                                         }
4345                                                 } else {
4346                                                         current = 0;
4347                                                 }
4348                                         }
4349                                 }
4350
4351                                 pos = 0;
4352                                 line_no++;
4353                                 line = GetLine(line_no);
4354                         }
4355
4356                         if (reverse) {
4357                                 if (last.height != -1) {
4358                                         result = last;
4359                                         return true;
4360                                 }
4361                         }
4362
4363                         return false;
4364
4365                         FindFound:
4366                         if (!reverse) {
4367 //                              if ((line.line_no == end.line.line_no) && (pos >= end.pos)) {
4368 //                                      return false;
4369 //                              }
4370                                 return true;
4371                         }
4372
4373                         result = last;
4374                         return true;
4375
4376                 }
4377
4378                 /* Marker stuff */
4379                 internal void GetMarker(out Marker mark, bool start) {
4380                         mark = new Marker();
4381
4382                         if (start) {
4383                                 mark.line = GetLine(1);
4384                                 mark.tag = mark.line.tags;
4385                                 mark.pos = 0;
4386                         } else {
4387                                 mark.line = GetLine(lines);
4388                                 mark.tag = mark.line.tags;
4389                                 while (mark.tag.next != null) {
4390                                         mark.tag = mark.tag.next;
4391                                 }
4392                                 mark.pos = mark.line.text.Length;
4393                         }
4394                 }
4395                 #endregion      // Internal Methods
4396
4397                 #region Events
4398                 internal event EventHandler CaretMoved;
4399                 internal event EventHandler WidthChanged;
4400                 internal event EventHandler HeightChanged;
4401                 internal event EventHandler LengthChanged;
4402                 #endregion      // Events
4403
4404                 #region Administrative
4405                 public IEnumerator GetEnumerator() {
4406                         // FIXME
4407                         return null;
4408                 }
4409
4410                 public override bool Equals(object obj) {
4411                         if (obj == null) {
4412                                 return false;
4413                         }
4414
4415                         if (!(obj is Document)) {
4416                                 return false;
4417                         }
4418
4419                         if (obj == this) {
4420                                 return true;
4421                         }
4422
4423                         if (ToString().Equals(((Document)obj).ToString())) {
4424                                 return true;
4425                         }
4426
4427                         return false;
4428                 }
4429
4430                 public override int GetHashCode() {
4431                         return document_id;
4432                 }
4433
4434                 public override string ToString() {
4435                         return "document " + this.document_id;
4436                 }
4437                 #endregion      // Administrative
4438         }
4439
4440         internal class PictureTag : LineTag {
4441
4442                 internal RTF.Picture picture;
4443
4444                 internal PictureTag (Line line, int start, RTF.Picture picture) : base (line, start)
4445                 {
4446                         this.picture = picture;
4447                 }
4448
4449                 public override bool IsTextTag {
4450                         get { return false; }
4451                 }
4452
4453                 internal override SizeF SizeOfPosition (Graphics dc, int pos)
4454                 {
4455                         return picture.Size;
4456                 }
4457
4458                 internal override int MaxHeight ()
4459                 {
4460                         return (int) (picture.Height + 0.5F);
4461                 }
4462
4463                 internal override void Draw (Graphics dc, Brush brush, float xoff, float y, int start, int end)
4464                 {
4465                         picture.DrawImage (dc, xoff + line.widths [start], y, false);
4466                 }
4467
4468                 internal override void Draw (Graphics dc, Brush brush, float xoff, float y, int start, int end, string text)
4469                 {
4470                         picture.DrawImage (dc, xoff + + line.widths [start], y, false);
4471                 }
4472
4473                 public override string Text ()
4474                 {
4475                         return "I";
4476                 }
4477         }
4478
4479         internal class LineTag {
4480                 #region Local Variables;
4481                 // Payload; formatting
4482                 internal Font           font;           // System.Drawing.Font object for this tag
4483                 internal SolidBrush     color;          // The font color for this tag
4484
4485                 // In 2.0 tags can have background colours.  I'm not going to #ifdef
4486                 // at this level though since I want to reduce code paths
4487                 internal SolidBrush back_color;  
4488
4489                 // Payload; text
4490                 internal int            start;          // start, in chars; index into Line.text
4491                 internal bool           r_to_l;         // Which way is the font
4492
4493                 // Drawing support
4494                 internal int            height;         // Height in pixels of the text this tag describes
4495
4496                 internal int            ascent;         // Ascent of the font for this tag
4497                 internal int            shift;          // Shift down for this tag, to stay on baseline
4498
4499                 // Administrative
4500                 internal Line           line;           // The line we're on
4501                 internal LineTag        next;           // Next tag on the same line
4502                 internal LineTag        previous;       // Previous tag on the same line
4503                 #endregion;
4504
4505                 #region Constructors
4506                 internal LineTag(Line line, int start) {
4507                         this.line = line;
4508                         this.start = start;
4509                 }
4510                 #endregion      // Constructors
4511
4512                 #region Internal Methods
4513
4514                 public float X {
4515                         get {
4516                                 if (start == 0)
4517                                         return line.X;
4518                                 return line.X + line.widths [start - 1];
4519                         }
4520                 }
4521
4522                 public int end {
4523                         get { return start + length; }
4524                 }
4525
4526                 public int TextEnd {
4527                         get { return start + TextLength; }
4528                 }
4529
4530                 public float width {
4531                         get {
4532                                 if (length == 0)
4533                                         return 0;
4534                                 return line.widths [start + length - 1] - (start != 0 ? line.widths [start - 1] : 0);
4535                         }
4536                 }
4537
4538                 public int length {
4539                         get {
4540                                 int res = 0;
4541                                 if (next != null)
4542                                         res = next.start - start;
4543                                 else
4544                                         res = line.text.Length - (start - 1);
4545
4546                                 return res > 0 ? res : 0;
4547                         }
4548                 }
4549
4550                 public int TextLength {
4551                         get {
4552                                 int res = 0;
4553                                 if (next != null)
4554                                         res = next.start - start;
4555                                 else
4556                                         res = line.TextLengthWithoutEnding () - (start - 1);
4557
4558                                 return res > 0 ? res : 0;
4559                         }
4560                 }
4561
4562                 public virtual bool IsTextTag {
4563                         get { return true; }
4564                 }
4565
4566                 internal virtual SizeF SizeOfPosition (Graphics dc, int pos)
4567                 {
4568                         if (pos >= line.TextLengthWithoutEnding () && line.document.multiline)
4569                                 return SizeF.Empty;
4570
4571                         string text = line.text.ToString (pos, 1);
4572                         switch ((int) text [0]) {
4573                         case '\t':
4574                                 if (!line.document.multiline)
4575                                         goto case 10;
4576                                 SizeF res = dc.MeasureString (" ", font, 10000, Document.string_format);
4577                                 res.Width *= 8.0F;
4578                                 return res;
4579                         case 10:
4580                         case 13:
4581                                 return dc.MeasureString ("\u0013", font, 10000, Document.string_format);
4582                         }
4583                         
4584                         return dc.MeasureString (text, font, 10000, Document.string_format);
4585                 }
4586
4587                 internal virtual int MaxHeight ()
4588                 {
4589                         return font.Height;
4590                 }
4591
4592                 internal virtual void Draw (Graphics dc, Brush brush, float x, float y, int start, int end)
4593                 {
4594                         dc.DrawString (line.text.ToString (start, end), font, brush, x, y, StringFormat.GenericTypographic);
4595                 }
4596
4597                 internal virtual void Draw (Graphics dc, Brush brush, float xoff, float y, int start, int end, string text)
4598                 {
4599                         while (start < end) {
4600                                 int tab_index = text.IndexOf ("\t", start);
4601                                 if (tab_index == -1)
4602                                         tab_index = end;
4603                                 dc.DrawString (text.Substring (start, tab_index - start), font, brush, xoff + line.widths [start],
4604                                                 y, StringFormat.GenericTypographic);
4605
4606                                 // non multilines get the unknown char 
4607                                 if (!line.document.multiline && tab_index != end)
4608                                         dc.DrawString ("\u0013", font, brush,  xoff + line.widths [tab_index], y, Document.string_format);
4609                                         
4610                                 start = tab_index + 1;
4611                         }
4612                 }
4613
4614                 ///<summary>Break a tag into two with identical attributes; pos is 1-based; returns tag starting at &gt;pos&lt; or null if end-of-line</summary>
4615                 internal LineTag Break(int pos) {
4616
4617                         LineTag new_tag;
4618
4619                         // Sanity
4620                         if (pos == this.start) {
4621                                 return this;
4622                         } else if (pos >= (start + length)) {
4623                                 return null;
4624                         }
4625
4626                         new_tag = new LineTag(line, pos);
4627                         new_tag.CopyFormattingFrom (this);
4628
4629                         new_tag.next = this.next;
4630                         this.next = new_tag;
4631                         new_tag.previous = this;
4632
4633                         if (new_tag.next != null) {
4634                                 new_tag.next.previous = new_tag;
4635                         }
4636
4637                         return new_tag;
4638                 }
4639
4640                 public virtual string Text ()
4641                 {
4642                         return line.text.ToString (start - 1, length);
4643                 }
4644
4645                 public void CopyFormattingFrom (LineTag other)
4646                 {
4647                         height = other.height;
4648                         font = other.font;
4649                         color = other.color;
4650                         back_color = other.back_color;
4651                 }
4652
4653                 /// <summary>Applies 'font' and 'brush' to characters starting at 'start' for 'length' chars; 
4654                 /// Removes any previous tags overlapping the same area; 
4655                 /// returns true if lineheight has changed</summary>
4656                 /// <param name="start">1-based character position on line</param>
4657                 internal static bool FormatText(Line line, int start, int length, Font font, SolidBrush color, SolidBrush back_color, FormatSpecified specified)
4658                 {
4659                         LineTag tag;
4660                         LineTag start_tag;
4661                         LineTag end_tag;
4662                         int     end;
4663                         bool    retval = false;         // Assume line-height doesn't change
4664
4665                         // Too simple?
4666                         if (((FormatSpecified.Font & specified) == FormatSpecified.Font) && font.Height != line.height) {
4667                                 retval = true;
4668                         }
4669                         line.recalc = true;             // This forces recalculation of the line in RecalculateDocument
4670
4671                         // A little sanity, not sure if it's needed, might be able to remove for speed
4672                         if (length > line.text.Length) {
4673                                 length = line.text.Length;
4674                         }
4675
4676                         tag = line.tags;
4677                         end = start + length;
4678
4679                         // Common special case
4680                         if ((start == 1) && (length == tag.length)) {
4681                                 tag.ascent = 0;
4682                                 SetFormat (tag, font, color, back_color, specified);
4683                                 return retval;
4684                         }
4685
4686                         start_tag = FindTag (line, start);
4687                         tag = start_tag.Break (start);
4688
4689                         while (tag != null && tag.end <= end) {
4690                                 SetFormat (tag, font, color, back_color, specified);
4691                                 tag = tag.next;
4692                         }
4693
4694                         if (tag != null && tag.end == end)
4695                                 return retval;
4696
4697                         /// Now do the last tag
4698                         end_tag = FindTag (line, end);
4699
4700                         if (end_tag != null) {
4701                                 end_tag.Break (end);
4702                                 SetFormat (end_tag, font, color, back_color, specified);
4703                         }
4704
4705                         return retval;
4706                 }
4707
4708                 private static void SetFormat (LineTag tag, Font font, SolidBrush color, SolidBrush back_color, FormatSpecified specified)
4709                 {
4710                         if ((FormatSpecified.Font & specified) == FormatSpecified.Font)
4711                                 tag.font = font;
4712                         if ((FormatSpecified.Color & specified) == FormatSpecified.Color)
4713                                 tag.color = color;
4714                         if ((FormatSpecified.BackColor & specified) == FormatSpecified.BackColor) {
4715                                 tag.back_color = back_color;
4716                         }
4717                         // Console.WriteLine ("setting format:   {0}  {1}   new color {2}", color.Color, specified, tag.color.Color);
4718                 }
4719
4720                 /// <summary>Finds the tag that describes the character at position 'pos' on 'line'</summary>
4721                 internal static LineTag FindTag(Line line, int pos) {
4722                         LineTag tag = line.tags;
4723
4724                         // Beginning of line is a bit special
4725                         if (pos == 0) {
4726                                 // Not sure if we should get the final tag here
4727                                 return tag;
4728                         }
4729
4730                         while (tag != null) {
4731                                 if ((tag.start <= pos) && (pos <= tag.end)) {
4732                                         return GetFinalTag (tag);
4733                                 }
4734
4735                                 tag = tag.next;
4736                         }
4737
4738                         return null;
4739                 }
4740
4741                 // There can be multiple tags at the same position, we want to make
4742                 // sure we are using the very last tag at the given position
4743                 internal static LineTag GetFinalTag (LineTag tag)
4744                 {
4745                         LineTag res = tag;
4746
4747                         while (res.length == 0 && res.next != null && res.next.length == 0)
4748                                 res = res.next;
4749
4750                         return res;
4751                 }
4752
4753                 /// <summary>Combines 'this' tag with 'other' tag</summary>
4754                 internal bool Combine(LineTag other) {
4755                         if (!this.Equals(other)) {
4756                                 return false;
4757                         }
4758
4759                         this.next = other.next;
4760                         if (this.next != null) {
4761                                 this.next.previous = this;
4762                         }
4763
4764                         return true;
4765                 }
4766
4767
4768                 /// <summary>Remove 'this' tag ; to be called when formatting is to be removed</summary>
4769                 internal bool Remove() {
4770                         if ((this.start == 1) && (this.next == null)) {
4771                                 // We cannot remove the only tag
4772                                 return false;
4773                         }
4774                         if (this.start != 1) {
4775                                 this.previous.next = this.next;
4776                                 this.next.previous = this.previous;
4777                         } else {
4778                                 this.next.start = 1;
4779                                 this.line.tags = this.next;
4780                                 this.next.previous = null;
4781                         }
4782                         return true;
4783                 }
4784
4785
4786                 /// <summary>Checks if 'this' tag describes the same formatting options as 'obj'</summary>
4787                 public override bool Equals(object obj) {
4788                         LineTag other;
4789
4790                         if (obj == null) {
4791                                 return false;
4792                         }
4793
4794                         if (!(obj is LineTag)) {
4795                                 return false;
4796                         }
4797
4798                         if (obj == this) {
4799                                 return true;
4800                         }
4801
4802                         other = (LineTag)obj;
4803
4804                         if (other.IsTextTag != IsTextTag)
4805                                 return false;
4806
4807                         if (this.font.Equals(other.font) && this.color.Equals(other.color)) {   // FIXME add checking for things like link or type later
4808                                 return true;
4809                         }
4810
4811                         return false;
4812                 }
4813
4814                 public override int GetHashCode() {
4815                         return base.GetHashCode ();
4816                 }
4817
4818                 public override string ToString() {
4819                         if (length > 0)
4820                                 return GetType () + " Tag starts at index " + this.start + " length " + this.length + " text: " + Text () + "Font " + this.font.ToString();
4821                         return "Zero Lengthed tag at index " + this.start;
4822                 }
4823
4824                 #endregion      // Internal Methods
4825         }
4826
4827         internal class UndoManager {
4828
4829                 internal enum ActionType {
4830
4831                         Typing,
4832
4833                         // This is basically just cut & paste
4834                         InsertString,
4835                         DeleteString,
4836
4837                         UserActionBegin,
4838                         UserActionEnd
4839                 }
4840
4841                 internal class Action {
4842                         internal ActionType     type;
4843                         internal int            line_no;
4844                         internal int            pos;
4845                         internal object         data;
4846                 }
4847
4848                 #region Local Variables
4849                 private Document        document;
4850                 private Stack           undo_actions;
4851                 private Stack           redo_actions;
4852
4853                 //private int           caret_line;
4854                 //private int           caret_pos;
4855
4856                 // When performing an action, we lock the queue, so that the action can't be undone
4857                 private bool locked;
4858                 #endregion      // Local Variables
4859
4860                 #region Constructors
4861                 internal UndoManager (Document document)
4862                 {
4863                         this.document = document;
4864                         undo_actions = new Stack (50);
4865                         redo_actions = new Stack (50);
4866                 }
4867                 #endregion      // Constructors
4868
4869                 #region Properties
4870                 internal bool CanUndo {
4871                         get { return undo_actions.Count > 0; }
4872                 }
4873
4874                 internal bool CanRedo {
4875                         get { return redo_actions.Count > 0; }
4876                 }
4877
4878                 internal string UndoActionName {
4879                         get {
4880                                 foreach (Action action in undo_actions) {
4881                                         if (action.type == ActionType.UserActionBegin)
4882                                                 return (string) action.data;
4883                                         if (action.type == ActionType.Typing)
4884                                                 return Locale.GetText ("Typing");
4885                                 }
4886                                 return String.Empty;
4887                         }
4888                 }
4889
4890                 internal string RedoActionName {
4891                         get {
4892                                 foreach (Action action in redo_actions) {
4893                                         if (action.type == ActionType.UserActionBegin)
4894                                                 return (string) action.data;
4895                                         if (action.type == ActionType.Typing)
4896                                                 return Locale.GetText ("Typing");
4897                                 }
4898                                 return String.Empty;
4899                         }
4900                 }
4901                 #endregion      // Properties
4902
4903                 #region Internal Methods
4904                 internal void Clear ()
4905                 {
4906                         undo_actions.Clear();
4907                         redo_actions.Clear();
4908                 }
4909
4910                 internal void Undo ()
4911                 {
4912                         Action action;
4913                         bool user_action_finished = false;
4914
4915                         if (undo_actions.Count == 0)
4916                                 return;
4917
4918                         // Nuke the redo queue
4919                         redo_actions.Clear ();
4920
4921                         locked = true;
4922                         do {
4923                                 Line start;
4924                                 action = (Action) undo_actions.Pop ();
4925
4926                                 // Put onto redo stack
4927                                 redo_actions.Push(action);
4928
4929                                 // Do the thing
4930                                 switch(action.type) {
4931
4932                                 case ActionType.UserActionBegin:
4933                                         user_action_finished = true;
4934                                         break;
4935
4936                                 case ActionType.UserActionEnd:
4937                                         // noop
4938                                         break;
4939
4940                                 case ActionType.InsertString:
4941                                         start = document.GetLine (action.line_no);
4942                                         document.SuspendUpdate ();
4943                                         document.DeleteMultiline (start, action.pos, ((string) action.data).Length + 1);
4944                                         document.PositionCaret (start, action.pos);
4945                                         document.SetSelectionToCaret (true);
4946                                         document.ResumeUpdate (true);
4947                                         break;
4948
4949                                 case ActionType.Typing:
4950                                         start = document.GetLine (action.line_no);
4951                                         document.SuspendUpdate ();
4952                                         document.DeleteMultiline (start, action.pos, ((StringBuilder) action.data).Length);
4953                                         document.PositionCaret (start, action.pos);
4954                                         document.SetSelectionToCaret (true);
4955                                         document.ResumeUpdate (true);
4956
4957                                         // This is an open ended operation, so only a single typing operation can be undone at once
4958                                         user_action_finished = true;
4959                                         break;
4960
4961                                 case ActionType.DeleteString:
4962                                         start = document.GetLine (action.line_no);
4963                                         document.SuspendUpdate ();
4964                                         Insert (start, action.pos, (Line) action.data, true);
4965                                         document.ResumeUpdate (true);
4966                                         break;
4967                                 }
4968                         } while (!user_action_finished && undo_actions.Count > 0);
4969
4970                         locked = false;
4971                 }
4972
4973                 internal void Redo ()
4974                 {
4975                         Action action;
4976                         bool user_action_finished = false;
4977
4978                         if (redo_actions.Count == 0)
4979                                 return;
4980
4981                         // You can't undo anything after redoing
4982                         undo_actions.Clear ();
4983
4984                         locked = true;
4985                         do {
4986                                 Line start;
4987                                 int start_index;
4988
4989                                 action = (Action) redo_actions.Pop ();
4990
4991                                 switch (action.type) {
4992
4993                                 case ActionType.UserActionBegin:
4994                                         //  Noop
4995                                         break;
4996
4997                                 case ActionType.UserActionEnd:
4998                                         user_action_finished = true;
4999                                         break;
5000
5001                                 case ActionType.InsertString:
5002                                         start = document.GetLine (action.line_no);
5003                                         document.SuspendUpdate ();
5004                                         start_index = document.LineTagToCharIndex (start, action.pos);
5005                                         document.InsertString (start, action.pos, (string) action.data);
5006                                         document.CharIndexToLineTag (start_index + ((string) action.data).Length,
5007                                                         out document.caret.line, out document.caret.tag,
5008                                                         out document.caret.pos);
5009                                         document.UpdateCaret ();
5010                                         document.SetSelectionToCaret (true);
5011                                         document.ResumeUpdate (true);
5012                                         break;
5013
5014                                 case ActionType.Typing:
5015                                         start = document.GetLine (action.line_no);
5016                                         document.SuspendUpdate ();
5017                                         start_index = document.LineTagToCharIndex (start, action.pos);
5018                                         document.InsertString (start, action.pos, ((StringBuilder) action.data).ToString ());
5019                                         document.CharIndexToLineTag (start_index + ((StringBuilder) action.data).Length,
5020                                                         out document.caret.line, out document.caret.tag,
5021                                                         out document.caret.pos);
5022                                         document.UpdateCaret ();
5023                                         document.SetSelectionToCaret (true);
5024                                         document.ResumeUpdate (true);
5025
5026                                         // This is an open ended operation, so only a single typing operation can be undone at once
5027                                         user_action_finished = true;
5028                                         break;
5029
5030                                 case ActionType.DeleteString:
5031                                         start = document.GetLine (action.line_no);
5032                                         document.SuspendUpdate ();
5033                                         document.DeleteMultiline (start, action.pos, ((Line) action.data).text.Length);
5034                                         document.PositionCaret (start, action.pos);
5035                                         document.SetSelectionToCaret (true);
5036                                         document.ResumeUpdate (true);
5037
5038                                         break;
5039                                 }
5040                         } while (!user_action_finished && redo_actions.Count > 0);
5041
5042                         locked = false;
5043                 }
5044                 #endregion      // Internal Methods
5045
5046                 #region Private Methods
5047
5048                 public void BeginUserAction (string name)
5049                 {
5050                         if (locked)
5051                                 return;
5052
5053                         Action ua = new Action ();
5054                         ua.type = ActionType.UserActionBegin;
5055                         ua.data = name;
5056
5057                         undo_actions.Push (ua);
5058                 }
5059
5060                 public void EndUserAction ()
5061                 {
5062                         if (locked)
5063                                 return;
5064
5065                         Action ua = new Action ();
5066                         ua.type = ActionType.UserActionEnd;
5067
5068                         undo_actions.Push (ua);
5069                 }
5070
5071                 // start_pos, end_pos = 1 based
5072                 public void RecordDeleteString (Line start_line, int start_pos, Line end_line, int end_pos)
5073                 {
5074                         if (locked)
5075                                 return;
5076
5077                         Action  a = new Action ();
5078
5079                         // We cant simply store the string, because then formatting would be lost
5080                         a.type = ActionType.DeleteString;
5081                         a.line_no = start_line.line_no;
5082                         a.pos = start_pos;
5083                         a.data = Duplicate (start_line, start_pos, end_line, end_pos);
5084
5085                         undo_actions.Push(a);
5086                 }
5087
5088                 public void RecordInsertString (Line line, int pos, string str)
5089                 {
5090                         if (locked || str.Length == 0)
5091                                 return;
5092
5093                         Action a = new Action ();
5094
5095                         a.type = ActionType.InsertString;
5096                         a.data = str;
5097                         a.line_no = line.line_no;
5098                         a.pos = pos;
5099
5100                         undo_actions.Push (a);
5101                 }
5102
5103                 public void RecordTyping (Line line, int pos, char ch)
5104                 {
5105                         if (locked)
5106                                 return;
5107
5108                         Action a = null;
5109
5110                         if (undo_actions.Count > 0)
5111                                 a = (Action) undo_actions.Peek ();
5112
5113                         if (a == null || a.type != ActionType.Typing) {
5114                                 a = new Action ();
5115                                 a.type = ActionType.Typing;
5116                                 a.data = new StringBuilder ();
5117                                 a.line_no = line.line_no;
5118                                 a.pos = pos;
5119
5120                                 undo_actions.Push (a);
5121                         }
5122
5123                         StringBuilder data = (StringBuilder) a.data;
5124                         data.Append (ch);
5125                 }
5126
5127                 // start_pos = 1-based
5128                 // end_pos = 1-based
5129                 public Line Duplicate(Line start_line, int start_pos, Line end_line, int end_pos)
5130                 {
5131                         Line    ret;
5132                         Line    line;
5133                         Line    current;
5134                         LineTag tag;
5135                         LineTag current_tag;
5136                         int     start;
5137                         int     end;
5138                         int     tag_start;
5139
5140                         line = new Line (start_line.document, start_line.ending);
5141                         ret = line;
5142
5143                         for (int i = start_line.line_no; i <= end_line.line_no; i++) {
5144                                 current = document.GetLine(i);
5145
5146                                 if (start_line.line_no == i) {
5147                                         start = start_pos;
5148                                 } else {
5149                                         start = 0;
5150                                 }
5151
5152                                 if (end_line.line_no == i) {
5153                                         end = end_pos;
5154                                 } else {
5155                                         end = current.text.Length;
5156                                 }
5157
5158                                 if (end_pos == 0)
5159                                         continue;
5160
5161                                 // Text for the tag
5162                                 line.text = new StringBuilder (current.text.ToString (start, end - start));
5163
5164                                 // Copy tags from start to start+length onto new line
5165                                 current_tag = current.FindTag (start);
5166                                 while ((current_tag != null) && (current_tag.start <= end)) {
5167                                         if ((current_tag.start <= start) && (start < (current_tag.start + current_tag.length))) {
5168                                                 // start tag is within this tag
5169                                                 tag_start = start;
5170                                         } else {
5171                                                 tag_start = current_tag.start;
5172                                         }
5173
5174                                         tag = new LineTag(line, tag_start - start + 1);
5175                                         tag.CopyFormattingFrom (current_tag);
5176
5177                                         current_tag = current_tag.next;
5178
5179                                         // Add the new tag to the line
5180                                         if (line.tags == null) {
5181                                                 line.tags = tag;
5182                                         } else {
5183                                                 LineTag tail;
5184                                                 tail = line.tags;
5185
5186                                                 while (tail.next != null) {
5187                                                         tail = tail.next;
5188                                                 }
5189                                                 tail.next = tag;
5190                                                 tag.previous = tail;
5191                                         }
5192                                 }
5193
5194                                 if ((i + 1) <= end_line.line_no) {
5195                                         line.ending = current.ending;
5196
5197                                         // Chain them (we use right/left as next/previous)
5198                                         line.right = new Line (start_line.document, start_line.ending);
5199                                         line.right.left = line;
5200                                         line = line.right;
5201                                 }
5202                         }
5203
5204                         return ret;
5205                 }
5206
5207                 // Insert multi-line text at the given position; use formatting at insertion point for inserted text
5208                 internal void Insert(Line line, int pos, Line insert, bool select)
5209                 {
5210                         Line    current;
5211                         LineTag tag;
5212                         int     offset;
5213                         int     lines;
5214                         Line    first;
5215
5216                         // Handle special case first
5217                         if (insert.right == null) {
5218
5219                                 // Single line insert
5220                                 document.Split(line, pos);
5221
5222                                 if (insert.tags == null) {
5223                                         return; // Blank line
5224                                 }
5225
5226                                 //Insert our tags at the end
5227                                 tag = line.tags;
5228
5229                                 while (tag.next != null) {
5230                                         tag = tag.next;
5231                                 }
5232
5233                                 offset = tag.start + tag.length - 1;
5234
5235                                 tag.next = insert.tags;
5236                                 line.text.Insert(offset, insert.text.ToString());
5237
5238                                 // Adjust start locations
5239                                 tag = tag.next;
5240                                 while (tag != null) {
5241                                         tag.start += offset;
5242                                         tag.line = line;
5243                                         tag = tag.next;
5244                                 }
5245                                 // Put it back together
5246                                 document.Combine(line.line_no, line.line_no + 1);
5247
5248                                 if (select) {
5249                                         document.SetSelectionStart (line, pos, false);
5250                                         document.SetSelectionEnd (line, pos + insert.text.Length, false);
5251                                 }
5252
5253                                 document.UpdateView(line, pos);
5254                                 return;
5255                         }
5256
5257                         first = line;
5258                         lines = 1;
5259                         current = insert;
5260
5261                         while (current != null) {
5262
5263                                 if (current == insert) {
5264                                         // Inserting the first line we split the line (and make space)
5265                                         document.Split(line.line_no, pos);
5266                                         //Insert our tags at the end of the line
5267                                         tag = line.tags;
5268
5269                                         
5270                                         if (tag != null && tag.length != 0) {
5271                                                 while (tag.next != null) {
5272                                                         tag = tag.next;
5273                                                 }
5274                                                 offset = tag.start + tag.length - 1;
5275                                                 tag.next = current.tags;
5276                                                 tag.next.previous = tag;
5277
5278                                                 tag = tag.next;
5279
5280                                         } else {
5281                                                 offset = 0;
5282                                                 line.tags = current.tags;
5283                                                 line.tags.previous = null;
5284                                                 tag = line.tags;
5285                                         }
5286
5287                                         line.ending = current.ending;
5288                                 } else {
5289                                         document.Split(line.line_no, 0);
5290                                         offset = 0;
5291                                         line.tags = current.tags;
5292                                         line.tags.previous = null;
5293                                         line.ending = current.ending;
5294                                         tag = line.tags;
5295                                 }
5296
5297                                 // Adjust start locations and line pointers
5298                                 while (tag != null) {
5299                                         tag.start += offset - 1;
5300                                         tag.line = line;
5301                                         tag = tag.next;
5302                                 }
5303
5304                                 line.text.Insert(offset, current.text.ToString());
5305                                 line.Grow(line.text.Length);
5306
5307                                 line.recalc = true;
5308                                 line = document.GetLine(line.line_no + 1);
5309
5310                                 // FIXME? Test undo of line-boundaries
5311                                 if ((current.right == null) && (current.tags.length != 0)) {
5312                                         document.Combine(line.line_no - 1, line.line_no);
5313                                 }
5314                                 current = current.right;
5315                                 lines++;
5316
5317                         }
5318
5319                         // Recalculate our document
5320                         document.UpdateView(first, lines, pos);
5321                         return;
5322                 }               
5323                 #endregion      // Private Methods
5324         }
5325 }