forked from icsharpcode/AvalonEdit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTextEditor.cs
More file actions
1184 lines (1060 loc) · 35.8 KB
/
TextEditor.cs
File metadata and controls
1184 lines (1060 loc) · 35.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Shapes;
using System.Windows.Threading;
using ICSharpCode.AvalonEdit.Document;
using ICSharpCode.AvalonEdit.Editing;
using ICSharpCode.AvalonEdit.Highlighting;
using ICSharpCode.AvalonEdit.Rendering;
using ICSharpCode.AvalonEdit.Utils;
namespace ICSharpCode.AvalonEdit
{
/// <summary>
/// The text editor control.
/// Contains a scrollable TextArea.
/// </summary>
[Localizability(LocalizationCategory.Text), ContentProperty("Text")]
public class TextEditor : Control, ITextEditorComponent, IServiceProvider, IWeakEventListener
{
#region Constructors
static TextEditor()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(TextEditor),
new FrameworkPropertyMetadata(typeof(TextEditor)));
FocusableProperty.OverrideMetadata(typeof(TextEditor),
new FrameworkPropertyMetadata(Boxes.True));
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
public TextEditor() : this(new TextArea())
{
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
protected TextEditor(TextArea textArea)
{
if (textArea == null)
throw new ArgumentNullException("textArea");
this.textArea = textArea;
textArea.TextView.Services.AddService(typeof(TextEditor), this);
SetCurrentValue(OptionsProperty, textArea.Options);
SetCurrentValue(DocumentProperty, new TextDocument());
}
#if !DOTNET4
void SetCurrentValue(DependencyProperty property, object value)
{
SetValue(property, value);
}
#endif
#endregion
/// <inheritdoc/>
protected override System.Windows.Automation.Peers.AutomationPeer OnCreateAutomationPeer()
{
return new TextEditorAutomationPeer(this);
}
/// Forward focus to TextArea.
/// <inheritdoc/>
protected override void OnGotKeyboardFocus(KeyboardFocusChangedEventArgs e)
{
base.OnGotKeyboardFocus(e);
if (e.NewFocus == this) {
Keyboard.Focus(textArea);
e.Handled = true;
}
}
#region Document property
/// <summary>
/// Document property.
/// </summary>
public static readonly DependencyProperty DocumentProperty
= TextView.DocumentProperty.AddOwner(
typeof(TextEditor), new FrameworkPropertyMetadata(OnDocumentChanged));
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// This is a dependency property.
/// </summary>
public TextDocument Document {
get { return (TextDocument)GetValue(DocumentProperty); }
set { SetValue(DocumentProperty, value); }
}
/// <summary>
/// Occurs when the document property has changed.
/// </summary>
public event EventHandler DocumentChanged;
/// <summary>
/// Raises the <see cref="DocumentChanged"/> event.
/// </summary>
protected virtual void OnDocumentChanged(EventArgs e)
{
if (DocumentChanged != null) {
DocumentChanged(this, e);
}
}
static void OnDocumentChanged(DependencyObject dp, DependencyPropertyChangedEventArgs e)
{
((TextEditor)dp).OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null) {
TextDocumentWeakEventManager.TextChanged.RemoveListener(oldValue, this);
PropertyChangedEventManager.RemoveListener(oldValue.UndoStack, this, "IsOriginalFile");
}
textArea.Document = newValue;
if (newValue != null) {
TextDocumentWeakEventManager.TextChanged.AddListener(newValue, this);
PropertyChangedEventManager.AddListener(newValue.UndoStack, this, "IsOriginalFile");
}
OnDocumentChanged(EventArgs.Empty);
OnTextChanged(EventArgs.Empty);
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly DependencyProperty OptionsProperty
= TextView.OptionsProperty.AddOwner(typeof(TextEditor), new FrameworkPropertyMetadata(OnOptionsChanged));
/// <summary>
/// Gets/Sets the options currently used by the text editor.
/// </summary>
public TextEditorOptions Options {
get { return (TextEditorOptions)GetValue(OptionsProperty); }
set { SetValue(OptionsProperty, value); }
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
if (OptionChanged != null) {
OptionChanged(this, e);
}
}
static void OnOptionsChanged(DependencyObject dp, DependencyPropertyChangedEventArgs e)
{
((TextEditor)dp).OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null) {
PropertyChangedWeakEventManager.RemoveListener(oldValue, this);
}
textArea.Options = newValue;
if (newValue != null) {
PropertyChangedWeakEventManager.AddListener(newValue, this);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
/// <inheritdoc cref="IWeakEventListener.ReceiveWeakEvent"/>
protected virtual bool ReceiveWeakEvent(Type managerType, object sender, EventArgs e)
{
if (managerType == typeof(PropertyChangedWeakEventManager)) {
OnOptionChanged((PropertyChangedEventArgs)e);
return true;
} else if (managerType == typeof(TextDocumentWeakEventManager.TextChanged)) {
OnTextChanged(e);
return true;
} else if (managerType == typeof(PropertyChangedEventManager)) {
return HandleIsOriginalChanged((PropertyChangedEventArgs)e);
}
return false;
}
bool IWeakEventListener.ReceiveWeakEvent(Type managerType, object sender, EventArgs e)
{
return ReceiveWeakEvent(managerType, sender, e);
}
#endregion
#region Text property
/// <summary>
/// Gets/Sets the text of the current document.
/// </summary>
[Localizability(LocalizationCategory.Text), DefaultValue("")]
public string Text {
get {
TextDocument document = this.Document;
return document != null ? document.Text : string.Empty;
}
set {
TextDocument document = GetDocument();
document.Text = value ?? string.Empty;
// after replacing the full text, the caret is positioned at the end of the document
// - reset it to the beginning.
this.CaretOffset = 0;
document.UndoStack.ClearAll();
}
}
TextDocument GetDocument()
{
TextDocument document = this.Document;
if (document == null)
throw ThrowUtil.NoDocumentAssigned();
return document;
}
/// <summary>
/// Occurs when the Text property changes.
/// </summary>
public event EventHandler TextChanged;
/// <summary>
/// Raises the <see cref="TextChanged"/> event.
/// </summary>
protected virtual void OnTextChanged(EventArgs e)
{
if (TextChanged != null) {
TextChanged(this, e);
}
}
#endregion
#region TextArea / ScrollViewer properties
readonly TextArea textArea;
ScrollViewer scrollViewer;
/// <summary>
/// Is called after the template was applied.
/// </summary>
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
scrollViewer = (ScrollViewer)Template.FindName("PART_ScrollViewer", this);
}
/// <summary>
/// Gets the text area.
/// </summary>
public TextArea TextArea {
get {
return textArea;
}
}
/// <summary>
/// Gets the scroll viewer used by the text editor.
/// This property can return null if the template has not been applied / does not contain a scroll viewer.
/// </summary>
internal ScrollViewer ScrollViewer {
get { return scrollViewer; }
}
bool CanExecute(RoutedUICommand command)
{
return command.CanExecute(null, textArea);
}
void Execute(RoutedUICommand command)
{
command.Execute(null, textArea);
}
#endregion
#region Syntax highlighting
/// <summary>
/// The <see cref="SyntaxHighlighting"/> property.
/// </summary>
public static readonly DependencyProperty SyntaxHighlightingProperty =
DependencyProperty.Register("SyntaxHighlighting", typeof(IHighlightingDefinition), typeof(TextEditor),
new FrameworkPropertyMetadata(OnSyntaxHighlightingChanged));
/// <summary>
/// Gets/sets the syntax highlighting definition used to colorize the text.
/// </summary>
public IHighlightingDefinition SyntaxHighlighting {
get { return (IHighlightingDefinition)GetValue(SyntaxHighlightingProperty); }
set { SetValue(SyntaxHighlightingProperty, value); }
}
IVisualLineTransformer colorizer;
static void OnSyntaxHighlightingChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
((TextEditor)d).OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition);
}
void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue)
{
if (colorizer != null) {
textArea.TextView.LineTransformers.Remove(colorizer);
colorizer = null;
}
if (newValue != null) {
colorizer = CreateColorizer(newValue);
if (colorizer != null)
textArea.TextView.LineTransformers.Insert(0, colorizer);
}
}
/// <summary>
/// Creates the highlighting colorizer for the specified highlighting definition.
/// Allows derived classes to provide custom colorizer implementations for special highlighting definitions.
/// </summary>
/// <returns></returns>
protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition)
{
if (highlightingDefinition == null)
throw new ArgumentNullException("highlightingDefinition");
return new HighlightingColorizer(highlightingDefinition);
}
#endregion
#region WordWrap
/// <summary>
/// Word wrap dependency property.
/// </summary>
public static readonly DependencyProperty WordWrapProperty =
DependencyProperty.Register("WordWrap", typeof(bool), typeof(TextEditor),
new FrameworkPropertyMetadata(Boxes.False));
/// <summary>
/// Specifies whether the text editor uses word wrapping.
/// </summary>
/// <remarks>
/// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the
/// HorizontalScrollBarVisibility setting.
/// </remarks>
public bool WordWrap {
get { return (bool)GetValue(WordWrapProperty); }
set { SetValue(WordWrapProperty, Boxes.Box(value)); }
}
#endregion
#region IsReadOnly
/// <summary>
/// IsReadOnly dependency property.
/// </summary>
public static readonly DependencyProperty IsReadOnlyProperty =
DependencyProperty.Register("IsReadOnly", typeof(bool), typeof(TextEditor),
new FrameworkPropertyMetadata(Boxes.False, OnIsReadOnlyChanged));
/// <summary>
/// Specifies whether the user can change the text editor content.
/// Setting this property will replace the
/// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>.
/// </summary>
public bool IsReadOnly {
get { return (bool)GetValue(IsReadOnlyProperty); }
set { SetValue(IsReadOnlyProperty, Boxes.Box(value)); }
}
static void OnIsReadOnlyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
TextEditor editor = d as TextEditor;
if (editor != null) {
if ((bool)e.NewValue)
editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance;
else
editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance;
TextEditorAutomationPeer peer = TextEditorAutomationPeer.FromElement(editor) as TextEditorAutomationPeer;
if (peer != null) {
peer.RaiseIsReadOnlyChanged((bool)e.OldValue, (bool)e.NewValue);
}
}
}
#endregion
#region IsModified
/// <summary>
/// Dependency property for <see cref="IsModified"/>
/// </summary>
public static readonly DependencyProperty IsModifiedProperty =
DependencyProperty.Register("IsModified", typeof(bool), typeof(TextEditor),
new FrameworkPropertyMetadata(Boxes.False, OnIsModifiedChanged));
/// <summary>
/// Gets/Sets the 'modified' flag.
/// </summary>
public bool IsModified {
get { return (bool)GetValue(IsModifiedProperty); }
set { SetValue(IsModifiedProperty, Boxes.Box(value)); }
}
static void OnIsModifiedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
TextEditor editor = d as TextEditor;
if (editor != null) {
TextDocument document = editor.Document;
if (document != null) {
UndoStack undoStack = document.UndoStack;
if ((bool)e.NewValue) {
if (undoStack.IsOriginalFile)
undoStack.DiscardOriginalFileMarker();
} else {
undoStack.MarkAsOriginalFile();
}
}
}
}
bool HandleIsOriginalChanged(PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile") {
TextDocument document = this.Document;
if (document != null) {
SetCurrentValue(IsModifiedProperty, Boxes.Box(!document.UndoStack.IsOriginalFile));
}
return true;
} else {
return false;
}
}
#endregion
#region ShowLineNumbers
/// <summary>
/// ShowLineNumbers dependency property.
/// </summary>
public static readonly DependencyProperty ShowLineNumbersProperty =
DependencyProperty.Register("ShowLineNumbers", typeof(bool), typeof(TextEditor),
new FrameworkPropertyMetadata(Boxes.False, OnShowLineNumbersChanged));
/// <summary>
/// Specifies whether line numbers are shown on the left to the text view.
/// </summary>
public bool ShowLineNumbers {
get { return (bool)GetValue(ShowLineNumbersProperty); }
set { SetValue(ShowLineNumbersProperty, Boxes.Box(value)); }
}
static void OnShowLineNumbersChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
TextEditor editor = (TextEditor)d;
var leftMargins = editor.TextArea.LeftMargins;
if ((bool)e.NewValue) {
LineNumberMargin lineNumbers = new LineNumberMargin();
Line line = (Line)DottedLineMargin.Create();
leftMargins.Insert(0, lineNumbers);
leftMargins.Insert(1, line);
var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor };
line.SetBinding(Line.StrokeProperty, lineNumbersForeground);
lineNumbers.SetBinding(Control.ForegroundProperty, lineNumbersForeground);
} else {
for (int i = 0; i < leftMargins.Count; i++) {
if (leftMargins[i] is LineNumberMargin) {
leftMargins.RemoveAt(i);
if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) {
leftMargins.RemoveAt(i);
}
break;
}
}
}
}
#endregion
#region LineNumbersForeground
/// <summary>
/// LineNumbersForeground dependency property.
/// </summary>
public static readonly DependencyProperty LineNumbersForegroundProperty =
DependencyProperty.Register("LineNumbersForeground", typeof(Brush), typeof(TextEditor),
new FrameworkPropertyMetadata(Brushes.Gray, OnLineNumbersForegroundChanged));
/// <summary>
/// Gets/sets the Brush used for displaying the foreground color of line numbers.
/// </summary>
public Brush LineNumbersForeground {
get { return (Brush)GetValue(LineNumbersForegroundProperty); }
set { SetValue(LineNumbersForegroundProperty, value); }
}
static void OnLineNumbersForegroundChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
TextEditor editor = (TextEditor)d;
var lineNumberMargin = editor.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin;;
if (lineNumberMargin != null) {
lineNumberMargin.SetValue(Control.ForegroundProperty, e.NewValue);
}
}
#endregion
#region TextBoxBase-like methods
/// <summary>
/// Appends text to the end of the document.
/// </summary>
public void AppendText(string textData)
{
var document = GetDocument();
document.Insert(document.TextLength, textData);
}
/// <summary>
/// Begins a group of document changes.
/// </summary>
public void BeginChange()
{
GetDocument().BeginUpdate();
}
/// <summary>
/// Copies the current selection to the clipboard.
/// </summary>
public void Copy()
{
Execute(ApplicationCommands.Copy);
}
/// <summary>
/// Removes the current selection and copies it to the clipboard.
/// </summary>
public void Cut()
{
Execute(ApplicationCommands.Cut);
}
/// <summary>
/// Begins a group of document changes and returns an object that ends the group of document
/// changes when it is disposed.
/// </summary>
public IDisposable DeclareChangeBlock()
{
return GetDocument().RunUpdate();
}
/// <summary>
/// Removes the current selection without copying it to the clipboard.
/// </summary>
public void Delete()
{
Execute(ApplicationCommands.Delete);
}
/// <summary>
/// Ends the current group of document changes.
/// </summary>
public void EndChange()
{
GetDocument().EndUpdate();
}
/// <summary>
/// Scrolls one line down.
/// </summary>
public void LineDown()
{
if (scrollViewer != null)
scrollViewer.LineDown();
}
/// <summary>
/// Scrolls to the left.
/// </summary>
public void LineLeft()
{
if (scrollViewer != null)
scrollViewer.LineLeft();
}
/// <summary>
/// Scrolls to the right.
/// </summary>
public void LineRight()
{
if (scrollViewer != null)
scrollViewer.LineRight();
}
/// <summary>
/// Scrolls one line up.
/// </summary>
public void LineUp()
{
if (scrollViewer != null)
scrollViewer.LineUp();
}
/// <summary>
/// Scrolls one page down.
/// </summary>
public void PageDown()
{
if (scrollViewer != null)
scrollViewer.PageDown();
}
/// <summary>
/// Scrolls one page up.
/// </summary>
public void PageUp()
{
if (scrollViewer != null)
scrollViewer.PageUp();
}
/// <summary>
/// Scrolls one page left.
/// </summary>
public void PageLeft()
{
if (scrollViewer != null)
scrollViewer.PageLeft();
}
/// <summary>
/// Scrolls one page right.
/// </summary>
public void PageRight()
{
if (scrollViewer != null)
scrollViewer.PageRight();
}
/// <summary>
/// Pastes the clipboard content.
/// </summary>
public void Paste()
{
Execute(ApplicationCommands.Paste);
}
/// <summary>
/// Redoes the most recent undone command.
/// </summary>
/// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns>
public bool Redo()
{
if (CanExecute(ApplicationCommands.Redo)) {
Execute(ApplicationCommands.Redo);
return true;
}
return false;
}
/// <summary>
/// Scrolls to the end of the document.
/// </summary>
public void ScrollToEnd()
{
ApplyTemplate(); // ensure scrollViewer is created
if (scrollViewer != null)
scrollViewer.ScrollToEnd();
}
/// <summary>
/// Scrolls to the start of the document.
/// </summary>
public void ScrollToHome()
{
ApplyTemplate(); // ensure scrollViewer is created
if (scrollViewer != null)
scrollViewer.ScrollToHome();
}
/// <summary>
/// Scrolls to the specified position in the document.
/// </summary>
public void ScrollToHorizontalOffset(double offset)
{
ApplyTemplate(); // ensure scrollViewer is created
if (scrollViewer != null)
scrollViewer.ScrollToHorizontalOffset(offset);
}
/// <summary>
/// Scrolls to the specified position in the document.
/// </summary>
public void ScrollToVerticalOffset(double offset)
{
ApplyTemplate(); // ensure scrollViewer is created
if (scrollViewer != null)
scrollViewer.ScrollToVerticalOffset(offset);
}
/// <summary>
/// Selects the entire text.
/// </summary>
public void SelectAll()
{
Execute(ApplicationCommands.SelectAll);
}
/// <summary>
/// Undoes the most recent command.
/// </summary>
/// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns>
public bool Undo()
{
if (CanExecute(ApplicationCommands.Undo)) {
Execute(ApplicationCommands.Undo);
return true;
}
return false;
}
/// <summary>
/// Gets if the most recent undone command can be redone.
/// </summary>
public bool CanRedo {
get { return CanExecute(ApplicationCommands.Redo); }
}
/// <summary>
/// Gets if the most recent command can be undone.
/// </summary>
public bool CanUndo {
get { return CanExecute(ApplicationCommands.Undo); }
}
/// <summary>
/// Gets the vertical size of the document.
/// </summary>
public double ExtentHeight {
get {
return scrollViewer != null ? scrollViewer.ExtentHeight : 0;
}
}
/// <summary>
/// Gets the horizontal size of the current document region.
/// </summary>
public double ExtentWidth {
get {
return scrollViewer != null ? scrollViewer.ExtentWidth : 0;
}
}
/// <summary>
/// Gets the horizontal size of the viewport.
/// </summary>
public double ViewportHeight {
get {
return scrollViewer != null ? scrollViewer.ViewportHeight : 0;
}
}
/// <summary>
/// Gets the horizontal size of the viewport.
/// </summary>
public double ViewportWidth {
get {
return scrollViewer != null ? scrollViewer.ViewportWidth : 0;
}
}
/// <summary>
/// Gets the vertical scroll position.
/// </summary>
public double VerticalOffset {
get {
return scrollViewer != null ? scrollViewer.VerticalOffset : 0;
}
}
/// <summary>
/// Gets the horizontal scroll position.
/// </summary>
public double HorizontalOffset {
get {
return scrollViewer != null ? scrollViewer.HorizontalOffset : 0;
}
}
#endregion
#region TextBox methods
/// <summary>
/// Gets/Sets the selected text.
/// </summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public string SelectedText {
get {
// We'll get the text from the whole surrounding segment.
// This is done to ensure that SelectedText.Length == SelectionLength.
if (textArea.Document != null && !textArea.Selection.IsEmpty)
return textArea.Document.GetText(textArea.Selection.SurroundingSegment);
else
return string.Empty;
}
set {
if (value == null)
throw new ArgumentNullException("value");
if (textArea.Document != null) {
int offset = this.SelectionStart;
int length = this.SelectionLength;
textArea.Document.Replace(offset, length, value);
// keep inserted text selected
textArea.Selection = SimpleSelection.Create(textArea, offset, offset + value.Length);
}
}
}
/// <summary>
/// Gets/sets the caret position.
/// </summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public int CaretOffset {
get {
return textArea.Caret.Offset;
}
set {
textArea.Caret.Offset = value;
}
}
/// <summary>
/// Gets/sets the start position of the selection.
/// </summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public int SelectionStart {
get {
if (textArea.Selection.IsEmpty)
return textArea.Caret.Offset;
else
return textArea.Selection.SurroundingSegment.Offset;
}
set {
Select(value, SelectionLength);
}
}
/// <summary>
/// Gets/sets the length of the selection.
/// </summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public int SelectionLength {
get {
if (!textArea.Selection.IsEmpty)
return textArea.Selection.SurroundingSegment.Length;
else
return 0;
}
set {
Select(SelectionStart, value);
}
}
/// <summary>
/// Selects the specified text section.
/// </summary>
public void Select(int start, int length)
{
int documentLength = Document != null ? Document.TextLength : 0;
if (start < 0 || start > documentLength)
throw new ArgumentOutOfRangeException("start", start, "Value must be between 0 and " + documentLength);
if (length < 0 || start + length > documentLength)
throw new ArgumentOutOfRangeException("length", length, "Value must be between 0 and " + (documentLength - start));
textArea.Selection = SimpleSelection.Create(textArea, start, start + length);
textArea.Caret.Offset = start + length;
}
/// <summary>
/// Gets the number of lines in the document.
/// </summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public int LineCount {
get {
TextDocument document = this.Document;
if (document != null)
return document.LineCount;
else
return 1;
}
}
/// <summary>
/// Clears the text.
/// </summary>
public void Clear()
{
this.Text = string.Empty;
}
#endregion
#region Loading from stream
/// <summary>
/// Loads the text from the stream, auto-detecting the encoding.
/// </summary>
/// <remarks>
/// This method sets <see cref="IsModified"/> to false.
/// </remarks>
public void Load(Stream stream)
{
using (StreamReader reader = FileReader.OpenStream(stream, this.Encoding ?? Encoding.UTF8)) {
this.Text = reader.ReadToEnd();
SetCurrentValue(EncodingProperty, reader.CurrentEncoding); // assign encoding after ReadToEnd() so that the StreamReader can autodetect the encoding
}
SetCurrentValue(IsModifiedProperty, Boxes.False);
}
/// <summary>
/// Loads the text from the stream, auto-detecting the encoding.
/// </summary>
public void Load(string fileName)
{
if (fileName == null)
throw new ArgumentNullException("fileName");
using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) {
Load(fs);
}
}
/// <summary>
/// Encoding dependency property.
/// </summary>
public static readonly DependencyProperty EncodingProperty =
DependencyProperty.Register("Encoding", typeof(Encoding), typeof(TextEditor));
/// <summary>
/// Gets/sets the encoding used when the file is saved.
/// </summary>
/// <remarks>
/// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly.
/// The <see cref="Save(Stream)"/> method uses the encoding specified in this property.
/// </remarks>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public Encoding Encoding {
get { return (Encoding)GetValue(EncodingProperty); }
set { SetValue(EncodingProperty, value); }
}
/// <summary>
/// Saves the text to the stream.
/// </summary>
/// <remarks>
/// This method sets <see cref="IsModified"/> to false.
/// </remarks>
public void Save(Stream stream)
{
if (stream == null)
throw new ArgumentNullException("stream");
var encoding = this.Encoding;
var document = this.Document;
StreamWriter writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream);
if (document != null)
document.WriteTextTo(writer);
writer.Flush();
// do not close the stream
SetCurrentValue(IsModifiedProperty, Boxes.False);
}
/// <summary>
/// Saves the text to the file.
/// </summary>
public void Save(string fileName)
{
if (fileName == null)
throw new ArgumentNullException("fileName");
using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) {
Save(fs);
}