2009-09-21 Carlos Alberto Cortez <calberto.cortez@gmail.com>
[mono.git] / mcs / class / Managed.Windows.Forms / System.Windows.Forms / RichTextBox.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) 2005-2006 Novell, Inc. (http://www.novell.com)
21 //
22 // Authors:
23 //      Peter Bartok    <pbartok@novell.com>
24 //
25 //
26
27 // #define DEBUG
28
29 using System;
30 using System.Collections;
31 using System.ComponentModel;
32 using System.Drawing;
33 using System.Drawing.Imaging;
34 using System.IO;
35 using System.Text;
36 using System.Runtime.InteropServices;
37 using RTF=System.Windows.Forms.RTF;
38
39 namespace System.Windows.Forms {
40 #if NET_2_0
41         [ClassInterface (ClassInterfaceType.AutoDispatch)]
42         [Docking (DockingBehavior.Ask)]
43         [ComVisible (true)]
44         [Designer ("System.Windows.Forms.Design.RichTextBoxDesigner, " + Consts.AssemblySystem_Design, "System.ComponentModel.Design.IDesigner")]
45 #endif
46         public class RichTextBox : TextBoxBase {
47                 #region Local Variables
48                 internal bool           auto_word_select;
49                 internal int            bullet_indent;
50                 internal bool           detect_urls;
51                 private bool            reuse_line;     // Sometimes we are loading text with already available lines
52                 internal int            margin_right;
53                 internal float          zoom;
54                 private StringBuilder   rtf_line;
55
56                 private RtfSectionStyle rtf_style;      // Replaces individual style
57                                                         // properties so we can revert
58                 private Stack           rtf_section_stack;
59
60                 private RTF.TextMap rtf_text_map;
61                 private int rtf_skip_count;
62                 private int             rtf_cursor_x;
63                 private int             rtf_cursor_y;
64                 private int             rtf_chars;
65
66 #if NET_2_0
67                 private bool            enable_auto_drag_drop;
68                 private RichTextBoxLanguageOptions language_option;
69                 private bool            rich_text_shortcuts_enabled;
70                 private Color           selection_back_color;
71 #endif
72                 #endregion      // Local Variables
73
74                 #region Public Constructors
75                 public RichTextBox() {
76                         accepts_return = true;
77                         auto_size = false;
78                         auto_word_select = false;
79                         bullet_indent = 0;
80                         base.MaxLength = Int32.MaxValue;
81                         margin_right = 0;
82                         zoom = 1;
83                         base.Multiline = true;
84                         document.CRLFSize = 1;
85                         shortcuts_enabled = true;
86                         base.EnableLinks = true;
87                         richtext = true;
88                         
89                         rtf_style = new RtfSectionStyle ();
90                         rtf_section_stack = null;
91
92                         scrollbars = RichTextBoxScrollBars.Both;
93                         alignment = HorizontalAlignment.Left;
94                         LostFocus += new EventHandler(RichTextBox_LostFocus);
95                         GotFocus += new EventHandler(RichTextBox_GotFocus);
96                         BackColor = ThemeEngine.Current.ColorWindow;
97 #if NET_2_0
98                         backcolor_set = false;
99                         language_option = RichTextBoxLanguageOptions.AutoFontSizeAdjust;
100                         rich_text_shortcuts_enabled = true;
101                         selection_back_color = DefaultBackColor;
102 #endif
103                         ForeColor = ThemeEngine.Current.ColorWindowText;
104
105                         base.HScrolled += new EventHandler(RichTextBox_HScrolled);
106                         base.VScrolled += new EventHandler(RichTextBox_VScrolled);
107
108 #if NET_2_0
109                         SetStyle (ControlStyles.StandardDoubleClick, false);
110 #endif
111                 }
112                 #endregion      // Public Constructors
113
114                 #region Private & Internal Methods
115
116                 internal override void HandleLinkClicked (LinkRectangle link)
117                 {
118                         OnLinkClicked (new LinkClickedEventArgs (link.LinkTag.LinkText));
119                 }
120
121                 internal override Color ChangeBackColor (Color backColor)
122                 {
123                         if (backColor == Color.Empty) {
124 #if NET_2_0
125                                 backcolor_set = false;
126                                 if (!ReadOnly) {
127                                         backColor = SystemColors.Window;
128                                 }
129 #else
130                                 backColor = SystemColors.Window;
131 #endif
132                         }
133                         return backColor;
134                 }
135
136                 internal override void RaiseSelectionChanged()
137                 {
138                         OnSelectionChanged (EventArgs.Empty);
139                 }
140                 
141                 private void RichTextBox_LostFocus(object sender, EventArgs e) {
142                         Invalidate();
143                 }
144
145                 private void RichTextBox_GotFocus(object sender, EventArgs e) {
146                         Invalidate();
147                 }
148                 #endregion      // Private & Internal Methods
149
150                 #region Public Instance Properties
151 #if NET_2_0
152                 [Browsable (false)]
153 #endif
154                 public override bool AllowDrop {
155                         get {
156                                 return base.AllowDrop;
157                         }
158
159                         set {
160                                 base.AllowDrop = value;
161                         }
162                 }
163
164                 [DefaultValue(false)]
165 #if NET_2_0
166                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Visible)]
167                 [RefreshProperties (RefreshProperties.Repaint)]
168                 [EditorBrowsable (EditorBrowsableState.Never)]
169                 [Browsable (false)]
170 #else
171                 [Localizable(true)]
172 #endif
173                 public override bool AutoSize {
174                         get {
175                                 return auto_size;
176                         }
177
178                         set {
179                                 base.AutoSize = value;
180                         }
181                 }
182
183                 [MonoTODO ("Value not respected, always true")]
184                 [DefaultValue(false)]
185                 public bool AutoWordSelection {
186                         get { return auto_word_select; }
187                         set { auto_word_select = value; }
188                 }
189
190                 [Browsable(false)]
191                 [EditorBrowsable(EditorBrowsableState.Never)]
192                 public override System.Drawing.Image BackgroundImage {
193                         get { return base.BackgroundImage; }
194                         set { base.BackgroundImage = value; }
195                 }
196
197 #if NET_2_0
198                 [Browsable (false)]
199                 [EditorBrowsable (EditorBrowsableState.Never)]
200                 public override ImageLayout BackgroundImageLayout {
201                         get { return base.BackgroundImageLayout; }
202                         set { base.BackgroundImageLayout = value; }
203                 }
204 #endif
205
206                 [DefaultValue(0)]
207                 [Localizable(true)]
208                 public int BulletIndent {
209                         get {
210                                 return bullet_indent;
211                         }
212
213                         set {
214                                 bullet_indent = value;
215                         }
216                 }
217
218                 [Browsable(false)]
219                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
220                 public bool CanRedo {
221                         get {
222                                 return document.undo.CanRedo;
223                         }
224                 }
225
226                 [DefaultValue(true)]
227                 public bool DetectUrls {
228                         get { return base.EnableLinks; }
229                         set { base.EnableLinks = value; }
230                 }
231
232 #if NET_2_0
233                 [MonoTODO ("Stub, does nothing")]
234                 [DefaultValue (false)]
235                 public bool EnableAutoDragDrop {
236                         get { return enable_auto_drag_drop; }
237                         set { enable_auto_drag_drop = value; }
238                 }
239 #endif
240
241                 public override Font Font {
242                         get {
243                                 return base.Font;
244                         }
245
246                         set {
247                                 if (font != value) {
248                                         Line    start;
249                                         Line    end;
250
251                                         if (auto_size) {
252                                                 if (PreferredHeight != Height) {
253                                                         Height = PreferredHeight;
254                                                 }
255                                         }
256
257                                         base.Font = value;
258
259                                         // Font changes always set the whole doc to that font
260                                         start = document.GetLine(1);
261                                         end = document.GetLine(document.Lines);
262                                         document.FormatText(start, 1, end, end.text.Length + 1, base.Font, Color.Empty, Color.Empty, FormatSpecified.Font);
263                                 }
264                         }
265                 }
266
267                 public override Color ForeColor {
268                         get {
269                                 return base.ForeColor;
270                         }
271
272                         set {
273                                 base.ForeColor = value;
274                         }
275                 }
276
277 #if NET_2_0
278                 [MonoTODO ("Stub, does nothing")]
279                 [Browsable (false)]
280                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
281                 public RichTextBoxLanguageOptions LanguageOption {
282                         get { return language_option; }
283                         set { language_option = value; }
284                 }
285 #endif
286
287                 [DefaultValue(Int32.MaxValue)]
288                 public override int MaxLength {
289                         get { return base.MaxLength; }
290                         set { base.MaxLength = value; }
291                 }
292
293                 [DefaultValue(true)]
294                 public override bool Multiline {
295                         get {
296                                 return base.Multiline;
297                         }
298
299                         set {
300                                 base.Multiline = value;
301                         }
302                 }
303
304                 [Browsable(false)]
305                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
306                 public string RedoActionName {
307                         get {
308                                 return document.undo.RedoActionName;
309                         }
310                 }
311
312 #if NET_2_0
313                 [MonoTODO ("Stub, does nothing")]
314                 [Browsable (false)]
315                 [DefaultValue (true)]
316                 [EditorBrowsable (EditorBrowsableState.Never)]
317                 public bool RichTextShortcutsEnabled {
318                         get { return rich_text_shortcuts_enabled; }
319                         set { rich_text_shortcuts_enabled = value; }
320                 }
321 #endif
322
323                 [DefaultValue(0)]
324                 [Localizable(true)]
325                 [MonoTODO ("Stub, does nothing")]
326                 [MonoInternalNote ("Teach TextControl.RecalculateLine to consider the right margin as well")]
327                 public int RightMargin {
328                         get {
329                                 return margin_right;
330                         }
331
332                         set {
333                                 margin_right = value;
334                         }
335                 }
336
337                 [Browsable(false)]
338                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
339 #if NET_2_0
340                 [RefreshProperties (RefreshProperties.All)]
341 #else
342                 [DefaultValue("")]
343 #endif
344                 public string Rtf {
345                         get {
346                                 Line            start_line;
347                                 Line            end_line;
348
349                                 start_line = document.GetLine(1);
350                                 end_line = document.GetLine(document.Lines);
351                                 return GenerateRTF(start_line, 0, end_line, end_line.text.Length).ToString();
352                         }
353
354                         set {
355                                 MemoryStream    data;
356
357                                 document.Empty();
358                                 data = new MemoryStream(Encoding.ASCII.GetBytes(value), false);
359
360                                 InsertRTFFromStream(data, 0, 1);
361
362                                 data.Close();
363
364                                 Invalidate();
365                         }
366                 }
367
368                 [DefaultValue(RichTextBoxScrollBars.Both)]
369                 [Localizable(true)]
370                 public RichTextBoxScrollBars ScrollBars {
371                         get {
372                                 return scrollbars;
373                         }
374
375                         set {
376                                 if (!Enum.IsDefined (typeof (RichTextBoxScrollBars), value))
377                                         throw new InvalidEnumArgumentException ("value", (int) value,
378                                                 typeof (RichTextBoxScrollBars));
379
380                                 if (value != scrollbars) {
381                                         scrollbars = value;
382                                         CalculateDocument ();
383                                 }
384                         }
385                 }
386
387                 [Browsable(false)]
388                 [DefaultValue("")]
389                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
390                 public string SelectedRtf {
391                         get {
392                                 return GenerateRTF(document.selection_start.line, document.selection_start.pos, document.selection_end.line, document.selection_end.pos).ToString();
393                         }
394
395                         set {                           
396                                 MemoryStream    data;
397                                 int             x;
398                                 int             y;
399                                 int             sel_start;
400                                 int             chars;
401                                 Line            line;
402                                 LineTag         tag;
403
404                                 if (document.selection_visible) {
405                                         document.ReplaceSelection("", false);
406                                 }
407
408                                 sel_start = document.LineTagToCharIndex(document.selection_start.line, document.selection_start.pos);
409
410                                 data = new MemoryStream(Encoding.ASCII.GetBytes(value), false);
411                                 int cursor_x = document.selection_start.pos;
412                                 int cursor_y = document.selection_start.line.line_no;
413
414                                 // The RFT parser by default, when finds our x cursor in 0, it thinks if needs to
415                                 // add a new line; but in *this* scenario the line is already created, so force it to reuse it.
416                                 // Hackish, but works without touching the heart of the buggy parser.
417                                 if (cursor_x == 0)
418                                         reuse_line = true;
419
420                                 InsertRTFFromStream(data, cursor_x, cursor_y, out x, out y, out chars);
421                                 data.Close();
422
423                                 int nl_length = document.LineEndingLength (XplatUI.RunningOnUnix ? LineEnding.Rich : LineEnding.Hard);
424                                 document.CharIndexToLineTag(sel_start + chars + (y - document.selection_start.line.line_no) * nl_length, 
425                                                 out line, out tag, out sel_start);
426                                 if (sel_start >= line.text.Length)
427                                         sel_start = line.text.Length -1;
428
429                                 document.SetSelection(line, sel_start);
430                                 document.PositionCaret(line, sel_start);
431                                 document.DisplayCaret();
432                                 ScrollToCaret();
433                                 OnTextChanged(EventArgs.Empty);
434                         }
435                 }
436
437                 [Browsable(false)]
438                 [DefaultValue("")]
439                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
440                 public override string SelectedText {
441                         get {
442                                 return base.SelectedText;
443                         }
444
445                         set {
446                                 base.SelectedText = value;
447                         }
448                 }
449
450                 [Browsable(false)]
451                 [DefaultValue(HorizontalAlignment.Left)]
452                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
453                 public HorizontalAlignment SelectionAlignment {
454                         get {
455                                 HorizontalAlignment     align;
456                                 Line                    start;
457                                 Line                    end;
458                                 Line                    line;
459
460                                 start = document.ParagraphStart(document.selection_start.line);
461                                 align = start.alignment;
462
463                                 end = document.ParagraphEnd(document.selection_end.line);
464
465                                 line = start;
466
467                                 while (true) {
468                                         if (line.alignment != align) {
469                                                 return HorizontalAlignment.Left;
470                                         }
471
472                                         if (line == end) {
473                                                 break;
474                                         }
475                                         line = document.GetLine(line.line_no + 1);
476                                 }
477
478                                 return align;
479                         }
480
481                         set {
482                                 Line                    start;
483                                 Line                    end;
484                                 Line                    line;
485
486                                 start = document.ParagraphStart(document.selection_start.line);
487
488                                 end = document.ParagraphEnd(document.selection_end.line);
489
490                                 line = start;
491
492                                 while (true) {
493                                         line.alignment = value;
494
495                                         if (line == end) {
496                                                 break;
497                                         }
498                                         line = document.GetLine(line.line_no + 1);
499                                 }
500                                 this.CalculateDocument();
501                         }
502                 }
503
504 #if NET_2_0
505                 [MonoTODO ("Stub, does nothing")]
506                 [Browsable (false)]
507                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
508                 public Color SelectionBackColor {
509                         get { return selection_back_color; }
510                         set { selection_back_color = value; }
511                 }
512 #endif
513
514                 [Browsable(false)]
515                 [DefaultValue(false)]
516                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
517                 [MonoTODO ("Stub, does nothing")]
518                 public bool SelectionBullet {
519                         get {
520                                 return false;
521                         }
522
523                         set {
524                         }
525                 }
526
527                 [Browsable(false)]
528                 [DefaultValue(0)]
529                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
530                 [MonoTODO ("Stub, does nothing")]
531                 public int SelectionCharOffset {
532                         get {
533                                 return 0;
534                         }
535
536                         set {
537                         }
538                 }
539
540                 [Browsable(false)]
541                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
542                 public Color SelectionColor {
543                         get {
544                                 Color   color;
545                                 LineTag start;
546                                 LineTag end;
547                                 LineTag tag;
548
549                                 if (selection_length > 0) {
550                                         start = document.selection_start.line.FindTag (document.selection_start.pos + 1);
551                                         end = document.selection_start.line.FindTag (document.selection_end.pos);
552                                 } else {
553                                         start = document.selection_start.line.FindTag (document.selection_start.pos);
554                                         end = start;
555                                 }
556
557                                 color = start.Color;
558
559                                 tag = start;
560                                 while (tag != null) {
561
562                                         if (!color.Equals (tag.Color))
563                                                 return Color.Empty;
564
565                                         if (tag == end)
566                                                 break;
567
568                                         tag = document.NextTag (tag);
569                                 }
570
571                                 return color;
572                         }
573
574                         set {
575                                 if (value == Color.Empty)
576                                         value = DefaultForeColor;
577                                         
578                                 int sel_start;
579                                 int sel_end;
580
581                                 sel_start = document.LineTagToCharIndex(document.selection_start.line, document.selection_start.pos);
582                                 sel_end = document.LineTagToCharIndex(document.selection_end.line, document.selection_end.pos);
583
584                                 document.FormatText (document.selection_start.line, document.selection_start.pos + 1,
585                                                 document.selection_end.line, document.selection_end.pos + 1, null,
586                                                 value, Color.Empty, FormatSpecified.Color);
587
588                                 document.CharIndexToLineTag(sel_start, out document.selection_start.line, out document.selection_start.tag, out document.selection_start.pos);
589                                 document.CharIndexToLineTag(sel_end, out document.selection_end.line, out document.selection_end.tag, out document.selection_end.pos);
590
591                                 document.UpdateView(document.selection_start.line, 0);
592
593                                 //Re-Align the caret in case its changed size or position
594                                 //probably not necessary here
595                                 document.AlignCaret(false);
596                         }
597                 }
598
599                 [Browsable(false)]
600                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
601                 public Font SelectionFont {
602                         get {
603                                 Font    font;
604                                 LineTag start;
605                                 LineTag end;
606                                 LineTag tag;
607
608                                 if (selection_length > 0) {
609                                         start = document.selection_start.line.FindTag (document.selection_start.pos + 1);
610                                         end = document.selection_start.line.FindTag (document.selection_end.pos);
611                                 } else {
612                                         start = document.selection_start.line.FindTag (document.selection_start.pos);
613                                         end = start;
614                                 }
615
616                                 font = start.Font;
617
618                                 if (selection_length > 1) {
619                                         tag = start;
620                                         while (tag != null) {
621
622                                                 if (!font.Equals(tag.Font))
623                                                         return null;
624
625                                                 if (tag == end)
626                                                         break;
627
628                                                 tag = document.NextTag (tag);
629                                         }
630                                 }
631
632                                 return font;
633                         }
634
635                         set {
636                                 int             sel_start;
637                                 int             sel_end;
638
639                                 sel_start = document.LineTagToCharIndex(document.selection_start.line, document.selection_start.pos);
640                                 sel_end = document.LineTagToCharIndex(document.selection_end.line, document.selection_end.pos);
641
642                                 document.FormatText (document.selection_start.line, document.selection_start.pos + 1,
643                                                 document.selection_end.line, document.selection_end.pos + 1, value,
644                                                 Color.Empty, Color.Empty, FormatSpecified.Font);
645
646                                 document.CharIndexToLineTag(sel_start, out document.selection_start.line, out document.selection_start.tag, out document.selection_start.pos);
647                                 document.CharIndexToLineTag(sel_end, out document.selection_end.line, out document.selection_end.tag, out document.selection_end.pos);
648
649                                 document.UpdateView(document.selection_start.line, 0);
650                                 //Re-Align the caret in case its changed size or position
651                                 Document.AlignCaret (false);
652
653                         }
654                 }
655
656                 [Browsable(false)]
657                 [DefaultValue(0)]
658                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
659                 [MonoTODO ("Stub, does nothing")]
660                 public int SelectionHangingIndent {
661                         get {
662                                 return 0;
663                         }
664
665                         set {
666                         }
667                 }
668
669                 [Browsable(false)]
670                 [DefaultValue(0)]
671                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
672                 [MonoTODO ("Stub, does nothing")]
673                 public int SelectionIndent {
674                         get {
675                                 return 0;
676                         }
677
678                         set {
679                         }
680                 }
681
682                 [Browsable(false)]
683                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
684                 public override int SelectionLength {
685                         get {
686                                 return base.SelectionLength;
687                         }
688
689                         set {
690                                 base.SelectionLength = value;
691                         }
692                 }
693
694                 [Browsable(false)]
695                 [DefaultValue(false)]
696                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
697                 [MonoTODO ("Stub, does nothing")]
698                 public bool SelectionProtected {
699                         get {
700                                 return false;
701                         }
702
703                         set {
704                         }
705                 }
706
707                 [Browsable(false)]
708                 [DefaultValue(0)]
709                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
710                 [MonoTODO ("Stub, does nothing")]
711                 public int SelectionRightIndent {
712                         get {
713                                 return 0;
714                         }
715
716                         set {
717                         }
718                 }
719
720                 [Browsable(false)]
721                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
722                 [MonoTODO ("Stub, does nothing")]
723                 public int[] SelectionTabs {
724                         get {
725                                 return new int[0];
726                         }
727
728                         set {
729                         }
730                 }
731
732                 [Browsable(false)]
733                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
734                 public RichTextBoxSelectionTypes SelectionType {
735                         get {
736                                 if (document.selection_start == document.selection_end) {
737                                         return RichTextBoxSelectionTypes.Empty;
738                                 }
739
740                                 // Lazy, but works
741                                 if (SelectedText.Length > 1) {
742                                         return RichTextBoxSelectionTypes.MultiChar | RichTextBoxSelectionTypes.Text;
743                                 }
744
745                                 return RichTextBoxSelectionTypes.Text;
746                         }
747                 }
748
749                 [DefaultValue(false)]
750                 [MonoTODO ("Stub, does nothing")]
751                 public bool ShowSelectionMargin {
752                         get {
753                                 return false;
754                         }
755
756                         set {
757                         }
758                 }
759
760                 [Localizable(true)]
761 #if NET_2_0
762                 [RefreshProperties (RefreshProperties.All)]
763 #endif
764                 public override string Text {
765                         get {
766                                 return base.Text;
767                         }
768
769                         set {
770                                 base.Text = value;
771                         }
772                 }
773
774                 [Browsable(false)]
775                 public override int TextLength {
776                         get {
777                                 return base.TextLength;
778                         }
779                 }
780
781                 [Browsable(false)]
782                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
783                 public string UndoActionName {
784                         get {
785                                 return document.undo.UndoActionName;
786                         }
787                 }
788
789                 [Localizable(true)]
790                 [DefaultValue(1)]
791                 public float ZoomFactor {
792                         get {
793                                 return zoom;
794                         }
795
796                         set {
797                                 zoom = value;
798                         }
799                 }
800                 #endregion      // Public Instance Properties
801
802                 #region Protected Instance Properties
803                 protected override CreateParams CreateParams {
804                         get {
805                                 return base.CreateParams;
806                         }
807                 }
808
809                 protected override Size DefaultSize {
810                         get {
811                                 return new Size(100, 96);
812                         }
813                 }
814                 #endregion      // Protected Instance Properties
815
816                 #region Public Instance Methods
817                 public bool CanPaste(DataFormats.Format clipFormat) {
818                         if ((clipFormat.Name == DataFormats.Rtf) ||
819                                 (clipFormat.Name == DataFormats.Text) ||
820                                 (clipFormat.Name == DataFormats.UnicodeText)) {
821                                         return true;
822                         }
823                         return false;
824                 }
825
826                 public int Find(char[] characterSet) {
827                         return Find(characterSet, -1, -1);
828                 }
829
830                 public int Find(char[] characterSet, int start) {
831                         return Find(characterSet, start, -1);
832                 }
833
834                 public int Find(char[] characterSet, int start, int end) {
835                         Document.Marker start_mark;
836                         Document.Marker end_mark;
837                         Document.Marker result;
838
839                         if (start == -1) {
840                                 document.GetMarker(out start_mark, true);
841                         } else {
842                                 Line line;
843                                 LineTag tag;
844                                 int pos;
845
846                                 start_mark = new Document.Marker();
847
848                                 document.CharIndexToLineTag(start, out line, out tag, out pos);
849                                 start_mark.line = line;
850                                 start_mark.tag = tag;
851                                 start_mark.pos = pos;
852                         }
853
854                         if (end == -1) {
855                                 document.GetMarker(out end_mark, false);
856                         } else {
857                                 Line line;
858                                 LineTag tag;
859                                 int pos;
860
861                                 end_mark = new Document.Marker();
862
863                                 document.CharIndexToLineTag(end, out line, out tag, out pos);
864                                 end_mark.line = line;
865                                 end_mark.tag = tag;
866                                 end_mark.pos = pos;
867                         }
868
869                         if (document.FindChars(characterSet, start_mark, end_mark, out result)) {
870                                 return document.LineTagToCharIndex(result.line, result.pos);
871                         }
872
873                         return -1;
874                 }
875
876                 public int Find(string str) {
877                         return Find(str, -1, -1, RichTextBoxFinds.None);
878                 }
879
880                 public int Find(string str, int start, int end, RichTextBoxFinds options) {
881                         Document.Marker start_mark;
882                         Document.Marker end_mark;
883                         Document.Marker result;
884
885                         if (start == -1) {
886                                 document.GetMarker(out start_mark, true);
887                         } else {
888                                 Line line;
889                                 LineTag tag;
890                                 int pos;
891
892                                 start_mark = new Document.Marker();
893
894                                 document.CharIndexToLineTag(start, out line, out tag, out pos);
895
896                                 start_mark.line = line;
897                                 start_mark.tag = tag;
898                                 start_mark.pos = pos;
899                         }
900
901                         if (end == -1) {
902                                 document.GetMarker(out end_mark, false);
903                         } else {
904                                 Line line;
905                                 LineTag tag;
906                                 int pos;
907
908                                 end_mark = new Document.Marker();
909
910                                 document.CharIndexToLineTag(end, out line, out tag, out pos);
911
912                                 end_mark.line = line;
913                                 end_mark.tag = tag;
914                                 end_mark.pos = pos;
915                         }
916
917                         if (document.Find(str, start_mark, end_mark, out result, options)) {
918                                 return document.LineTagToCharIndex(result.line, result.pos);
919                         }
920
921                         return -1;
922                 }
923
924                 public int Find(string str, int start, RichTextBoxFinds options) {
925                         return Find(str, start, -1, options);
926                 }
927
928                 public int Find(string str, RichTextBoxFinds options) {
929                         return Find(str, -1, -1, options);
930                 }
931
932                 
933 #if !NET_2_0
934                 public char GetCharFromPosition(Point pt) {
935                         LineTag tag;
936                         int     pos;
937
938                         PointToTagPos(pt, out tag, out pos);
939
940                         if (pos >= tag.Line.text.Length) {
941                                 return '\n';
942                         }
943
944                         return tag.Line.text[pos];
945                 }
946 #else
947                 internal override char GetCharFromPositionInternal (Point p)
948                 {
949                         LineTag tag;
950                         int pos;
951
952                         PointToTagPos (p, out tag, out pos);
953
954                         if (pos >= tag.Line.text.Length)
955                                 return '\n';
956
957                         return tag.Line.text[pos];
958                 }
959 #endif
960
961                 public
962 #if NET_2_0
963                 override
964 #endif  
965                 int GetCharIndexFromPosition(Point pt) {
966                         LineTag tag;
967                         int     pos;
968
969                         PointToTagPos(pt, out tag, out pos);
970
971                         return document.LineTagToCharIndex(tag.Line, pos);
972                 }
973
974                 public
975 #if NET_2_0
976                 override
977 #endif
978                 int GetLineFromCharIndex(int index) {
979                         Line    line;
980                         LineTag tag;
981                         int     pos;
982
983                         document.CharIndexToLineTag(index, out line, out tag, out pos);
984
985                         return line.LineNo - 1;
986                 }
987
988                 public
989 #if NET_2_0
990                 override
991 #endif
992                 Point GetPositionFromCharIndex(int index) {
993                         Line    line;
994                         LineTag tag;
995                         int     pos;
996
997                         document.CharIndexToLineTag(index, out line, out tag, out pos);
998                         return new Point(line.X + (int)line.widths[pos] + document.OffsetX - document.ViewPortX, 
999                                          line.Y + document.OffsetY - document.ViewPortY);
1000                 }
1001
1002                 public void LoadFile(System.IO.Stream data, RichTextBoxStreamType fileType) {
1003                         document.Empty();
1004
1005                         
1006                         // FIXME - ignoring unicode
1007                         if (fileType == RichTextBoxStreamType.PlainText) {
1008                                 StringBuilder sb;
1009                                 char[] buffer;
1010
1011                                 try {
1012                                         sb = new StringBuilder ((int) data.Length);
1013                                         buffer = new char [1024];
1014                                 } catch {
1015                                         throw new IOException("Not enough memory to load document");
1016                                 }
1017
1018                                 StreamReader sr = new StreamReader (data, Encoding.Default, true);
1019                                 int charsRead = sr.Read (buffer, 0, buffer.Length);
1020                                 while (charsRead > 0) {
1021                                         sb.Append (buffer, 0, charsRead);
1022                                         charsRead = sr.Read (buffer, 0, buffer.Length);
1023                                 }
1024
1025                                 // Remove the EOF converted to an extra EOL by the StreamReader
1026                                 if (sb.Length > 0 && sb [sb.Length - 1] == '\n')
1027                                         sb.Remove (sb.Length - 1, 1);
1028
1029                                 base.Text = sb.ToString();
1030                                 return;
1031                         }
1032
1033                         InsertRTFFromStream(data, 0, 1);
1034
1035                         document.PositionCaret (document.GetLine (1), 0);
1036                         document.SetSelectionToCaret (true);
1037                         ScrollToCaret ();
1038                 }
1039
1040                 public void LoadFile(string path) {
1041                         LoadFile (path, RichTextBoxStreamType.RichText);
1042                 }
1043
1044                 public void LoadFile(string path, RichTextBoxStreamType fileType) {
1045                         FileStream      data;
1046
1047                         data = null;
1048
1049
1050                         try {
1051                                 data = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 1024);
1052
1053                                 LoadFile(data, fileType);
1054                         }
1055 #if !DEBUG
1056                         catch (Exception ex) {
1057                                 throw new IOException("Could not open file " + path, ex);
1058                         }
1059 #endif
1060                         finally {
1061                                 if (data != null) {
1062                                         data.Close();
1063                                 }
1064                         }
1065                 }
1066
1067                 public void Paste(DataFormats.Format clipFormat) {
1068                         base.Paste(Clipboard.GetDataObject(), clipFormat, false);
1069                 }
1070
1071                 public void Redo()
1072                 {
1073                         if (document.undo.Redo ())
1074                                 OnTextChanged (EventArgs.Empty);
1075                 }
1076
1077                 public void SaveFile(Stream data, RichTextBoxStreamType fileType) {
1078                         Encoding        encoding;
1079                         int             i;
1080                         Byte[]          bytes;
1081
1082
1083                         if (fileType == RichTextBoxStreamType.UnicodePlainText) {
1084                                 encoding = Encoding.Unicode;
1085                         } else {
1086                                 encoding = Encoding.ASCII;
1087                         }
1088
1089                         switch(fileType) {
1090                                 case RichTextBoxStreamType.PlainText: 
1091                                 case RichTextBoxStreamType.TextTextOleObjs: 
1092                                 case RichTextBoxStreamType.UnicodePlainText: {
1093                                         if (!Multiline) {
1094                                                 bytes = encoding.GetBytes(document.Root.text.ToString());
1095                                                 data.Write(bytes, 0, bytes.Length);
1096                                                 return;
1097                                         }
1098
1099                                         for (i = 1; i < document.Lines; i++) {
1100                                                 // Normalize the new lines to the system ones
1101                                                 string line_text = document.GetLine (i).TextWithoutEnding () + Environment.NewLine;
1102                                                 bytes = encoding.GetBytes(line_text);
1103                                                 data.Write(bytes, 0, bytes.Length);
1104                                         }
1105                                         bytes = encoding.GetBytes(document.GetLine(document.Lines).text.ToString());
1106                                         data.Write(bytes, 0, bytes.Length);
1107                                         return;
1108                                 }
1109                         }
1110
1111                         // If we're here we're saving RTF
1112                         Line            start_line;
1113                         Line            end_line;
1114                         StringBuilder   rtf;
1115                         int             current;
1116                         int             total;
1117
1118                         start_line = document.GetLine(1);
1119                         end_line = document.GetLine(document.Lines);
1120                         rtf = GenerateRTF(start_line, 0, end_line, end_line.text.Length);
1121                         total = rtf.Length;
1122                         bytes = new Byte[4096];
1123
1124                         // Let's chunk it so we don't use up all memory...
1125                         for (i = 0; i < total; i += 1024) {
1126                                 if ((i + 1024) < total) {
1127                                         current = encoding.GetBytes(rtf.ToString(i, 1024), 0, 1024, bytes, 0);
1128                                 } else {
1129                                         current = total - i;
1130                                         current = encoding.GetBytes(rtf.ToString(i, current), 0, current, bytes, 0);
1131                                 }
1132                                 data.Write(bytes, 0, current);
1133                         }
1134                 }
1135
1136                 public void SaveFile(string path) {
1137                         if (path.EndsWith(".rtf")) {
1138                                 SaveFile(path, RichTextBoxStreamType.RichText);
1139                         } else {
1140                                 SaveFile(path, RichTextBoxStreamType.PlainText);
1141                         }
1142                 }
1143
1144                 public void SaveFile(string path, RichTextBoxStreamType fileType) {
1145                         FileStream      data;
1146
1147                         data = null;
1148
1149 //                      try {
1150                                 data = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None, 1024, false);
1151                                 SaveFile(data, fileType);
1152 //                      }
1153
1154 //                      catch {
1155 //                              throw new IOException("Could not write document to file " + path);
1156 //                      }
1157
1158 //                      finally {
1159                                 if (data != null) {
1160                                         data.Close();
1161                                 }
1162 //                      }
1163                 }
1164
1165 #if NET_2_0
1166                 [EditorBrowsable (EditorBrowsableState.Never)]
1167                 public new void DrawToBitmap (Bitmap bitmap, Rectangle targetBounds)
1168                 {
1169                         Graphics dc = Graphics.FromImage (bitmap);
1170
1171                         Draw (dc, targetBounds);
1172                 }
1173 #endif
1174
1175                 #endregion      // Public Instance Methods
1176
1177                 #region Protected Instance Methods
1178                 protected virtual object CreateRichEditOleCallback() {
1179                         throw new NotImplementedException();
1180                 }
1181
1182                 protected override void OnBackColorChanged(EventArgs e) {
1183                         base.OnBackColorChanged (e);
1184                 }
1185
1186                 protected virtual void OnContentsResized(ContentsResizedEventArgs e) {
1187                         ContentsResizedEventHandler eh = (ContentsResizedEventHandler)(Events [ContentsResizedEvent]);
1188                         if (eh != null)
1189                                 eh (this, e);
1190                 }
1191
1192                 protected override void OnContextMenuChanged(EventArgs e) {
1193                         base.OnContextMenuChanged (e);
1194                 }
1195
1196                 protected override void OnHandleCreated(EventArgs e) {
1197                         base.OnHandleCreated (e);
1198                 }
1199
1200                 protected override void OnHandleDestroyed(EventArgs e) {
1201                         base.OnHandleDestroyed (e);
1202                 }
1203
1204                 protected virtual void OnHScroll(EventArgs e) {
1205                         EventHandler eh = (EventHandler)(Events [HScrollEvent]);
1206                         if (eh != null)
1207                                 eh (this, e);
1208                 }
1209
1210                 [MonoTODO ("Stub, never called")]
1211                 protected virtual void OnImeChange(EventArgs e) {
1212                         EventHandler eh = (EventHandler)(Events [ImeChangeEvent]);
1213                         if (eh != null)
1214                                 eh (this, e);
1215                 }
1216
1217                 protected virtual void OnLinkClicked(LinkClickedEventArgs e) {
1218                         LinkClickedEventHandler eh = (LinkClickedEventHandler)(Events [LinkClickedEvent]);
1219                         if (eh != null)
1220                                 eh (this, e);
1221                 }
1222
1223                 protected virtual void OnProtected(EventArgs e) {
1224                         EventHandler eh = (EventHandler)(Events [ProtectedEvent]);
1225                         if (eh != null)
1226                                 eh (this, e);
1227                 }
1228
1229                 protected override void OnRightToLeftChanged(EventArgs e) {
1230                         base.OnRightToLeftChanged (e);
1231                 }
1232
1233                 protected virtual void OnSelectionChanged(EventArgs e) {
1234                         EventHandler eh = (EventHandler)(Events [SelectionChangedEvent]);
1235                         if (eh != null)
1236                                 eh (this, e);
1237                 }
1238
1239 #if !NET_2_0
1240                 protected override void OnSystemColorsChanged(EventArgs e) {
1241                         base.OnSystemColorsChanged (e);
1242                 }
1243
1244                 protected override void OnTextChanged(EventArgs e) {
1245                         base.OnTextChanged (e);
1246                 }
1247 #endif
1248
1249                 protected virtual void OnVScroll(EventArgs e) {
1250                         EventHandler eh = (EventHandler)(Events [VScrollEvent]);
1251                         if (eh != null)
1252                                 eh (this, e);
1253                 }
1254
1255                 protected override void WndProc(ref Message m) {
1256                         base.WndProc (ref m);
1257                 }
1258
1259 #if NET_2_0
1260                 protected override bool ProcessCmdKey (ref Message m, Keys keyData)
1261                 {
1262                         return base.ProcessCmdKey (ref m, keyData);
1263                 }
1264 #endif
1265                 #endregion      // Protected Instance Methods
1266
1267                 #region Events
1268                 static object ContentsResizedEvent = new object ();
1269                 static object HScrollEvent = new object ();
1270                 static object ImeChangeEvent = new object ();
1271                 static object LinkClickedEvent = new object ();
1272                 static object ProtectedEvent = new object ();
1273                 static object SelectionChangedEvent = new object ();
1274                 static object VScrollEvent = new object ();
1275
1276                 [Browsable(false)]
1277                 [EditorBrowsable(EditorBrowsableState.Never)]
1278                 public new event EventHandler BackgroundImageChanged {
1279                         add { base.BackgroundImageChanged += value; }
1280                         remove { base.BackgroundImageChanged -= value; }
1281                 }
1282
1283 #if NET_2_0
1284                 [Browsable (false)]
1285                 [EditorBrowsable (EditorBrowsableState.Never)]
1286                 public new event EventHandler BackgroundImageLayoutChanged {
1287                         add { base.BackgroundImageLayoutChanged += value; }
1288                         remove { base.BackgroundImageLayoutChanged -= value; }
1289                 }
1290 #endif
1291
1292                 public event ContentsResizedEventHandler ContentsResized {
1293                         add { Events.AddHandler (ContentsResizedEvent, value); }
1294                         remove { Events.RemoveHandler (ContentsResizedEvent, value); }
1295                 }
1296
1297 #if !NET_2_0
1298                 [Browsable(false)]
1299                 [EditorBrowsable(EditorBrowsableState.Never)]
1300                 public new event EventHandler DoubleClick {
1301                         add { base.DoubleClick += value; }
1302                         remove { base.DoubleClick -= value; }
1303                 }
1304 #endif
1305
1306                 [Browsable(false)]
1307 #if !NET_2_0
1308                 [EditorBrowsable(EditorBrowsableState.Never)]
1309 #endif
1310                 public new event DragEventHandler DragDrop {
1311                         add { base.DragDrop += value; }
1312                         remove { base.DragDrop -= value; }
1313                 }
1314
1315                 [Browsable(false)]
1316 #if !NET_2_0
1317                 [EditorBrowsable(EditorBrowsableState.Never)]
1318 #endif
1319                 public new event DragEventHandler DragEnter {
1320                         add { base.DragEnter += value; }
1321                         remove { base.DragEnter -= value; }
1322                 }
1323
1324                 [Browsable(false)]
1325                 [EditorBrowsable(EditorBrowsableState.Never)]
1326                 public new event EventHandler DragLeave {
1327                         add { base.DragLeave += value; }
1328                         remove { base.DragLeave -= value; }
1329                 }
1330
1331
1332                 [Browsable(false)]
1333                 [EditorBrowsable(EditorBrowsableState.Never)]
1334                 public new event DragEventHandler DragOver {
1335                         add { base.DragOver += value; }
1336                         remove { base.DragOver -= value; }
1337                 }
1338
1339
1340                 [Browsable(false)]
1341                 [EditorBrowsable(EditorBrowsableState.Never)]
1342                 public new event GiveFeedbackEventHandler GiveFeedback {
1343                         add { base.GiveFeedback += value; }
1344                         remove { base.GiveFeedback -= value; }
1345                 }
1346
1347                 public event EventHandler HScroll {
1348                         add { Events.AddHandler (HScrollEvent, value); }
1349                         remove { Events.RemoveHandler (HScrollEvent, value); }
1350                 }
1351
1352                 public event EventHandler ImeChange {
1353                         add { Events.AddHandler (ImeChangeEvent, value); }
1354                         remove { Events.RemoveHandler (ImeChangeEvent, value); }
1355                 }
1356
1357                 public event LinkClickedEventHandler LinkClicked {
1358                         add { Events.AddHandler (LinkClickedEvent, value); }
1359                         remove { Events.RemoveHandler (LinkClickedEvent, value); }
1360                 }
1361
1362                 public event EventHandler Protected {
1363                         add { Events.AddHandler (ProtectedEvent, value); }
1364                         remove { Events.RemoveHandler (ProtectedEvent, value); }
1365                 }
1366
1367                 [Browsable(false)]
1368                 [EditorBrowsable(EditorBrowsableState.Never)]
1369                 public new event QueryContinueDragEventHandler QueryContinueDrag {
1370                         add { base.QueryContinueDrag += value; }
1371                         remove { base.QueryContinueDrag -= value; }
1372                 }
1373
1374                 [MonoTODO ("Event never raised")]
1375                 public event EventHandler SelectionChanged {
1376                         add { Events.AddHandler (SelectionChangedEvent, value); }
1377                         remove { Events.RemoveHandler (SelectionChangedEvent, value); }
1378                 }
1379
1380                 public event EventHandler VScroll {
1381                         add { Events.AddHandler (VScrollEvent, value); }
1382                         remove { Events.RemoveHandler (VScrollEvent, value); }
1383                 }
1384                 #endregion      // Events
1385
1386                 #region Private Methods
1387
1388                 internal override void SelectWord ()
1389                 {
1390                         document.ExpandSelection(CaretSelection.Word, false);
1391                 }
1392
1393                 private class RtfSectionStyle : ICloneable {
1394                         internal Color rtf_color;
1395                         internal RTF.Font rtf_rtffont;
1396                         internal int rtf_rtffont_size;
1397                         internal FontStyle rtf_rtfstyle;
1398                         internal HorizontalAlignment rtf_rtfalign;
1399                         internal int rtf_par_line_left_indent;
1400                         internal bool rtf_visible;
1401                         internal int rtf_skip_width;
1402
1403                         public object Clone ()
1404                         {
1405                                 RtfSectionStyle new_style = new RtfSectionStyle ();
1406
1407                                 new_style.rtf_color = rtf_color;
1408                                 new_style.rtf_par_line_left_indent = rtf_par_line_left_indent;
1409                                 new_style.rtf_rtfalign = rtf_rtfalign;
1410                                 new_style.rtf_rtffont = rtf_rtffont;
1411                                 new_style.rtf_rtffont_size = rtf_rtffont_size;
1412                                 new_style.rtf_rtfstyle = rtf_rtfstyle;
1413                                 new_style.rtf_visible = rtf_visible;
1414                                 new_style.rtf_skip_width = rtf_skip_width;
1415
1416                                 return new_style;
1417                         }
1418                 }
1419
1420                 // To allow us to keep track of the sections and revert formatting
1421                 // as we go in and out of sections of the document.
1422                 private void HandleGroup (RTF.RTF rtf)
1423                 {
1424                         //start group - save the current formatting on to a stack
1425                         //end group - go back to the formatting at the current group
1426                         if (rtf_section_stack == null) {
1427                                 rtf_section_stack = new Stack ();
1428                         }
1429
1430                         if (rtf.Major == RTF.Major.BeginGroup) {
1431                                 rtf_section_stack.Push (rtf_style.Clone ());
1432                                 //spec specifies resetting unicode ignore at begin group as an attempt at error
1433                                 //recovery.
1434                                 rtf_skip_count = 0;
1435                         } else if (rtf.Major == RTF.Major.EndGroup) {
1436                                 if (rtf_section_stack.Count > 0) {
1437                                         FlushText (rtf, false);
1438
1439                                         rtf_style = (RtfSectionStyle) rtf_section_stack.Pop ();
1440                                 }
1441                         }
1442                 }
1443
1444                 [MonoInternalNote ("Add QuadJust support for justified alignment")]
1445                 private void HandleControl(RTF.RTF rtf) {
1446                         switch(rtf.Major) {
1447                                 case RTF.Major.Unicode: {
1448                                         switch(rtf.Minor) {
1449                                                 case RTF.Minor.UnicodeCharBytes: {
1450                                                         rtf_style.rtf_skip_width = rtf.Param;
1451                                                         break;
1452                                                 }
1453
1454                                                 case RTF.Minor.UnicodeChar: {
1455                                                         FlushText (rtf, false);
1456                                                         rtf_skip_count += rtf_style.rtf_skip_width;
1457                                                         rtf_line.Append((char)rtf.Param);
1458                                                         break;
1459                                                 }
1460                                         }
1461                                         break;
1462                                 }
1463
1464                                 case RTF.Major.Destination: {
1465 //                                      Console.Write("[Got Destination control {0}]", rtf.Minor);
1466                                         rtf.SkipGroup();
1467                                         break;
1468                                 }
1469
1470                                 case RTF.Major.PictAttr:
1471                                         if (rtf.Picture != null && rtf.Picture.IsValid ()) {
1472                                                 Line line = document.GetLine (rtf_cursor_y);
1473                                                 document.InsertPicture (line, 0, rtf.Picture);
1474                                                 rtf_cursor_x++;
1475
1476                                                 FlushText (rtf, true);
1477                                                 rtf.Picture = null;
1478                                         }
1479                                         break;
1480
1481                                 case RTF.Major.CharAttr: {
1482                                         switch(rtf.Minor) {
1483                                                 case RTF.Minor.ForeColor: {
1484                                                         System.Windows.Forms.RTF.Color  color;
1485
1486                                                         color = System.Windows.Forms.RTF.Color.GetColor(rtf, rtf.Param);
1487                                                         
1488                                                         if (color != null) {
1489                                                                 FlushText(rtf, false);
1490                                                                 if (color.Red == -1 && color.Green == -1 && color.Blue == -1) {
1491                                                                         this.rtf_style.rtf_color = ForeColor;
1492                                                                 } else {
1493                                                                         this.rtf_style.rtf_color = Color.FromArgb(color.Red, color.Green, color.Blue);
1494                                                                 }
1495                                                                 FlushText (rtf, false);
1496                                                         }
1497                                                         break;
1498                                                 }
1499
1500                                                 case RTF.Minor.FontSize: {
1501                                                         FlushText(rtf, false);
1502                                                         this.rtf_style.rtf_rtffont_size = rtf.Param / 2;
1503                                                         break;
1504                                                 }
1505
1506                                                 case RTF.Minor.FontNum: {
1507                                                         System.Windows.Forms.RTF.Font   font;
1508
1509                                                         font = System.Windows.Forms.RTF.Font.GetFont(rtf, rtf.Param);
1510                                                         if (font != null) {
1511                                                                 FlushText(rtf, false);
1512                                                                 this.rtf_style.rtf_rtffont = font;
1513                                                         }
1514                                                         break;
1515                                                 }
1516
1517                                                 case RTF.Minor.Plain: {
1518                                                         FlushText(rtf, false);
1519                                                         rtf_style.rtf_rtfstyle = FontStyle.Regular;
1520                                                         break;
1521                                                 }
1522
1523                                                 case RTF.Minor.Bold: {
1524                                                         FlushText(rtf, false);
1525                                                         if (rtf.Param == RTF.RTF.NoParam) {
1526                                                                 rtf_style.rtf_rtfstyle |= FontStyle.Bold;
1527                                                         } else {
1528                                                                 rtf_style.rtf_rtfstyle &= ~FontStyle.Bold;
1529                                                         }
1530                                                         break;
1531                                                 }
1532
1533                                                 case RTF.Minor.Italic: {
1534                                                         FlushText(rtf, false);
1535                                                         if (rtf.Param == RTF.RTF.NoParam) {
1536                                                                 rtf_style.rtf_rtfstyle |= FontStyle.Italic;
1537                                                         } else {
1538                                                                 rtf_style.rtf_rtfstyle &= ~FontStyle.Italic;
1539                                                         }
1540                                                         break;
1541                                                 }
1542
1543                                                 case RTF.Minor.StrikeThru: {
1544                                                         FlushText(rtf, false);
1545                                                         if (rtf.Param == RTF.RTF.NoParam) {
1546                                                                 rtf_style.rtf_rtfstyle |= FontStyle.Strikeout;
1547                                                         } else {
1548                                                                 rtf_style.rtf_rtfstyle &= ~FontStyle.Strikeout;
1549                                                         }
1550                                                         break;
1551                                                 }
1552
1553                                                 case RTF.Minor.Underline: {
1554                                                         FlushText(rtf, false);
1555                                                         if (rtf.Param == RTF.RTF.NoParam) {
1556                                                                 rtf_style.rtf_rtfstyle |= FontStyle.Underline;
1557                                                         } else {
1558                                                                 rtf_style.rtf_rtfstyle = rtf_style.rtf_rtfstyle & ~FontStyle.Underline;
1559                                                         }
1560                                                         break;
1561                                                 }
1562
1563                                                 case RTF.Minor.Invisible: {
1564                                                         FlushText (rtf, false);
1565                                                         rtf_style.rtf_visible = false;
1566                                                         break;
1567                                                 }
1568
1569                                                 case RTF.Minor.NoUnderline: {
1570                                                         FlushText(rtf, false);
1571                                                         rtf_style.rtf_rtfstyle &= ~FontStyle.Underline;
1572                                                         break;
1573                                                 }
1574                                         }
1575                                         break;
1576                                 }
1577
1578                         case RTF.Major.ParAttr: {
1579                                 switch (rtf.Minor) {
1580
1581                                 case RTF.Minor.ParDef:
1582                                         FlushText (rtf, false);
1583                                         rtf_style.rtf_par_line_left_indent = 0;
1584                                         rtf_style.rtf_rtfalign = HorizontalAlignment.Left;
1585                                         break;
1586
1587                                 case RTF.Minor.LeftIndent:
1588                                         rtf_style.rtf_par_line_left_indent = (int) (((float) rtf.Param / 1440.0F) * CreateGraphics ().DpiX + 0.5F);
1589                                         break;
1590
1591                                 case RTF.Minor.QuadCenter:
1592                                         FlushText (rtf, false);
1593                                         rtf_style.rtf_rtfalign = HorizontalAlignment.Center;
1594                                         break;
1595
1596                                 case RTF.Minor.QuadJust:
1597                                         FlushText (rtf, false);
1598                                         rtf_style.rtf_rtfalign = HorizontalAlignment.Center;
1599                                         break;
1600
1601                                 case RTF.Minor.QuadLeft:
1602                                         FlushText (rtf, false);
1603                                         rtf_style.rtf_rtfalign = HorizontalAlignment.Left;
1604                                         break;
1605
1606                                 case RTF.Minor.QuadRight:
1607                                         FlushText (rtf, false);
1608                                         rtf_style.rtf_rtfalign = HorizontalAlignment.Right;
1609                                         break;
1610                                 }
1611                                 break;
1612                         }
1613
1614                         case RTF.Major.SpecialChar: {
1615                                         //Console.Write("[Got SpecialChar control {0}]", rtf.Minor);
1616                                         SpecialChar (rtf);
1617                                         break;
1618                                 }
1619                         }
1620                 }
1621
1622                 private void SpecialChar(RTF.RTF rtf) {
1623                         switch(rtf.Minor) {
1624                                 case RTF.Minor.Page:
1625                                 case RTF.Minor.Sect:
1626                                 case RTF.Minor.Row:
1627                                 case RTF.Minor.Line:
1628                                 case RTF.Minor.Par: {
1629                                         FlushText(rtf, true);
1630                                         break;
1631                                 }
1632
1633                                 case RTF.Minor.Cell: {
1634                                         Console.Write(" ");
1635                                         break;
1636                                 }
1637
1638                                 case RTF.Minor.NoBrkSpace: {
1639                                         Console.Write(" ");
1640                                         break;
1641                                 }
1642
1643                                 case RTF.Minor.Tab: {
1644                                         rtf_line.Append ("\t");
1645 //                                      FlushText (rtf, false);
1646                                         break;
1647                                 }
1648
1649                                 case RTF.Minor.NoReqHyphen:
1650                                 case RTF.Minor.NoBrkHyphen: {
1651                                         rtf_line.Append ("-");
1652 //                                      FlushText (rtf, false);
1653                                         break;
1654                                 }
1655
1656                                 case RTF.Minor.Bullet: {
1657                                         Console.WriteLine("*");
1658                                         break;
1659                                 }
1660
1661                         case RTF.Minor.WidowCtrl:
1662                                 break;
1663
1664                                 case RTF.Minor.EmDash: {
1665                                 rtf_line.Append ("\u2014");
1666                                         break;
1667                                 }
1668
1669                                 case RTF.Minor.EnDash: {
1670                                         rtf_line.Append ("\u2013");
1671                                         break;
1672                                 }
1673 /*
1674                                 case RTF.Minor.LQuote: {
1675                                         Console.Write("\u2018");
1676                                         break;
1677                                 }
1678
1679                                 case RTF.Minor.RQuote: {
1680                                         Console.Write("\u2019");
1681                                         break;
1682                                 }
1683
1684                                 case RTF.Minor.LDblQuote: {
1685                                         Console.Write("\u201C");
1686                                         break;
1687                                 }
1688
1689                                 case RTF.Minor.RDblQuote: {
1690                                         Console.Write("\u201D");
1691                                         break;
1692                                 }
1693 */
1694                                 default: {
1695 //                                      Console.WriteLine ("skipped special char:   {0}", rtf.Minor);
1696 //                                      rtf.SkipGroup();
1697                                         break;
1698                                 }
1699                         }
1700                 }
1701
1702                 private void HandleText(RTF.RTF rtf) {
1703                         string str = rtf.EncodedText;
1704
1705                         //todo - simplistically skips characters, should skip bytes?
1706                         if (rtf_skip_count > 0 && str.Length > 0) {
1707                                 int iToRemove = Math.Min (rtf_skip_count, str.Length);
1708
1709                                 str = str.Substring (iToRemove);
1710                                 rtf_skip_count-=iToRemove;
1711                         }
1712
1713                         /*
1714                         if ((RTF.StandardCharCode)rtf.Minor != RTF.StandardCharCode.nothing) {
1715                                 rtf_line.Append(rtf_text_map[(RTF.StandardCharCode)rtf.Minor]);
1716                         } else {
1717                                 if ((int)rtf.Major > 31 && (int)rtf.Major < 128) {
1718                                         rtf_line.Append((char)rtf.Major);
1719                                 } else {
1720                                         //rtf_line.Append((char)rtf.Major);
1721                                         Console.Write("[Literal:0x{0:X2}]", (int)rtf.Major);
1722                                 }
1723                         }
1724                         */
1725
1726                         if  (rtf_style.rtf_visible)
1727                                 rtf_line.Append (str);
1728                 }
1729
1730                 private void FlushText(RTF.RTF rtf, bool newline) {
1731                         int             length;
1732                         Font            font;
1733
1734                         length = rtf_line.Length;
1735                         if (!newline && (length == 0)) {
1736                                 return;
1737                         }
1738
1739                         if (rtf_style.rtf_rtffont == null) {
1740                                 // First font in table is default
1741                                 rtf_style.rtf_rtffont = System.Windows.Forms.RTF.Font.GetFont (rtf, 0);
1742                         }
1743
1744                         font = new Font (rtf_style.rtf_rtffont.Name, rtf_style.rtf_rtffont_size, rtf_style.rtf_rtfstyle);
1745
1746                         if (rtf_style.rtf_color == Color.Empty) {
1747                                 System.Windows.Forms.RTF.Color color;
1748
1749                                 // First color in table is default
1750                                 color = System.Windows.Forms.RTF.Color.GetColor (rtf, 0);
1751
1752                                 if ((color == null) || (color.Red == -1 && color.Green == -1 && color.Blue == -1)) {
1753                                         rtf_style.rtf_color = ForeColor;
1754                                 } else {
1755                                         rtf_style.rtf_color = Color.FromArgb (color.Red, color.Green, color.Blue);
1756                                 }
1757
1758                         }
1759
1760                         rtf_chars += rtf_line.Length;
1761
1762                         // Try to re-use if we are told so - this usually happens when we are inserting a flow of rtf text
1763                         // with an already alive line.
1764                         if (rtf_cursor_x == 0 && !reuse_line) {
1765                                 if (newline && rtf_line.ToString ().EndsWith (Environment.NewLine) == false)
1766                                         rtf_line.Append (Environment.NewLine);
1767
1768                                 document.Add (rtf_cursor_y, rtf_line.ToString (), rtf_style.rtf_rtfalign, font, rtf_style.rtf_color,
1769                                                                 newline ? LineEnding.Rich : LineEnding.Wrap);
1770                                 if (rtf_style.rtf_par_line_left_indent != 0) {
1771                                         Line line = document.GetLine (rtf_cursor_y);
1772                                         line.indent = rtf_style.rtf_par_line_left_indent;
1773                                 }
1774                         } else {
1775                                 Line line;
1776
1777                                 line = document.GetLine (rtf_cursor_y);
1778                                 line.indent = rtf_style.rtf_par_line_left_indent;
1779                                 if (rtf_line.Length > 0) {
1780                                         document.InsertString (line, rtf_cursor_x, rtf_line.ToString ());
1781                                         document.FormatText (line, rtf_cursor_x + 1, line, rtf_cursor_x + 1 + length,
1782                             font, rtf_style.rtf_color, Color.Empty,
1783                                                         FormatSpecified.Font | FormatSpecified.Color);
1784                                 }
1785                                 if (newline) {
1786                                         line = document.GetLine (rtf_cursor_y);
1787                                         line.ending = LineEnding.Rich;
1788
1789                                         if (line.Text.EndsWith (Environment.NewLine) == false)
1790                                                 line.Text += Environment.NewLine;
1791                                 }
1792
1793                                 reuse_line = false; // sanity assignment - in this case we have already re-used one line.
1794                         }
1795
1796                         if (newline) {
1797                                 rtf_cursor_x = 0;
1798                                 rtf_cursor_y++;
1799                         } else {
1800                                 rtf_cursor_x += length;
1801                         }
1802                         rtf_line.Length = 0;    // Empty line
1803                 }
1804
1805                 private void InsertRTFFromStream(Stream data, int cursor_x, int cursor_y) {
1806                         int     x;
1807                         int     y;
1808                         int     chars;
1809
1810                         InsertRTFFromStream(data, cursor_x, cursor_y, out x, out y, out chars);
1811                 }
1812
1813                 private void InsertRTFFromStream(Stream data, int cursor_x, int cursor_y, out int to_x, out int to_y, out int chars) {
1814                         RTF.RTF         rtf;
1815
1816                         rtf = new RTF.RTF(data);
1817
1818                         // Prepare
1819                         rtf.ClassCallback[RTF.TokenClass.Text] = new RTF.ClassDelegate(HandleText);
1820                         rtf.ClassCallback[RTF.TokenClass.Control] = new RTF.ClassDelegate(HandleControl);
1821                         rtf.ClassCallback[RTF.TokenClass.Group] = new RTF.ClassDelegate(HandleGroup);
1822
1823                         rtf_skip_count = 0;
1824                         rtf_line = new StringBuilder();
1825                         rtf_style.rtf_color = Color.Empty;
1826                         rtf_style.rtf_rtffont_size = (int)this.Font.Size;
1827                         rtf_style.rtf_rtfalign = HorizontalAlignment.Left;
1828                         rtf_style.rtf_rtfstyle = FontStyle.Regular;
1829                         rtf_style.rtf_rtffont = null;
1830                         rtf_style.rtf_visible = true;
1831                         rtf_style.rtf_skip_width = 1;
1832                         rtf_cursor_x = cursor_x;
1833                         rtf_cursor_y = cursor_y;
1834                         rtf_chars = 0;
1835                         rtf.DefaultFont(this.Font.Name);
1836
1837                         rtf_text_map = new RTF.TextMap();
1838                         RTF.TextMap.SetupStandardTable(rtf_text_map.Table);
1839
1840                         document.SuspendRecalc ();
1841
1842                         try {
1843                                 rtf.Read();     // That's it
1844                                 FlushText(rtf, false);
1845
1846                         }
1847
1848
1849                         catch (RTF.RTFException e) {
1850 #if DEBUG
1851                                 throw e;
1852 #endif
1853                                 // Seems to be plain text or broken RTF
1854                                 Console.WriteLine("RTF Parsing failure: {0}", e.Message);
1855                         }                     
1856
1857                         to_x = rtf_cursor_x;
1858                         to_y = rtf_cursor_y;
1859                         chars = rtf_chars;
1860
1861                         // clear the section stack if it was used
1862                         if (rtf_section_stack != null)
1863                                 rtf_section_stack.Clear();
1864
1865                         document.RecalculateDocument(CreateGraphicsInternal(), cursor_y, document.Lines, false);
1866                         document.ResumeRecalc (true);
1867
1868                         document.Invalidate (document.GetLine(cursor_y), 0, document.GetLine(document.Lines), -1);
1869                 }
1870
1871                 private void RichTextBox_HScrolled(object sender, EventArgs e) {
1872                         OnHScroll(e);
1873                 }
1874
1875                 private void RichTextBox_VScrolled(object sender, EventArgs e) {
1876                         OnVScroll(e);
1877                 }
1878
1879                 private void PointToTagPos(Point pt, out LineTag tag, out int pos) {
1880                         Point p;
1881
1882                         p = pt;
1883
1884                         if (p.X >= document.ViewPortWidth) {
1885                                 p.X = document.ViewPortWidth - 1;
1886                         } else if (p.X < 0) {
1887                                 p.X = 0;
1888                         }
1889
1890                         if (p.Y >= document.ViewPortHeight) {
1891                                 p.Y = document.ViewPortHeight - 1;
1892                         } else if (p.Y < 0) {
1893                                 p.Y = 0;
1894                         }
1895
1896                         tag = document.FindCursor(p.X + document.ViewPortX, p.Y + document.ViewPortY, out pos);
1897                 }
1898
1899                 private void EmitRTFFontProperties(StringBuilder rtf, int prev_index, int font_index, Font prev_font, Font font) {
1900                         if (prev_index != font_index) {
1901                                 rtf.Append(String.Format("\\f{0}", font_index));        // Font table entry
1902                         }
1903
1904                         if ((prev_font == null) || (prev_font.Size != font.Size)) {
1905                                 rtf.Append(String.Format("\\fs{0}", (int)(font.Size * 2)));             // Font size
1906                         }
1907
1908                         if ((prev_font == null) || (font.Bold != prev_font.Bold)) {
1909                                 if (font.Bold) {
1910                                         rtf.Append("\\b");
1911                                 } else {
1912                                         if (prev_font != null) {
1913                                                 rtf.Append("\\b0");
1914                                         }
1915                                 }
1916                         }
1917
1918                         if ((prev_font == null) || (font.Italic != prev_font.Italic)) {
1919                                 if (font.Italic) {
1920                                         rtf.Append("\\i");
1921                                 } else {
1922                                         if (prev_font != null) {
1923                                                 rtf.Append("\\i0");
1924                                         }
1925                                 }
1926                         }
1927
1928                         if ((prev_font == null) || (font.Strikeout != prev_font.Strikeout)) {
1929                                 if (font.Strikeout) {
1930                                         rtf.Append("\\strike");
1931                                 } else {
1932                                         if (prev_font != null) {
1933                                                 rtf.Append("\\strike0");
1934                                         }
1935                                 }
1936                         }
1937
1938                         if ((prev_font == null) || (font.Underline != prev_font.Underline)) {
1939                                 if (font.Underline) {
1940                                         rtf.Append("\\ul");
1941                                 } else {
1942                                         if (prev_font != null) {
1943                                                 rtf.Append("\\ul0");
1944                                         }
1945                                 }
1946                         }
1947                 }
1948
1949                 [MonoInternalNote ("Emit unicode and other special characters properly")]
1950                 private void EmitRTFText(StringBuilder rtf, string text) {
1951                         rtf.Append(text);
1952                 }
1953
1954                 // start_pos and end_pos are 0-based
1955                 private StringBuilder GenerateRTF(Line start_line, int start_pos, Line end_line, int end_pos) {
1956                         StringBuilder   sb;
1957                         ArrayList       fonts;
1958                         ArrayList       colors;
1959                         Color           color;
1960                         Font            font;
1961                         Line            line;
1962                         LineTag         tag;
1963                         int             pos;
1964                         int             line_no;
1965                         int             line_len;
1966                         int             i;
1967                         int             length;
1968
1969                         sb = new StringBuilder();
1970                         fonts = new ArrayList(10);
1971                         colors = new ArrayList(10);
1972
1973                         // Two runs, first we parse to determine tables;
1974                         // and unlike most of our processing here we work on tags
1975
1976                         line = start_line;
1977                         line_no = start_line.line_no;
1978                         pos = start_pos;
1979
1980                         // Add default font and color; to optimize document content we don't
1981                         // use this.Font and this.ForeColor but the font/color from the first tag
1982                         tag = LineTag.FindTag(start_line, pos);
1983                         font = tag.Font;
1984                         color = tag.Color;
1985                         fonts.Add(font.Name);
1986                         colors.Add(color);
1987
1988                         while (line_no <= end_line.line_no) {
1989                                 line = document.GetLine(line_no);
1990                                 tag = LineTag.FindTag(line, pos);
1991
1992                                 if (line_no != end_line.line_no) {
1993                                         line_len = line.text.Length;
1994                                 } else {
1995                                         line_len = end_pos;
1996                                 }
1997
1998                                 while (pos < line_len) {
1999                                         if (tag.Font.Name != font.Name) {
2000                                                 font = tag.Font;
2001                                                 if (!fonts.Contains(font.Name)) {
2002                                                         fonts.Add(font.Name);
2003                                                 }
2004                                         }
2005
2006                                         if (tag.Color != color) {
2007                                                 color = tag.Color;
2008                                                 if (!colors.Contains(color)) {
2009                                                         colors.Add(color);
2010                                                 }
2011                                         }
2012
2013                                         pos = tag.Start + tag.Length - 1;
2014                                         tag = tag.Next;
2015                                 }
2016                                 pos = 0;
2017                                 line_no++;
2018                         }
2019
2020                         // We have the tables, emit the header
2021                         sb.Append("{\\rtf1\\ansi");
2022                         sb.Append("\\ansicpg1252");     // FIXME - is this correct?
2023
2024                         // Default Font
2025                         sb.Append(String.Format("\\deff{0}", fonts.IndexOf(this.Font.Name)));
2026
2027                         // Default Language 
2028                         sb.Append("\\deflang1033" + Environment.NewLine);       // FIXME - always 1033?
2029
2030                         // Emit the font table
2031                         sb.Append("{\\fonttbl");
2032                         for (i = 0; i < fonts.Count; i++) {
2033                                 sb.Append(String.Format("{{\\f{0}", i));        // {Font 
2034                                 sb.Append("\\fnil");                    // Family
2035                                 sb.Append("\\fcharset0 ");              // Charset ANSI<space>
2036                                 sb.Append((string)fonts[i]);            // Font name
2037                                 sb.Append(";}");                        // }
2038                         }
2039                         sb.Append("}");
2040                         sb.Append(Environment.NewLine);
2041
2042                         // Emit the color table (if needed)
2043                         if ((colors.Count > 1) || ((((Color)colors[0]).R != this.ForeColor.R) || (((Color)colors[0]).G != this.ForeColor.G) || (((Color)colors[0]).B != this.ForeColor.B))) {
2044                                 sb.Append("{\\colortbl ");                      // Header and NO! default color
2045                                 for (i = 0; i < colors.Count; i++) {
2046                                         sb.Append(String.Format("\\red{0}", ((Color)colors[i]).R));
2047                                         sb.Append(String.Format("\\green{0}", ((Color)colors[i]).G));
2048                                         sb.Append(String.Format("\\blue{0}", ((Color)colors[i]).B));
2049                                         sb.Append(";");
2050                                 }
2051                                 sb.Append("}");
2052                                 sb.Append(Environment.NewLine);
2053                         }
2054
2055                         sb.Append("{\\*\\generator Mono RichTextBox;}");
2056                         // Emit initial paragraph settings
2057                         tag = LineTag.FindTag(start_line, start_pos);
2058                         sb.Append("\\pard");    // Reset to default paragraph properties
2059                         EmitRTFFontProperties(sb, -1, fonts.IndexOf(tag.Font.Name), null, tag.Font);    // Font properties
2060                         sb.Append(" ");         // Space separator
2061
2062                         font = tag.Font;
2063                         color = (Color)colors[0];
2064                         line = start_line;
2065                         line_no = start_line.line_no;
2066                         pos = start_pos;
2067
2068                         while (line_no <= end_line.line_no) {
2069                                 line = document.GetLine(line_no);
2070                                 tag = LineTag.FindTag(line, pos);
2071
2072                                 if (line_no != end_line.line_no) {
2073                                         line_len = line.text.Length;
2074                                 } else {
2075                                         line_len = end_pos;
2076                                 }
2077
2078                                 while (pos < line_len) {
2079                                         length = sb.Length;
2080
2081                                         if (tag.Font != font) {
2082                                                 EmitRTFFontProperties(sb, fonts.IndexOf(font.Name), fonts.IndexOf(tag.Font.Name), font, tag.Font);
2083                                                 font = tag.Font;
2084                                         }
2085
2086                                         if (tag.Color != color) {
2087                                                 color = tag.Color;
2088                                                 sb.Append(String.Format("\\cf{0}", colors.IndexOf(color)));
2089                                         }
2090                                         if (length != sb.Length) {
2091                                                 sb.Append(" "); // Emit space to separate keywords from text
2092                                         }
2093
2094                                         // Emit the string itself
2095                                         if (line_no != end_line.line_no) {
2096                                                 EmitRTFText(sb, tag.Line.text.ToString(pos, tag.Start + tag.Length - pos - 1));
2097                                         } else {
2098                                                 if (end_pos < (tag.Start + tag.Length - 1)) {
2099                                                         // Emit partial tag only, end_pos is inside this tag
2100                                                         EmitRTFText(sb, tag.Line.text.ToString(pos, end_pos - pos));
2101                                                 } else {
2102                                                         EmitRTFText(sb, tag.Line.text.ToString(pos, tag.Start + tag.Length - pos - 1));
2103                                                 }
2104                                         }
2105
2106                                         pos = tag.Start + tag.Length - 1;
2107                                         tag = tag.Next;
2108                                 }
2109                                 if (pos >= line.text.Length) {
2110                                         if (line.ending != LineEnding.Wrap) {
2111                                                 sb.Append("\\par");
2112                                                 sb.Append(Environment.NewLine);
2113                                         }
2114                                 }
2115                                 pos = 0;
2116                                 line_no++;
2117                         }
2118
2119                         sb.Append("}");
2120                         sb.Append(Environment.NewLine);
2121
2122                         return sb;
2123                 }
2124                 #endregion      // Private Methods
2125         }
2126 }