Search is not available for this dataset
id
stringlengths
1
8
text
stringlengths
72
9.81M
addition_count
int64
0
10k
commit_subject
stringlengths
0
3.7k
deletion_count
int64
0
8.43k
file_extension
stringlengths
0
32
lang
stringlengths
1
94
license
stringclasses
10 values
repo_name
stringlengths
9
59
10067250
<NME> EditingCommandHandler.cs <BEF> // 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.Collections.Generic; using System.Globalization; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using Avalonia.Input; using AvaloniaEdit.Utils; namespace AvaloniaEdit.Editing { /// <summary> /// We re-use the CommandBinding and InputBinding instances between multiple text areas, /// so this class is static. /// </summary> internal class EditingCommandHandler { /// <summary> /// Creates a new <see cref="TextAreaInputHandler"/> for the text area. /// </summary> public static TextAreaInputHandler Create(TextArea textArea) { var handler = new TextAreaInputHandler(textArea); handler.CommandBindings.AddRange(CommandBindings); handler.KeyBindings.AddRange(KeyBindings); return handler; } private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>(); private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>(); private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler) { CommandBindings.Add(new RoutedCommandBinding(command, handler)); KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key)); } private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null) { CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler)); } static EditingCommandHandler() { AddBinding(EditingCommands.Delete, KeyModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight)); AddBinding(EditingCommands.DeleteNextWord, KeyModifiers.Control, Key.Delete, OnDelete(CaretMovementType.WordRight)); AddBinding(EditingCommands.Backspace, KeyModifiers.None, Key.Back, OnDelete(CaretMovementType.Backspace)); KeyBindings.Add( TextAreaDefaultInputHandler.CreateKeyBinding(EditingCommands.Backspace, KeyModifiers.Shift, Key.Back)); // make Shift-Backspace do the same as plain backspace AddBinding(EditingCommands.DeletePreviousWord, KeyModifiers.Control, Key.Back, OnDelete(CaretMovementType.WordLeft)); AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter); AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter); AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab); AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab); AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete); AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy); AddBinding(ApplicationCommands.Cut, OnCut, CanCut); AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste); AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike); AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine); AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace); AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace); AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase); AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase); AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase); AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase); AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces); AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs); AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces); AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs); AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection); } private static TextArea GetTextArea(object target) { return target as TextArea; } #region Text Transformation Helpers private enum DefaultSegmentType { WholeDocument, CurrentLine } /// <summary> /// Calls transformLine on all lines in the selected range. /// transformLine needs to handle read-only segments! /// </summary> private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target, ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { DocumentLine start, end; if (textArea.Selection.IsEmpty) { if (defaultSegmentType == DefaultSegmentType.CurrentLine) { start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line); } else if (defaultSegmentType == DefaultSegmentType.WholeDocument) { start = textArea.Document.Lines.First(); end = textArea.Document.Lines.Last(); } else { start = end = null; } } else { var segment = textArea.Selection.SurroundingSegment; start = textArea.Document.GetLineByOffset(segment.Offset); end = textArea.Document.GetLineByOffset(segment.EndOffset); // don't include the last line if no characters on it are selected if (start != end && end.Offset == segment.EndOffset) end = end.PreviousLine; } if (start != null) { transformLine(textArea, start); while (start != end) { start = start.NextLine; transformLine(textArea, start); } } } textArea.Caret.BringCaretToView(); args.Handled = true; } } /// <summary> /// Calls transformLine on all writable segment in the selected range. /// </summary> private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target, ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { IEnumerable<ISegment> segments; if (textArea.Selection.IsEmpty) { if (defaultSegmentType == DefaultSegmentType.CurrentLine) { segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) }; } else if (defaultSegmentType == DefaultSegmentType.WholeDocument) { segments = textArea.Document.Lines; } else { segments = null; } } else { segments = textArea.Selection.Segments; } if (segments != null) { foreach (var segment in segments.Reverse()) { foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse()) { transformSegment(textArea, writableSegment); } } } } textArea.Caret.BringCaretToView(); args.Handled = true; } } #endregion #region EnterLineBreak private static void OnEnter(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea != null && textArea.IsFocused) { textArea.PerformTextInput("\n"); args.Handled = true; } } #endregion #region Tab private static void OnTab(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { if (textArea.Selection.IsMultiline) { var segment = textArea.Selection.SurroundingSegment; var start = textArea.Document.GetLineByOffset(segment.Offset); var end = textArea.Document.GetLineByOffset(segment.EndOffset); // don't include the last line if no characters on it are selected if (start != end && end.Offset == segment.EndOffset) end = end.PreviousLine; var current = start; while (true) { var offset = current.Offset; if (textArea.ReadOnlySectionProvider.CanInsert(offset)) textArea.Document.Replace(offset, 0, textArea.Options.IndentationString, OffsetChangeMappingType.KeepAnchorBeforeInsertion); if (current == end) break; current = current.NextLine; } } else { var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column); textArea.ReplaceSelectionWithText(indentationString); } } textArea.Caret.BringCaretToView(); args.Handled = true; } } private static void OnShiftTab(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { var offset = line.Offset; var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset, textArea.Options.IndentationSize); if (s.Length > 0) { s = textArea.GetDeletableSegments(s).FirstOrDefault(); if (s != null && s.Length > 0) { textArea.Document.Remove(s.Offset, s.Length); } } }, target, args, DefaultSegmentType.CurrentLine); } #endregion #region Delete private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement) { return (target, args) => { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty) { var startPos = textArea.Caret.Position; var enableVirtualSpace = textArea.Options.EnableVirtualSpace; // When pressing delete; don't move the caret further into virtual space - instead delete the newline if (caretMovement == CaretMovementType.CharRight) enableVirtualSpace = false; var desiredXPos = textArea.Caret.DesiredXPos; var endPos = CaretNavigationCommandHandler.GetNewCaretPosition( textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos); // GetNewCaretPosition may return (0,0) as new position, // thus we need to validate endPos before using it in the selection. if (endPos.Line < 1 || endPos.Column < 1) endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1)); // Don't do anything if the number of lines of a rectangular selection would be changed by the deletion. if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line) return; // Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic // Reuse the existing selection, so that we continue using the same logic textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos) .ReplaceSelectionWithText(string.Empty); } else { textArea.RemoveSelectedText(); } textArea.Caret.BringCaretToView(); args.Handled = true; } }; } private static void CanDelete(object target, CanExecuteRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = true; args.Handled = true; } } #endregion #region Clipboard commands private static void CanCut(object target, CanExecuteRoutedEventArgs args) { // HasSomethingSelected for copy and cut commands var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly; args.Handled = true; } } private static void CanCopy(object target, CanExecuteRoutedEventArgs args) { // HasSomethingSelected for copy and cut commands var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty; args.Handled = true; } } private static void OnCopy(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine) { var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line); CopyWholeLine(textArea, currentLine); } else { CopySelectedText(textArea); } args.Handled = true; } } private static void OnCut(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine) { var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line); if (CopyWholeLine(textArea, currentLine)) { var segmentsToDelete = textArea.GetDeletableSegments( new SimpleSegment(currentLine.Offset, currentLine.TotalLength)); for (var i = segmentsToDelete.Length - 1; i >= 0; i--) { textArea.Document.Remove(segmentsToDelete[i]); } } } else { if (CopySelectedText(textArea)) textArea.RemoveSelectedText(); } textArea.Caret.BringCaretToView(); args.Handled = true; } } private static bool CopySelectedText(TextArea textArea) { var text = textArea.Selection.GetText(); text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); SetClipboardText(text); textArea.OnTextCopied(new TextEventArgs(text)); return true; } private static void SetClipboardText(string text) { try { Application.Current.Clipboard.SetTextAsync(text).GetAwaiter().GetResult(); } catch (Exception) { // Apparently this exception sometimes happens randomly. // The MS controls just ignore it, so we'll do the same. } } private static bool CopyWholeLine(TextArea textArea, DocumentLine line) { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); // Ignore empty line copy if(string.IsNullOrEmpty(text)) return false; // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); // TODO: formats //DataObject data = new DataObject(); //if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText)) // data.SetText(text); //// Also copy text in HTML format to clipboard - good for pasting text into Word //// or to the SharpDevelop forums. //if (ConfirmDataFormat(textArea, data, DataFormats.Html)) //{ // IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter; // HtmlClipboard.SetHtml(data, // HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine, // new HtmlOptions(textArea.Options))); //} //if (ConfirmDataFormat(textArea, data, LineSelectedType)) //{ // var lineSelected = new MemoryStream(1); // lineSelected.WriteByte(1); // data.SetData(LineSelectedType, lineSelected, false); //} //var copyingEventArgs = new DataObjectCopyingEventArgs(data, false); var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset) && !string.IsNullOrEmpty(Application.Current.Clipboard.GetTextAsync() .GetAwaiter() .GetResult()); args.Handled = true; } } private static void OnPaste(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { string text; try { text = Application.Current.Clipboard.GetTextAsync().GetAwaiter().GetResult(); } catch (Exception) { return; } string text = null; try { text = await Application.Current.Clipboard.GetTextAsync(); } catch (Exception) { textArea.Document.EndUpdate(); return; textArea.Caret.BringCaretToView(); args.Handled = true; } } if (!string.IsNullOrEmpty(text)) { textArea.ReplaceSelectionWithText(text); } textArea.Caret.BringCaretToView(); args.Handled = true; textArea.Document.EndUpdate(); } } internal static string GetTextToPaste(string text, TextArea textArea) { try { // Try retrieving the text as one of: // - the FormatToApply // - UnicodeText // - Text // (but don't try the same format twice) //if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply)) // text = (string)dataObject.GetData(pastingEventArgs.FormatToApply); //else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText && // dataObject.GetDataPresent(DataFormats.UnicodeText)) // text = (string)dataObject.GetData(DataFormats.UnicodeText); //else if (pastingEventArgs.FormatToApply != DataFormats.Text && // dataObject.GetDataPresent(DataFormats.Text)) // text = (string)dataObject.GetData(DataFormats.Text); //else // return null; // no text data format // convert text back to correct newlines for this document var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line); text = TextUtilities.NormalizeNewLines(text, newLine); text = textArea.Options.ConvertTabsToSpaces ? text.Replace("\t", new String(' ', textArea.Options.IndentationSize)) : text; return text; } catch (OutOfMemoryException) { // may happen when trying to paste a huge string return null; } } #endregion #region Toggle Overstrike private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea != null && textArea.Options.AllowToggleOverstrikeMode) textArea.OverstrikeMode = !textArea.OverstrikeMode; } #endregion #region DeleteLine private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { int firstLineIndex, lastLineIndex; if (textArea.Selection.Length == 0) { // There is no selection, simply delete current line firstLineIndex = lastLineIndex = textArea.Caret.Line; } else { // There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction) firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line, textArea.Selection.EndPosition.Line); lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line, textArea.Selection.EndPosition.Line); } var startLine = textArea.Document.GetLineByNumber(firstLineIndex); var endLine = textArea.Document.GetLineByNumber(lastLineIndex); textArea.Selection = Selection.Create(textArea, startLine.Offset, endLine.Offset + endLine.TotalLength); textArea.RemoveSelectedText(); args.Handled = true; } } #endregion #region Remove..Whitespace / Convert Tabs-Spaces private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment) { var document = textArea.Document; var endOffset = segment.EndOffset; var indentationString = new string(' ', textArea.Options.IndentationSize); for (var offset = segment.Offset; offset < endOffset; offset++) { if (document.GetCharAt(offset) == '\t') { document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace); endOffset += indentationString.Length - 1; } } } private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment) { var document = textArea.Document; var endOffset = segment.EndOffset; var indentationSize = textArea.Options.IndentationSize; var spacesCount = 0; for (var offset = segment.Offset; offset < endOffset; offset++) { if (document.GetCharAt(offset) == ' ') { spacesCount++; if (spacesCount == indentationSize) { document.Replace(offset - (indentationSize - 1), indentationSize, "\t", OffsetChangeMappingType.CharacterReplace); spacesCount = 0; offset -= indentationSize - 1; endOffset -= indentationSize - 1; } } else { spacesCount = 0; } } } #endregion #region Convert...Case private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments( delegate (TextArea textArea, ISegment segment) { var oldText = textArea.Document.GetText(segment); var newText = transformText(oldText); textArea.Document.Replace(segment.Offset, segment.Length, newText, OffsetChangeMappingType.CharacterReplace); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args); } private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args); } private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args) { throw new NotSupportedException(); //ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args); } private static void OnInvertCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(InvertCase, target, args); } private static string InvertCase(string text) { // TODO: culture //var culture = CultureInfo.CurrentCulture; var buffer = text.ToCharArray(); for (var i = 0; i < buffer.Length; ++i) { var c = buffer[i]; buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c); } return new string(buffer); } #endregion private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null && textArea.IndentationStrategy != null) { using (textArea.Document.RunUpdate()) { int start, end; if (textArea.Selection.IsEmpty) { start = 1; end = textArea.Document.LineCount; } else { start = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.Offset) .LineNumber; end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset) .LineNumber; } textArea.IndentationStrategy.IndentLines(textArea.Document, start, end); } textArea.Caret.BringCaretToView(); args.Handled = true; } } } } <MSG> fix paste from external app on linux. <DFF> @@ -24,6 +24,7 @@ using Avalonia; using AvaloniaEdit.Document; using Avalonia.Input; using AvaloniaEdit.Utils; +using System.Threading.Tasks; namespace AvaloniaEdit.Editing { @@ -469,26 +470,26 @@ namespace AvaloniaEdit.Editing var textArea = GetTextArea(target); if (textArea?.Document != null) { - args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset) - && !string.IsNullOrEmpty(Application.Current.Clipboard.GetTextAsync() - .GetAwaiter() - .GetResult()); + args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset); args.Handled = true; } } - private static void OnPaste(object target, ExecutedRoutedEventArgs args) + private static async void OnPaste(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { - string text; + textArea.Document.BeginUpdate(); + + string text = null; try { - text = Application.Current.Clipboard.GetTextAsync().GetAwaiter().GetResult(); + text = await Application.Current.Clipboard.GetTextAsync(); } catch (Exception) { + textArea.Document.EndUpdate(); return; } @@ -505,6 +506,8 @@ namespace AvaloniaEdit.Editing textArea.Caret.BringCaretToView(); args.Handled = true; + + textArea.Document.EndUpdate(); } }
10
fix paste from external app on linux.
7
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10067251
<NME> EditingCommandHandler.cs <BEF> // 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.Collections.Generic; using System.Globalization; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using Avalonia.Input; using AvaloniaEdit.Utils; namespace AvaloniaEdit.Editing { /// <summary> /// We re-use the CommandBinding and InputBinding instances between multiple text areas, /// so this class is static. /// </summary> internal class EditingCommandHandler { /// <summary> /// Creates a new <see cref="TextAreaInputHandler"/> for the text area. /// </summary> public static TextAreaInputHandler Create(TextArea textArea) { var handler = new TextAreaInputHandler(textArea); handler.CommandBindings.AddRange(CommandBindings); handler.KeyBindings.AddRange(KeyBindings); return handler; } private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>(); private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>(); private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler) { CommandBindings.Add(new RoutedCommandBinding(command, handler)); KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key)); } private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null) { CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler)); } static EditingCommandHandler() { AddBinding(EditingCommands.Delete, KeyModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight)); AddBinding(EditingCommands.DeleteNextWord, KeyModifiers.Control, Key.Delete, OnDelete(CaretMovementType.WordRight)); AddBinding(EditingCommands.Backspace, KeyModifiers.None, Key.Back, OnDelete(CaretMovementType.Backspace)); KeyBindings.Add( TextAreaDefaultInputHandler.CreateKeyBinding(EditingCommands.Backspace, KeyModifiers.Shift, Key.Back)); // make Shift-Backspace do the same as plain backspace AddBinding(EditingCommands.DeletePreviousWord, KeyModifiers.Control, Key.Back, OnDelete(CaretMovementType.WordLeft)); AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter); AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter); AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab); AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab); AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete); AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy); AddBinding(ApplicationCommands.Cut, OnCut, CanCut); AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste); AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike); AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine); AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace); AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace); AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase); AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase); AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase); AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase); AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces); AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs); AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces); AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs); AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection); } private static TextArea GetTextArea(object target) { return target as TextArea; } #region Text Transformation Helpers private enum DefaultSegmentType { WholeDocument, CurrentLine } /// <summary> /// Calls transformLine on all lines in the selected range. /// transformLine needs to handle read-only segments! /// </summary> private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target, ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { DocumentLine start, end; if (textArea.Selection.IsEmpty) { if (defaultSegmentType == DefaultSegmentType.CurrentLine) { start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line); } else if (defaultSegmentType == DefaultSegmentType.WholeDocument) { start = textArea.Document.Lines.First(); end = textArea.Document.Lines.Last(); } else { start = end = null; } } else { var segment = textArea.Selection.SurroundingSegment; start = textArea.Document.GetLineByOffset(segment.Offset); end = textArea.Document.GetLineByOffset(segment.EndOffset); // don't include the last line if no characters on it are selected if (start != end && end.Offset == segment.EndOffset) end = end.PreviousLine; } if (start != null) { transformLine(textArea, start); while (start != end) { start = start.NextLine; transformLine(textArea, start); } } } textArea.Caret.BringCaretToView(); args.Handled = true; } } /// <summary> /// Calls transformLine on all writable segment in the selected range. /// </summary> private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target, ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { IEnumerable<ISegment> segments; if (textArea.Selection.IsEmpty) { if (defaultSegmentType == DefaultSegmentType.CurrentLine) { segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) }; } else if (defaultSegmentType == DefaultSegmentType.WholeDocument) { segments = textArea.Document.Lines; } else { segments = null; } } else { segments = textArea.Selection.Segments; } if (segments != null) { foreach (var segment in segments.Reverse()) { foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse()) { transformSegment(textArea, writableSegment); } } } } textArea.Caret.BringCaretToView(); args.Handled = true; } } #endregion #region EnterLineBreak private static void OnEnter(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea != null && textArea.IsFocused) { textArea.PerformTextInput("\n"); args.Handled = true; } } #endregion #region Tab private static void OnTab(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { if (textArea.Selection.IsMultiline) { var segment = textArea.Selection.SurroundingSegment; var start = textArea.Document.GetLineByOffset(segment.Offset); var end = textArea.Document.GetLineByOffset(segment.EndOffset); // don't include the last line if no characters on it are selected if (start != end && end.Offset == segment.EndOffset) end = end.PreviousLine; var current = start; while (true) { var offset = current.Offset; if (textArea.ReadOnlySectionProvider.CanInsert(offset)) textArea.Document.Replace(offset, 0, textArea.Options.IndentationString, OffsetChangeMappingType.KeepAnchorBeforeInsertion); if (current == end) break; current = current.NextLine; } } else { var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column); textArea.ReplaceSelectionWithText(indentationString); } } textArea.Caret.BringCaretToView(); args.Handled = true; } } private static void OnShiftTab(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { var offset = line.Offset; var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset, textArea.Options.IndentationSize); if (s.Length > 0) { s = textArea.GetDeletableSegments(s).FirstOrDefault(); if (s != null && s.Length > 0) { textArea.Document.Remove(s.Offset, s.Length); } } }, target, args, DefaultSegmentType.CurrentLine); } #endregion #region Delete private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement) { return (target, args) => { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty) { var startPos = textArea.Caret.Position; var enableVirtualSpace = textArea.Options.EnableVirtualSpace; // When pressing delete; don't move the caret further into virtual space - instead delete the newline if (caretMovement == CaretMovementType.CharRight) enableVirtualSpace = false; var desiredXPos = textArea.Caret.DesiredXPos; var endPos = CaretNavigationCommandHandler.GetNewCaretPosition( textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos); // GetNewCaretPosition may return (0,0) as new position, // thus we need to validate endPos before using it in the selection. if (endPos.Line < 1 || endPos.Column < 1) endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1)); // Don't do anything if the number of lines of a rectangular selection would be changed by the deletion. if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line) return; // Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic // Reuse the existing selection, so that we continue using the same logic textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos) .ReplaceSelectionWithText(string.Empty); } else { textArea.RemoveSelectedText(); } textArea.Caret.BringCaretToView(); args.Handled = true; } }; } private static void CanDelete(object target, CanExecuteRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = true; args.Handled = true; } } #endregion #region Clipboard commands private static void CanCut(object target, CanExecuteRoutedEventArgs args) { // HasSomethingSelected for copy and cut commands var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly; args.Handled = true; } } private static void CanCopy(object target, CanExecuteRoutedEventArgs args) { // HasSomethingSelected for copy and cut commands var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty; args.Handled = true; } } private static void OnCopy(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine) { var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line); CopyWholeLine(textArea, currentLine); } else { CopySelectedText(textArea); } args.Handled = true; } } private static void OnCut(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine) { var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line); if (CopyWholeLine(textArea, currentLine)) { var segmentsToDelete = textArea.GetDeletableSegments( new SimpleSegment(currentLine.Offset, currentLine.TotalLength)); for (var i = segmentsToDelete.Length - 1; i >= 0; i--) { textArea.Document.Remove(segmentsToDelete[i]); } } } else { if (CopySelectedText(textArea)) textArea.RemoveSelectedText(); } textArea.Caret.BringCaretToView(); args.Handled = true; } } private static bool CopySelectedText(TextArea textArea) { var text = textArea.Selection.GetText(); text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); SetClipboardText(text); textArea.OnTextCopied(new TextEventArgs(text)); return true; } private static void SetClipboardText(string text) { try { Application.Current.Clipboard.SetTextAsync(text).GetAwaiter().GetResult(); } catch (Exception) { // Apparently this exception sometimes happens randomly. // The MS controls just ignore it, so we'll do the same. } } private static bool CopyWholeLine(TextArea textArea, DocumentLine line) { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); // Ignore empty line copy if(string.IsNullOrEmpty(text)) return false; // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); // TODO: formats //DataObject data = new DataObject(); //if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText)) // data.SetText(text); //// Also copy text in HTML format to clipboard - good for pasting text into Word //// or to the SharpDevelop forums. //if (ConfirmDataFormat(textArea, data, DataFormats.Html)) //{ // IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter; // HtmlClipboard.SetHtml(data, // HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine, // new HtmlOptions(textArea.Options))); //} //if (ConfirmDataFormat(textArea, data, LineSelectedType)) //{ // var lineSelected = new MemoryStream(1); // lineSelected.WriteByte(1); // data.SetData(LineSelectedType, lineSelected, false); //} //var copyingEventArgs = new DataObjectCopyingEventArgs(data, false); var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset) && !string.IsNullOrEmpty(Application.Current.Clipboard.GetTextAsync() .GetAwaiter() .GetResult()); args.Handled = true; } } private static void OnPaste(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { string text; try { text = Application.Current.Clipboard.GetTextAsync().GetAwaiter().GetResult(); } catch (Exception) { return; } string text = null; try { text = await Application.Current.Clipboard.GetTextAsync(); } catch (Exception) { textArea.Document.EndUpdate(); return; textArea.Caret.BringCaretToView(); args.Handled = true; } } if (!string.IsNullOrEmpty(text)) { textArea.ReplaceSelectionWithText(text); } textArea.Caret.BringCaretToView(); args.Handled = true; textArea.Document.EndUpdate(); } } internal static string GetTextToPaste(string text, TextArea textArea) { try { // Try retrieving the text as one of: // - the FormatToApply // - UnicodeText // - Text // (but don't try the same format twice) //if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply)) // text = (string)dataObject.GetData(pastingEventArgs.FormatToApply); //else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText && // dataObject.GetDataPresent(DataFormats.UnicodeText)) // text = (string)dataObject.GetData(DataFormats.UnicodeText); //else if (pastingEventArgs.FormatToApply != DataFormats.Text && // dataObject.GetDataPresent(DataFormats.Text)) // text = (string)dataObject.GetData(DataFormats.Text); //else // return null; // no text data format // convert text back to correct newlines for this document var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line); text = TextUtilities.NormalizeNewLines(text, newLine); text = textArea.Options.ConvertTabsToSpaces ? text.Replace("\t", new String(' ', textArea.Options.IndentationSize)) : text; return text; } catch (OutOfMemoryException) { // may happen when trying to paste a huge string return null; } } #endregion #region Toggle Overstrike private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea != null && textArea.Options.AllowToggleOverstrikeMode) textArea.OverstrikeMode = !textArea.OverstrikeMode; } #endregion #region DeleteLine private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { int firstLineIndex, lastLineIndex; if (textArea.Selection.Length == 0) { // There is no selection, simply delete current line firstLineIndex = lastLineIndex = textArea.Caret.Line; } else { // There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction) firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line, textArea.Selection.EndPosition.Line); lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line, textArea.Selection.EndPosition.Line); } var startLine = textArea.Document.GetLineByNumber(firstLineIndex); var endLine = textArea.Document.GetLineByNumber(lastLineIndex); textArea.Selection = Selection.Create(textArea, startLine.Offset, endLine.Offset + endLine.TotalLength); textArea.RemoveSelectedText(); args.Handled = true; } } #endregion #region Remove..Whitespace / Convert Tabs-Spaces private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment) { var document = textArea.Document; var endOffset = segment.EndOffset; var indentationString = new string(' ', textArea.Options.IndentationSize); for (var offset = segment.Offset; offset < endOffset; offset++) { if (document.GetCharAt(offset) == '\t') { document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace); endOffset += indentationString.Length - 1; } } } private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment) { var document = textArea.Document; var endOffset = segment.EndOffset; var indentationSize = textArea.Options.IndentationSize; var spacesCount = 0; for (var offset = segment.Offset; offset < endOffset; offset++) { if (document.GetCharAt(offset) == ' ') { spacesCount++; if (spacesCount == indentationSize) { document.Replace(offset - (indentationSize - 1), indentationSize, "\t", OffsetChangeMappingType.CharacterReplace); spacesCount = 0; offset -= indentationSize - 1; endOffset -= indentationSize - 1; } } else { spacesCount = 0; } } } #endregion #region Convert...Case private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments( delegate (TextArea textArea, ISegment segment) { var oldText = textArea.Document.GetText(segment); var newText = transformText(oldText); textArea.Document.Replace(segment.Offset, segment.Length, newText, OffsetChangeMappingType.CharacterReplace); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args); } private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args); } private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args) { throw new NotSupportedException(); //ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args); } private static void OnInvertCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(InvertCase, target, args); } private static string InvertCase(string text) { // TODO: culture //var culture = CultureInfo.CurrentCulture; var buffer = text.ToCharArray(); for (var i = 0; i < buffer.Length; ++i) { var c = buffer[i]; buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c); } return new string(buffer); } #endregion private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null && textArea.IndentationStrategy != null) { using (textArea.Document.RunUpdate()) { int start, end; if (textArea.Selection.IsEmpty) { start = 1; end = textArea.Document.LineCount; } else { start = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.Offset) .LineNumber; end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset) .LineNumber; } textArea.IndentationStrategy.IndentLines(textArea.Document, start, end); } textArea.Caret.BringCaretToView(); args.Handled = true; } } } } <MSG> fix paste from external app on linux. <DFF> @@ -24,6 +24,7 @@ using Avalonia; using AvaloniaEdit.Document; using Avalonia.Input; using AvaloniaEdit.Utils; +using System.Threading.Tasks; namespace AvaloniaEdit.Editing { @@ -469,26 +470,26 @@ namespace AvaloniaEdit.Editing var textArea = GetTextArea(target); if (textArea?.Document != null) { - args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset) - && !string.IsNullOrEmpty(Application.Current.Clipboard.GetTextAsync() - .GetAwaiter() - .GetResult()); + args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset); args.Handled = true; } } - private static void OnPaste(object target, ExecutedRoutedEventArgs args) + private static async void OnPaste(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { - string text; + textArea.Document.BeginUpdate(); + + string text = null; try { - text = Application.Current.Clipboard.GetTextAsync().GetAwaiter().GetResult(); + text = await Application.Current.Clipboard.GetTextAsync(); } catch (Exception) { + textArea.Document.EndUpdate(); return; } @@ -505,6 +506,8 @@ namespace AvaloniaEdit.Editing textArea.Caret.BringCaretToView(); args.Handled = true; + + textArea.Document.EndUpdate(); } }
10
fix paste from external app on linux.
7
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10067252
<NME> EditingCommandHandler.cs <BEF> // 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.Collections.Generic; using System.Globalization; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using Avalonia.Input; using AvaloniaEdit.Utils; namespace AvaloniaEdit.Editing { /// <summary> /// We re-use the CommandBinding and InputBinding instances between multiple text areas, /// so this class is static. /// </summary> internal class EditingCommandHandler { /// <summary> /// Creates a new <see cref="TextAreaInputHandler"/> for the text area. /// </summary> public static TextAreaInputHandler Create(TextArea textArea) { var handler = new TextAreaInputHandler(textArea); handler.CommandBindings.AddRange(CommandBindings); handler.KeyBindings.AddRange(KeyBindings); return handler; } private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>(); private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>(); private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler) { CommandBindings.Add(new RoutedCommandBinding(command, handler)); KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key)); } private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null) { CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler)); } static EditingCommandHandler() { AddBinding(EditingCommands.Delete, KeyModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight)); AddBinding(EditingCommands.DeleteNextWord, KeyModifiers.Control, Key.Delete, OnDelete(CaretMovementType.WordRight)); AddBinding(EditingCommands.Backspace, KeyModifiers.None, Key.Back, OnDelete(CaretMovementType.Backspace)); KeyBindings.Add( TextAreaDefaultInputHandler.CreateKeyBinding(EditingCommands.Backspace, KeyModifiers.Shift, Key.Back)); // make Shift-Backspace do the same as plain backspace AddBinding(EditingCommands.DeletePreviousWord, KeyModifiers.Control, Key.Back, OnDelete(CaretMovementType.WordLeft)); AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter); AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter); AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab); AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab); AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete); AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy); AddBinding(ApplicationCommands.Cut, OnCut, CanCut); AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste); AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike); AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine); AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace); AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace); AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase); AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase); AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase); AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase); AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces); AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs); AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces); AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs); AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection); } private static TextArea GetTextArea(object target) { return target as TextArea; } #region Text Transformation Helpers private enum DefaultSegmentType { WholeDocument, CurrentLine } /// <summary> /// Calls transformLine on all lines in the selected range. /// transformLine needs to handle read-only segments! /// </summary> private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target, ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { DocumentLine start, end; if (textArea.Selection.IsEmpty) { if (defaultSegmentType == DefaultSegmentType.CurrentLine) { start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line); } else if (defaultSegmentType == DefaultSegmentType.WholeDocument) { start = textArea.Document.Lines.First(); end = textArea.Document.Lines.Last(); } else { start = end = null; } } else { var segment = textArea.Selection.SurroundingSegment; start = textArea.Document.GetLineByOffset(segment.Offset); end = textArea.Document.GetLineByOffset(segment.EndOffset); // don't include the last line if no characters on it are selected if (start != end && end.Offset == segment.EndOffset) end = end.PreviousLine; } if (start != null) { transformLine(textArea, start); while (start != end) { start = start.NextLine; transformLine(textArea, start); } } } textArea.Caret.BringCaretToView(); args.Handled = true; } } /// <summary> /// Calls transformLine on all writable segment in the selected range. /// </summary> private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target, ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { IEnumerable<ISegment> segments; if (textArea.Selection.IsEmpty) { if (defaultSegmentType == DefaultSegmentType.CurrentLine) { segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) }; } else if (defaultSegmentType == DefaultSegmentType.WholeDocument) { segments = textArea.Document.Lines; } else { segments = null; } } else { segments = textArea.Selection.Segments; } if (segments != null) { foreach (var segment in segments.Reverse()) { foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse()) { transformSegment(textArea, writableSegment); } } } } textArea.Caret.BringCaretToView(); args.Handled = true; } } #endregion #region EnterLineBreak private static void OnEnter(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea != null && textArea.IsFocused) { textArea.PerformTextInput("\n"); args.Handled = true; } } #endregion #region Tab private static void OnTab(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { if (textArea.Selection.IsMultiline) { var segment = textArea.Selection.SurroundingSegment; var start = textArea.Document.GetLineByOffset(segment.Offset); var end = textArea.Document.GetLineByOffset(segment.EndOffset); // don't include the last line if no characters on it are selected if (start != end && end.Offset == segment.EndOffset) end = end.PreviousLine; var current = start; while (true) { var offset = current.Offset; if (textArea.ReadOnlySectionProvider.CanInsert(offset)) textArea.Document.Replace(offset, 0, textArea.Options.IndentationString, OffsetChangeMappingType.KeepAnchorBeforeInsertion); if (current == end) break; current = current.NextLine; } } else { var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column); textArea.ReplaceSelectionWithText(indentationString); } } textArea.Caret.BringCaretToView(); args.Handled = true; } } private static void OnShiftTab(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { var offset = line.Offset; var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset, textArea.Options.IndentationSize); if (s.Length > 0) { s = textArea.GetDeletableSegments(s).FirstOrDefault(); if (s != null && s.Length > 0) { textArea.Document.Remove(s.Offset, s.Length); } } }, target, args, DefaultSegmentType.CurrentLine); } #endregion #region Delete private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement) { return (target, args) => { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty) { var startPos = textArea.Caret.Position; var enableVirtualSpace = textArea.Options.EnableVirtualSpace; // When pressing delete; don't move the caret further into virtual space - instead delete the newline if (caretMovement == CaretMovementType.CharRight) enableVirtualSpace = false; var desiredXPos = textArea.Caret.DesiredXPos; var endPos = CaretNavigationCommandHandler.GetNewCaretPosition( textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos); // GetNewCaretPosition may return (0,0) as new position, // thus we need to validate endPos before using it in the selection. if (endPos.Line < 1 || endPos.Column < 1) endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1)); // Don't do anything if the number of lines of a rectangular selection would be changed by the deletion. if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line) return; // Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic // Reuse the existing selection, so that we continue using the same logic textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos) .ReplaceSelectionWithText(string.Empty); } else { textArea.RemoveSelectedText(); } textArea.Caret.BringCaretToView(); args.Handled = true; } }; } private static void CanDelete(object target, CanExecuteRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = true; args.Handled = true; } } #endregion #region Clipboard commands private static void CanCut(object target, CanExecuteRoutedEventArgs args) { // HasSomethingSelected for copy and cut commands var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly; args.Handled = true; } } private static void CanCopy(object target, CanExecuteRoutedEventArgs args) { // HasSomethingSelected for copy and cut commands var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty; args.Handled = true; } } private static void OnCopy(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine) { var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line); CopyWholeLine(textArea, currentLine); } else { CopySelectedText(textArea); } args.Handled = true; } } private static void OnCut(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine) { var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line); if (CopyWholeLine(textArea, currentLine)) { var segmentsToDelete = textArea.GetDeletableSegments( new SimpleSegment(currentLine.Offset, currentLine.TotalLength)); for (var i = segmentsToDelete.Length - 1; i >= 0; i--) { textArea.Document.Remove(segmentsToDelete[i]); } } } else { if (CopySelectedText(textArea)) textArea.RemoveSelectedText(); } textArea.Caret.BringCaretToView(); args.Handled = true; } } private static bool CopySelectedText(TextArea textArea) { var text = textArea.Selection.GetText(); text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); SetClipboardText(text); textArea.OnTextCopied(new TextEventArgs(text)); return true; } private static void SetClipboardText(string text) { try { Application.Current.Clipboard.SetTextAsync(text).GetAwaiter().GetResult(); } catch (Exception) { // Apparently this exception sometimes happens randomly. // The MS controls just ignore it, so we'll do the same. } } private static bool CopyWholeLine(TextArea textArea, DocumentLine line) { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); // Ignore empty line copy if(string.IsNullOrEmpty(text)) return false; // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); // TODO: formats //DataObject data = new DataObject(); //if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText)) // data.SetText(text); //// Also copy text in HTML format to clipboard - good for pasting text into Word //// or to the SharpDevelop forums. //if (ConfirmDataFormat(textArea, data, DataFormats.Html)) //{ // IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter; // HtmlClipboard.SetHtml(data, // HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine, // new HtmlOptions(textArea.Options))); //} //if (ConfirmDataFormat(textArea, data, LineSelectedType)) //{ // var lineSelected = new MemoryStream(1); // lineSelected.WriteByte(1); // data.SetData(LineSelectedType, lineSelected, false); //} //var copyingEventArgs = new DataObjectCopyingEventArgs(data, false); var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset) && !string.IsNullOrEmpty(Application.Current.Clipboard.GetTextAsync() .GetAwaiter() .GetResult()); args.Handled = true; } } private static void OnPaste(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { string text; try { text = Application.Current.Clipboard.GetTextAsync().GetAwaiter().GetResult(); } catch (Exception) { return; } string text = null; try { text = await Application.Current.Clipboard.GetTextAsync(); } catch (Exception) { textArea.Document.EndUpdate(); return; textArea.Caret.BringCaretToView(); args.Handled = true; } } if (!string.IsNullOrEmpty(text)) { textArea.ReplaceSelectionWithText(text); } textArea.Caret.BringCaretToView(); args.Handled = true; textArea.Document.EndUpdate(); } } internal static string GetTextToPaste(string text, TextArea textArea) { try { // Try retrieving the text as one of: // - the FormatToApply // - UnicodeText // - Text // (but don't try the same format twice) //if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply)) // text = (string)dataObject.GetData(pastingEventArgs.FormatToApply); //else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText && // dataObject.GetDataPresent(DataFormats.UnicodeText)) // text = (string)dataObject.GetData(DataFormats.UnicodeText); //else if (pastingEventArgs.FormatToApply != DataFormats.Text && // dataObject.GetDataPresent(DataFormats.Text)) // text = (string)dataObject.GetData(DataFormats.Text); //else // return null; // no text data format // convert text back to correct newlines for this document var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line); text = TextUtilities.NormalizeNewLines(text, newLine); text = textArea.Options.ConvertTabsToSpaces ? text.Replace("\t", new String(' ', textArea.Options.IndentationSize)) : text; return text; } catch (OutOfMemoryException) { // may happen when trying to paste a huge string return null; } } #endregion #region Toggle Overstrike private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea != null && textArea.Options.AllowToggleOverstrikeMode) textArea.OverstrikeMode = !textArea.OverstrikeMode; } #endregion #region DeleteLine private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { int firstLineIndex, lastLineIndex; if (textArea.Selection.Length == 0) { // There is no selection, simply delete current line firstLineIndex = lastLineIndex = textArea.Caret.Line; } else { // There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction) firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line, textArea.Selection.EndPosition.Line); lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line, textArea.Selection.EndPosition.Line); } var startLine = textArea.Document.GetLineByNumber(firstLineIndex); var endLine = textArea.Document.GetLineByNumber(lastLineIndex); textArea.Selection = Selection.Create(textArea, startLine.Offset, endLine.Offset + endLine.TotalLength); textArea.RemoveSelectedText(); args.Handled = true; } } #endregion #region Remove..Whitespace / Convert Tabs-Spaces private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment) { var document = textArea.Document; var endOffset = segment.EndOffset; var indentationString = new string(' ', textArea.Options.IndentationSize); for (var offset = segment.Offset; offset < endOffset; offset++) { if (document.GetCharAt(offset) == '\t') { document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace); endOffset += indentationString.Length - 1; } } } private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment) { var document = textArea.Document; var endOffset = segment.EndOffset; var indentationSize = textArea.Options.IndentationSize; var spacesCount = 0; for (var offset = segment.Offset; offset < endOffset; offset++) { if (document.GetCharAt(offset) == ' ') { spacesCount++; if (spacesCount == indentationSize) { document.Replace(offset - (indentationSize - 1), indentationSize, "\t", OffsetChangeMappingType.CharacterReplace); spacesCount = 0; offset -= indentationSize - 1; endOffset -= indentationSize - 1; } } else { spacesCount = 0; } } } #endregion #region Convert...Case private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments( delegate (TextArea textArea, ISegment segment) { var oldText = textArea.Document.GetText(segment); var newText = transformText(oldText); textArea.Document.Replace(segment.Offset, segment.Length, newText, OffsetChangeMappingType.CharacterReplace); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args); } private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args); } private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args) { throw new NotSupportedException(); //ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args); } private static void OnInvertCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(InvertCase, target, args); } private static string InvertCase(string text) { // TODO: culture //var culture = CultureInfo.CurrentCulture; var buffer = text.ToCharArray(); for (var i = 0; i < buffer.Length; ++i) { var c = buffer[i]; buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c); } return new string(buffer); } #endregion private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null && textArea.IndentationStrategy != null) { using (textArea.Document.RunUpdate()) { int start, end; if (textArea.Selection.IsEmpty) { start = 1; end = textArea.Document.LineCount; } else { start = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.Offset) .LineNumber; end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset) .LineNumber; } textArea.IndentationStrategy.IndentLines(textArea.Document, start, end); } textArea.Caret.BringCaretToView(); args.Handled = true; } } } } <MSG> fix paste from external app on linux. <DFF> @@ -24,6 +24,7 @@ using Avalonia; using AvaloniaEdit.Document; using Avalonia.Input; using AvaloniaEdit.Utils; +using System.Threading.Tasks; namespace AvaloniaEdit.Editing { @@ -469,26 +470,26 @@ namespace AvaloniaEdit.Editing var textArea = GetTextArea(target); if (textArea?.Document != null) { - args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset) - && !string.IsNullOrEmpty(Application.Current.Clipboard.GetTextAsync() - .GetAwaiter() - .GetResult()); + args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset); args.Handled = true; } } - private static void OnPaste(object target, ExecutedRoutedEventArgs args) + private static async void OnPaste(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { - string text; + textArea.Document.BeginUpdate(); + + string text = null; try { - text = Application.Current.Clipboard.GetTextAsync().GetAwaiter().GetResult(); + text = await Application.Current.Clipboard.GetTextAsync(); } catch (Exception) { + textArea.Document.EndUpdate(); return; } @@ -505,6 +506,8 @@ namespace AvaloniaEdit.Editing textArea.Caret.BringCaretToView(); args.Handled = true; + + textArea.Document.EndUpdate(); } }
10
fix paste from external app on linux.
7
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10067253
<NME> EditingCommandHandler.cs <BEF> // 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.Collections.Generic; using System.Globalization; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using Avalonia.Input; using AvaloniaEdit.Utils; namespace AvaloniaEdit.Editing { /// <summary> /// We re-use the CommandBinding and InputBinding instances between multiple text areas, /// so this class is static. /// </summary> internal class EditingCommandHandler { /// <summary> /// Creates a new <see cref="TextAreaInputHandler"/> for the text area. /// </summary> public static TextAreaInputHandler Create(TextArea textArea) { var handler = new TextAreaInputHandler(textArea); handler.CommandBindings.AddRange(CommandBindings); handler.KeyBindings.AddRange(KeyBindings); return handler; } private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>(); private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>(); private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler) { CommandBindings.Add(new RoutedCommandBinding(command, handler)); KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key)); } private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null) { CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler)); } static EditingCommandHandler() { AddBinding(EditingCommands.Delete, KeyModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight)); AddBinding(EditingCommands.DeleteNextWord, KeyModifiers.Control, Key.Delete, OnDelete(CaretMovementType.WordRight)); AddBinding(EditingCommands.Backspace, KeyModifiers.None, Key.Back, OnDelete(CaretMovementType.Backspace)); KeyBindings.Add( TextAreaDefaultInputHandler.CreateKeyBinding(EditingCommands.Backspace, KeyModifiers.Shift, Key.Back)); // make Shift-Backspace do the same as plain backspace AddBinding(EditingCommands.DeletePreviousWord, KeyModifiers.Control, Key.Back, OnDelete(CaretMovementType.WordLeft)); AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter); AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter); AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab); AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab); AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete); AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy); AddBinding(ApplicationCommands.Cut, OnCut, CanCut); AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste); AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike); AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine); AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace); AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace); AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase); AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase); AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase); AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase); AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces); AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs); AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces); AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs); AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection); } private static TextArea GetTextArea(object target) { return target as TextArea; } #region Text Transformation Helpers private enum DefaultSegmentType { WholeDocument, CurrentLine } /// <summary> /// Calls transformLine on all lines in the selected range. /// transformLine needs to handle read-only segments! /// </summary> private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target, ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { DocumentLine start, end; if (textArea.Selection.IsEmpty) { if (defaultSegmentType == DefaultSegmentType.CurrentLine) { start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line); } else if (defaultSegmentType == DefaultSegmentType.WholeDocument) { start = textArea.Document.Lines.First(); end = textArea.Document.Lines.Last(); } else { start = end = null; } } else { var segment = textArea.Selection.SurroundingSegment; start = textArea.Document.GetLineByOffset(segment.Offset); end = textArea.Document.GetLineByOffset(segment.EndOffset); // don't include the last line if no characters on it are selected if (start != end && end.Offset == segment.EndOffset) end = end.PreviousLine; } if (start != null) { transformLine(textArea, start); while (start != end) { start = start.NextLine; transformLine(textArea, start); } } } textArea.Caret.BringCaretToView(); args.Handled = true; } } /// <summary> /// Calls transformLine on all writable segment in the selected range. /// </summary> private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target, ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { IEnumerable<ISegment> segments; if (textArea.Selection.IsEmpty) { if (defaultSegmentType == DefaultSegmentType.CurrentLine) { segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) }; } else if (defaultSegmentType == DefaultSegmentType.WholeDocument) { segments = textArea.Document.Lines; } else { segments = null; } } else { segments = textArea.Selection.Segments; } if (segments != null) { foreach (var segment in segments.Reverse()) { foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse()) { transformSegment(textArea, writableSegment); } } } } textArea.Caret.BringCaretToView(); args.Handled = true; } } #endregion #region EnterLineBreak private static void OnEnter(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea != null && textArea.IsFocused) { textArea.PerformTextInput("\n"); args.Handled = true; } } #endregion #region Tab private static void OnTab(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { if (textArea.Selection.IsMultiline) { var segment = textArea.Selection.SurroundingSegment; var start = textArea.Document.GetLineByOffset(segment.Offset); var end = textArea.Document.GetLineByOffset(segment.EndOffset); // don't include the last line if no characters on it are selected if (start != end && end.Offset == segment.EndOffset) end = end.PreviousLine; var current = start; while (true) { var offset = current.Offset; if (textArea.ReadOnlySectionProvider.CanInsert(offset)) textArea.Document.Replace(offset, 0, textArea.Options.IndentationString, OffsetChangeMappingType.KeepAnchorBeforeInsertion); if (current == end) break; current = current.NextLine; } } else { var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column); textArea.ReplaceSelectionWithText(indentationString); } } textArea.Caret.BringCaretToView(); args.Handled = true; } } private static void OnShiftTab(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { var offset = line.Offset; var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset, textArea.Options.IndentationSize); if (s.Length > 0) { s = textArea.GetDeletableSegments(s).FirstOrDefault(); if (s != null && s.Length > 0) { textArea.Document.Remove(s.Offset, s.Length); } } }, target, args, DefaultSegmentType.CurrentLine); } #endregion #region Delete private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement) { return (target, args) => { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty) { var startPos = textArea.Caret.Position; var enableVirtualSpace = textArea.Options.EnableVirtualSpace; // When pressing delete; don't move the caret further into virtual space - instead delete the newline if (caretMovement == CaretMovementType.CharRight) enableVirtualSpace = false; var desiredXPos = textArea.Caret.DesiredXPos; var endPos = CaretNavigationCommandHandler.GetNewCaretPosition( textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos); // GetNewCaretPosition may return (0,0) as new position, // thus we need to validate endPos before using it in the selection. if (endPos.Line < 1 || endPos.Column < 1) endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1)); // Don't do anything if the number of lines of a rectangular selection would be changed by the deletion. if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line) return; // Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic // Reuse the existing selection, so that we continue using the same logic textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos) .ReplaceSelectionWithText(string.Empty); } else { textArea.RemoveSelectedText(); } textArea.Caret.BringCaretToView(); args.Handled = true; } }; } private static void CanDelete(object target, CanExecuteRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = true; args.Handled = true; } } #endregion #region Clipboard commands private static void CanCut(object target, CanExecuteRoutedEventArgs args) { // HasSomethingSelected for copy and cut commands var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly; args.Handled = true; } } private static void CanCopy(object target, CanExecuteRoutedEventArgs args) { // HasSomethingSelected for copy and cut commands var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty; args.Handled = true; } } private static void OnCopy(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine) { var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line); CopyWholeLine(textArea, currentLine); } else { CopySelectedText(textArea); } args.Handled = true; } } private static void OnCut(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine) { var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line); if (CopyWholeLine(textArea, currentLine)) { var segmentsToDelete = textArea.GetDeletableSegments( new SimpleSegment(currentLine.Offset, currentLine.TotalLength)); for (var i = segmentsToDelete.Length - 1; i >= 0; i--) { textArea.Document.Remove(segmentsToDelete[i]); } } } else { if (CopySelectedText(textArea)) textArea.RemoveSelectedText(); } textArea.Caret.BringCaretToView(); args.Handled = true; } } private static bool CopySelectedText(TextArea textArea) { var text = textArea.Selection.GetText(); text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); SetClipboardText(text); textArea.OnTextCopied(new TextEventArgs(text)); return true; } private static void SetClipboardText(string text) { try { Application.Current.Clipboard.SetTextAsync(text).GetAwaiter().GetResult(); } catch (Exception) { // Apparently this exception sometimes happens randomly. // The MS controls just ignore it, so we'll do the same. } } private static bool CopyWholeLine(TextArea textArea, DocumentLine line) { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); // Ignore empty line copy if(string.IsNullOrEmpty(text)) return false; // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); // TODO: formats //DataObject data = new DataObject(); //if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText)) // data.SetText(text); //// Also copy text in HTML format to clipboard - good for pasting text into Word //// or to the SharpDevelop forums. //if (ConfirmDataFormat(textArea, data, DataFormats.Html)) //{ // IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter; // HtmlClipboard.SetHtml(data, // HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine, // new HtmlOptions(textArea.Options))); //} //if (ConfirmDataFormat(textArea, data, LineSelectedType)) //{ // var lineSelected = new MemoryStream(1); // lineSelected.WriteByte(1); // data.SetData(LineSelectedType, lineSelected, false); //} //var copyingEventArgs = new DataObjectCopyingEventArgs(data, false); var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset) && !string.IsNullOrEmpty(Application.Current.Clipboard.GetTextAsync() .GetAwaiter() .GetResult()); args.Handled = true; } } private static void OnPaste(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { string text; try { text = Application.Current.Clipboard.GetTextAsync().GetAwaiter().GetResult(); } catch (Exception) { return; } string text = null; try { text = await Application.Current.Clipboard.GetTextAsync(); } catch (Exception) { textArea.Document.EndUpdate(); return; textArea.Caret.BringCaretToView(); args.Handled = true; } } if (!string.IsNullOrEmpty(text)) { textArea.ReplaceSelectionWithText(text); } textArea.Caret.BringCaretToView(); args.Handled = true; textArea.Document.EndUpdate(); } } internal static string GetTextToPaste(string text, TextArea textArea) { try { // Try retrieving the text as one of: // - the FormatToApply // - UnicodeText // - Text // (but don't try the same format twice) //if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply)) // text = (string)dataObject.GetData(pastingEventArgs.FormatToApply); //else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText && // dataObject.GetDataPresent(DataFormats.UnicodeText)) // text = (string)dataObject.GetData(DataFormats.UnicodeText); //else if (pastingEventArgs.FormatToApply != DataFormats.Text && // dataObject.GetDataPresent(DataFormats.Text)) // text = (string)dataObject.GetData(DataFormats.Text); //else // return null; // no text data format // convert text back to correct newlines for this document var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line); text = TextUtilities.NormalizeNewLines(text, newLine); text = textArea.Options.ConvertTabsToSpaces ? text.Replace("\t", new String(' ', textArea.Options.IndentationSize)) : text; return text; } catch (OutOfMemoryException) { // may happen when trying to paste a huge string return null; } } #endregion #region Toggle Overstrike private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea != null && textArea.Options.AllowToggleOverstrikeMode) textArea.OverstrikeMode = !textArea.OverstrikeMode; } #endregion #region DeleteLine private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { int firstLineIndex, lastLineIndex; if (textArea.Selection.Length == 0) { // There is no selection, simply delete current line firstLineIndex = lastLineIndex = textArea.Caret.Line; } else { // There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction) firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line, textArea.Selection.EndPosition.Line); lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line, textArea.Selection.EndPosition.Line); } var startLine = textArea.Document.GetLineByNumber(firstLineIndex); var endLine = textArea.Document.GetLineByNumber(lastLineIndex); textArea.Selection = Selection.Create(textArea, startLine.Offset, endLine.Offset + endLine.TotalLength); textArea.RemoveSelectedText(); args.Handled = true; } } #endregion #region Remove..Whitespace / Convert Tabs-Spaces private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment) { var document = textArea.Document; var endOffset = segment.EndOffset; var indentationString = new string(' ', textArea.Options.IndentationSize); for (var offset = segment.Offset; offset < endOffset; offset++) { if (document.GetCharAt(offset) == '\t') { document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace); endOffset += indentationString.Length - 1; } } } private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment) { var document = textArea.Document; var endOffset = segment.EndOffset; var indentationSize = textArea.Options.IndentationSize; var spacesCount = 0; for (var offset = segment.Offset; offset < endOffset; offset++) { if (document.GetCharAt(offset) == ' ') { spacesCount++; if (spacesCount == indentationSize) { document.Replace(offset - (indentationSize - 1), indentationSize, "\t", OffsetChangeMappingType.CharacterReplace); spacesCount = 0; offset -= indentationSize - 1; endOffset -= indentationSize - 1; } } else { spacesCount = 0; } } } #endregion #region Convert...Case private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments( delegate (TextArea textArea, ISegment segment) { var oldText = textArea.Document.GetText(segment); var newText = transformText(oldText); textArea.Document.Replace(segment.Offset, segment.Length, newText, OffsetChangeMappingType.CharacterReplace); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args); } private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args); } private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args) { throw new NotSupportedException(); //ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args); } private static void OnInvertCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(InvertCase, target, args); } private static string InvertCase(string text) { // TODO: culture //var culture = CultureInfo.CurrentCulture; var buffer = text.ToCharArray(); for (var i = 0; i < buffer.Length; ++i) { var c = buffer[i]; buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c); } return new string(buffer); } #endregion private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null && textArea.IndentationStrategy != null) { using (textArea.Document.RunUpdate()) { int start, end; if (textArea.Selection.IsEmpty) { start = 1; end = textArea.Document.LineCount; } else { start = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.Offset) .LineNumber; end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset) .LineNumber; } textArea.IndentationStrategy.IndentLines(textArea.Document, start, end); } textArea.Caret.BringCaretToView(); args.Handled = true; } } } } <MSG> fix paste from external app on linux. <DFF> @@ -24,6 +24,7 @@ using Avalonia; using AvaloniaEdit.Document; using Avalonia.Input; using AvaloniaEdit.Utils; +using System.Threading.Tasks; namespace AvaloniaEdit.Editing { @@ -469,26 +470,26 @@ namespace AvaloniaEdit.Editing var textArea = GetTextArea(target); if (textArea?.Document != null) { - args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset) - && !string.IsNullOrEmpty(Application.Current.Clipboard.GetTextAsync() - .GetAwaiter() - .GetResult()); + args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset); args.Handled = true; } } - private static void OnPaste(object target, ExecutedRoutedEventArgs args) + private static async void OnPaste(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { - string text; + textArea.Document.BeginUpdate(); + + string text = null; try { - text = Application.Current.Clipboard.GetTextAsync().GetAwaiter().GetResult(); + text = await Application.Current.Clipboard.GetTextAsync(); } catch (Exception) { + textArea.Document.EndUpdate(); return; } @@ -505,6 +506,8 @@ namespace AvaloniaEdit.Editing textArea.Caret.BringCaretToView(); args.Handled = true; + + textArea.Document.EndUpdate(); } }
10
fix paste from external app on linux.
7
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10067254
<NME> EditingCommandHandler.cs <BEF> // 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.Collections.Generic; using System.Globalization; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using Avalonia.Input; using AvaloniaEdit.Utils; namespace AvaloniaEdit.Editing { /// <summary> /// We re-use the CommandBinding and InputBinding instances between multiple text areas, /// so this class is static. /// </summary> internal class EditingCommandHandler { /// <summary> /// Creates a new <see cref="TextAreaInputHandler"/> for the text area. /// </summary> public static TextAreaInputHandler Create(TextArea textArea) { var handler = new TextAreaInputHandler(textArea); handler.CommandBindings.AddRange(CommandBindings); handler.KeyBindings.AddRange(KeyBindings); return handler; } private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>(); private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>(); private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler) { CommandBindings.Add(new RoutedCommandBinding(command, handler)); KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key)); } private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null) { CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler)); } static EditingCommandHandler() { AddBinding(EditingCommands.Delete, KeyModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight)); AddBinding(EditingCommands.DeleteNextWord, KeyModifiers.Control, Key.Delete, OnDelete(CaretMovementType.WordRight)); AddBinding(EditingCommands.Backspace, KeyModifiers.None, Key.Back, OnDelete(CaretMovementType.Backspace)); KeyBindings.Add( TextAreaDefaultInputHandler.CreateKeyBinding(EditingCommands.Backspace, KeyModifiers.Shift, Key.Back)); // make Shift-Backspace do the same as plain backspace AddBinding(EditingCommands.DeletePreviousWord, KeyModifiers.Control, Key.Back, OnDelete(CaretMovementType.WordLeft)); AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter); AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter); AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab); AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab); AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete); AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy); AddBinding(ApplicationCommands.Cut, OnCut, CanCut); AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste); AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike); AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine); AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace); AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace); AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase); AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase); AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase); AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase); AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces); AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs); AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces); AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs); AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection); } private static TextArea GetTextArea(object target) { return target as TextArea; } #region Text Transformation Helpers private enum DefaultSegmentType { WholeDocument, CurrentLine } /// <summary> /// Calls transformLine on all lines in the selected range. /// transformLine needs to handle read-only segments! /// </summary> private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target, ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { DocumentLine start, end; if (textArea.Selection.IsEmpty) { if (defaultSegmentType == DefaultSegmentType.CurrentLine) { start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line); } else if (defaultSegmentType == DefaultSegmentType.WholeDocument) { start = textArea.Document.Lines.First(); end = textArea.Document.Lines.Last(); } else { start = end = null; } } else { var segment = textArea.Selection.SurroundingSegment; start = textArea.Document.GetLineByOffset(segment.Offset); end = textArea.Document.GetLineByOffset(segment.EndOffset); // don't include the last line if no characters on it are selected if (start != end && end.Offset == segment.EndOffset) end = end.PreviousLine; } if (start != null) { transformLine(textArea, start); while (start != end) { start = start.NextLine; transformLine(textArea, start); } } } textArea.Caret.BringCaretToView(); args.Handled = true; } } /// <summary> /// Calls transformLine on all writable segment in the selected range. /// </summary> private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target, ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { IEnumerable<ISegment> segments; if (textArea.Selection.IsEmpty) { if (defaultSegmentType == DefaultSegmentType.CurrentLine) { segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) }; } else if (defaultSegmentType == DefaultSegmentType.WholeDocument) { segments = textArea.Document.Lines; } else { segments = null; } } else { segments = textArea.Selection.Segments; } if (segments != null) { foreach (var segment in segments.Reverse()) { foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse()) { transformSegment(textArea, writableSegment); } } } } textArea.Caret.BringCaretToView(); args.Handled = true; } } #endregion #region EnterLineBreak private static void OnEnter(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea != null && textArea.IsFocused) { textArea.PerformTextInput("\n"); args.Handled = true; } } #endregion #region Tab private static void OnTab(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { if (textArea.Selection.IsMultiline) { var segment = textArea.Selection.SurroundingSegment; var start = textArea.Document.GetLineByOffset(segment.Offset); var end = textArea.Document.GetLineByOffset(segment.EndOffset); // don't include the last line if no characters on it are selected if (start != end && end.Offset == segment.EndOffset) end = end.PreviousLine; var current = start; while (true) { var offset = current.Offset; if (textArea.ReadOnlySectionProvider.CanInsert(offset)) textArea.Document.Replace(offset, 0, textArea.Options.IndentationString, OffsetChangeMappingType.KeepAnchorBeforeInsertion); if (current == end) break; current = current.NextLine; } } else { var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column); textArea.ReplaceSelectionWithText(indentationString); } } textArea.Caret.BringCaretToView(); args.Handled = true; } } private static void OnShiftTab(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { var offset = line.Offset; var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset, textArea.Options.IndentationSize); if (s.Length > 0) { s = textArea.GetDeletableSegments(s).FirstOrDefault(); if (s != null && s.Length > 0) { textArea.Document.Remove(s.Offset, s.Length); } } }, target, args, DefaultSegmentType.CurrentLine); } #endregion #region Delete private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement) { return (target, args) => { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty) { var startPos = textArea.Caret.Position; var enableVirtualSpace = textArea.Options.EnableVirtualSpace; // When pressing delete; don't move the caret further into virtual space - instead delete the newline if (caretMovement == CaretMovementType.CharRight) enableVirtualSpace = false; var desiredXPos = textArea.Caret.DesiredXPos; var endPos = CaretNavigationCommandHandler.GetNewCaretPosition( textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos); // GetNewCaretPosition may return (0,0) as new position, // thus we need to validate endPos before using it in the selection. if (endPos.Line < 1 || endPos.Column < 1) endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1)); // Don't do anything if the number of lines of a rectangular selection would be changed by the deletion. if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line) return; // Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic // Reuse the existing selection, so that we continue using the same logic textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos) .ReplaceSelectionWithText(string.Empty); } else { textArea.RemoveSelectedText(); } textArea.Caret.BringCaretToView(); args.Handled = true; } }; } private static void CanDelete(object target, CanExecuteRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = true; args.Handled = true; } } #endregion #region Clipboard commands private static void CanCut(object target, CanExecuteRoutedEventArgs args) { // HasSomethingSelected for copy and cut commands var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly; args.Handled = true; } } private static void CanCopy(object target, CanExecuteRoutedEventArgs args) { // HasSomethingSelected for copy and cut commands var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty; args.Handled = true; } } private static void OnCopy(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine) { var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line); CopyWholeLine(textArea, currentLine); } else { CopySelectedText(textArea); } args.Handled = true; } } private static void OnCut(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine) { var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line); if (CopyWholeLine(textArea, currentLine)) { var segmentsToDelete = textArea.GetDeletableSegments( new SimpleSegment(currentLine.Offset, currentLine.TotalLength)); for (var i = segmentsToDelete.Length - 1; i >= 0; i--) { textArea.Document.Remove(segmentsToDelete[i]); } } } else { if (CopySelectedText(textArea)) textArea.RemoveSelectedText(); } textArea.Caret.BringCaretToView(); args.Handled = true; } } private static bool CopySelectedText(TextArea textArea) { var text = textArea.Selection.GetText(); text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); SetClipboardText(text); textArea.OnTextCopied(new TextEventArgs(text)); return true; } private static void SetClipboardText(string text) { try { Application.Current.Clipboard.SetTextAsync(text).GetAwaiter().GetResult(); } catch (Exception) { // Apparently this exception sometimes happens randomly. // The MS controls just ignore it, so we'll do the same. } } private static bool CopyWholeLine(TextArea textArea, DocumentLine line) { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); // Ignore empty line copy if(string.IsNullOrEmpty(text)) return false; // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); // TODO: formats //DataObject data = new DataObject(); //if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText)) // data.SetText(text); //// Also copy text in HTML format to clipboard - good for pasting text into Word //// or to the SharpDevelop forums. //if (ConfirmDataFormat(textArea, data, DataFormats.Html)) //{ // IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter; // HtmlClipboard.SetHtml(data, // HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine, // new HtmlOptions(textArea.Options))); //} //if (ConfirmDataFormat(textArea, data, LineSelectedType)) //{ // var lineSelected = new MemoryStream(1); // lineSelected.WriteByte(1); // data.SetData(LineSelectedType, lineSelected, false); //} //var copyingEventArgs = new DataObjectCopyingEventArgs(data, false); var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset) && !string.IsNullOrEmpty(Application.Current.Clipboard.GetTextAsync() .GetAwaiter() .GetResult()); args.Handled = true; } } private static void OnPaste(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { string text; try { text = Application.Current.Clipboard.GetTextAsync().GetAwaiter().GetResult(); } catch (Exception) { return; } string text = null; try { text = await Application.Current.Clipboard.GetTextAsync(); } catch (Exception) { textArea.Document.EndUpdate(); return; textArea.Caret.BringCaretToView(); args.Handled = true; } } if (!string.IsNullOrEmpty(text)) { textArea.ReplaceSelectionWithText(text); } textArea.Caret.BringCaretToView(); args.Handled = true; textArea.Document.EndUpdate(); } } internal static string GetTextToPaste(string text, TextArea textArea) { try { // Try retrieving the text as one of: // - the FormatToApply // - UnicodeText // - Text // (but don't try the same format twice) //if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply)) // text = (string)dataObject.GetData(pastingEventArgs.FormatToApply); //else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText && // dataObject.GetDataPresent(DataFormats.UnicodeText)) // text = (string)dataObject.GetData(DataFormats.UnicodeText); //else if (pastingEventArgs.FormatToApply != DataFormats.Text && // dataObject.GetDataPresent(DataFormats.Text)) // text = (string)dataObject.GetData(DataFormats.Text); //else // return null; // no text data format // convert text back to correct newlines for this document var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line); text = TextUtilities.NormalizeNewLines(text, newLine); text = textArea.Options.ConvertTabsToSpaces ? text.Replace("\t", new String(' ', textArea.Options.IndentationSize)) : text; return text; } catch (OutOfMemoryException) { // may happen when trying to paste a huge string return null; } } #endregion #region Toggle Overstrike private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea != null && textArea.Options.AllowToggleOverstrikeMode) textArea.OverstrikeMode = !textArea.OverstrikeMode; } #endregion #region DeleteLine private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { int firstLineIndex, lastLineIndex; if (textArea.Selection.Length == 0) { // There is no selection, simply delete current line firstLineIndex = lastLineIndex = textArea.Caret.Line; } else { // There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction) firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line, textArea.Selection.EndPosition.Line); lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line, textArea.Selection.EndPosition.Line); } var startLine = textArea.Document.GetLineByNumber(firstLineIndex); var endLine = textArea.Document.GetLineByNumber(lastLineIndex); textArea.Selection = Selection.Create(textArea, startLine.Offset, endLine.Offset + endLine.TotalLength); textArea.RemoveSelectedText(); args.Handled = true; } } #endregion #region Remove..Whitespace / Convert Tabs-Spaces private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment) { var document = textArea.Document; var endOffset = segment.EndOffset; var indentationString = new string(' ', textArea.Options.IndentationSize); for (var offset = segment.Offset; offset < endOffset; offset++) { if (document.GetCharAt(offset) == '\t') { document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace); endOffset += indentationString.Length - 1; } } } private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment) { var document = textArea.Document; var endOffset = segment.EndOffset; var indentationSize = textArea.Options.IndentationSize; var spacesCount = 0; for (var offset = segment.Offset; offset < endOffset; offset++) { if (document.GetCharAt(offset) == ' ') { spacesCount++; if (spacesCount == indentationSize) { document.Replace(offset - (indentationSize - 1), indentationSize, "\t", OffsetChangeMappingType.CharacterReplace); spacesCount = 0; offset -= indentationSize - 1; endOffset -= indentationSize - 1; } } else { spacesCount = 0; } } } #endregion #region Convert...Case private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments( delegate (TextArea textArea, ISegment segment) { var oldText = textArea.Document.GetText(segment); var newText = transformText(oldText); textArea.Document.Replace(segment.Offset, segment.Length, newText, OffsetChangeMappingType.CharacterReplace); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args); } private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args); } private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args) { throw new NotSupportedException(); //ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args); } private static void OnInvertCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(InvertCase, target, args); } private static string InvertCase(string text) { // TODO: culture //var culture = CultureInfo.CurrentCulture; var buffer = text.ToCharArray(); for (var i = 0; i < buffer.Length; ++i) { var c = buffer[i]; buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c); } return new string(buffer); } #endregion private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null && textArea.IndentationStrategy != null) { using (textArea.Document.RunUpdate()) { int start, end; if (textArea.Selection.IsEmpty) { start = 1; end = textArea.Document.LineCount; } else { start = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.Offset) .LineNumber; end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset) .LineNumber; } textArea.IndentationStrategy.IndentLines(textArea.Document, start, end); } textArea.Caret.BringCaretToView(); args.Handled = true; } } } } <MSG> fix paste from external app on linux. <DFF> @@ -24,6 +24,7 @@ using Avalonia; using AvaloniaEdit.Document; using Avalonia.Input; using AvaloniaEdit.Utils; +using System.Threading.Tasks; namespace AvaloniaEdit.Editing { @@ -469,26 +470,26 @@ namespace AvaloniaEdit.Editing var textArea = GetTextArea(target); if (textArea?.Document != null) { - args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset) - && !string.IsNullOrEmpty(Application.Current.Clipboard.GetTextAsync() - .GetAwaiter() - .GetResult()); + args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset); args.Handled = true; } } - private static void OnPaste(object target, ExecutedRoutedEventArgs args) + private static async void OnPaste(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { - string text; + textArea.Document.BeginUpdate(); + + string text = null; try { - text = Application.Current.Clipboard.GetTextAsync().GetAwaiter().GetResult(); + text = await Application.Current.Clipboard.GetTextAsync(); } catch (Exception) { + textArea.Document.EndUpdate(); return; } @@ -505,6 +506,8 @@ namespace AvaloniaEdit.Editing textArea.Caret.BringCaretToView(); args.Handled = true; + + textArea.Document.EndUpdate(); } }
10
fix paste from external app on linux.
7
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10067255
<NME> EditingCommandHandler.cs <BEF> // 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.Collections.Generic; using System.Globalization; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using Avalonia.Input; using AvaloniaEdit.Utils; namespace AvaloniaEdit.Editing { /// <summary> /// We re-use the CommandBinding and InputBinding instances between multiple text areas, /// so this class is static. /// </summary> internal class EditingCommandHandler { /// <summary> /// Creates a new <see cref="TextAreaInputHandler"/> for the text area. /// </summary> public static TextAreaInputHandler Create(TextArea textArea) { var handler = new TextAreaInputHandler(textArea); handler.CommandBindings.AddRange(CommandBindings); handler.KeyBindings.AddRange(KeyBindings); return handler; } private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>(); private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>(); private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler) { CommandBindings.Add(new RoutedCommandBinding(command, handler)); KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key)); } private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null) { CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler)); } static EditingCommandHandler() { AddBinding(EditingCommands.Delete, KeyModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight)); AddBinding(EditingCommands.DeleteNextWord, KeyModifiers.Control, Key.Delete, OnDelete(CaretMovementType.WordRight)); AddBinding(EditingCommands.Backspace, KeyModifiers.None, Key.Back, OnDelete(CaretMovementType.Backspace)); KeyBindings.Add( TextAreaDefaultInputHandler.CreateKeyBinding(EditingCommands.Backspace, KeyModifiers.Shift, Key.Back)); // make Shift-Backspace do the same as plain backspace AddBinding(EditingCommands.DeletePreviousWord, KeyModifiers.Control, Key.Back, OnDelete(CaretMovementType.WordLeft)); AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter); AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter); AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab); AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab); AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete); AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy); AddBinding(ApplicationCommands.Cut, OnCut, CanCut); AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste); AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike); AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine); AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace); AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace); AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase); AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase); AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase); AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase); AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces); AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs); AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces); AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs); AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection); } private static TextArea GetTextArea(object target) { return target as TextArea; } #region Text Transformation Helpers private enum DefaultSegmentType { WholeDocument, CurrentLine } /// <summary> /// Calls transformLine on all lines in the selected range. /// transformLine needs to handle read-only segments! /// </summary> private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target, ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { DocumentLine start, end; if (textArea.Selection.IsEmpty) { if (defaultSegmentType == DefaultSegmentType.CurrentLine) { start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line); } else if (defaultSegmentType == DefaultSegmentType.WholeDocument) { start = textArea.Document.Lines.First(); end = textArea.Document.Lines.Last(); } else { start = end = null; } } else { var segment = textArea.Selection.SurroundingSegment; start = textArea.Document.GetLineByOffset(segment.Offset); end = textArea.Document.GetLineByOffset(segment.EndOffset); // don't include the last line if no characters on it are selected if (start != end && end.Offset == segment.EndOffset) end = end.PreviousLine; } if (start != null) { transformLine(textArea, start); while (start != end) { start = start.NextLine; transformLine(textArea, start); } } } textArea.Caret.BringCaretToView(); args.Handled = true; } } /// <summary> /// Calls transformLine on all writable segment in the selected range. /// </summary> private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target, ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { IEnumerable<ISegment> segments; if (textArea.Selection.IsEmpty) { if (defaultSegmentType == DefaultSegmentType.CurrentLine) { segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) }; } else if (defaultSegmentType == DefaultSegmentType.WholeDocument) { segments = textArea.Document.Lines; } else { segments = null; } } else { segments = textArea.Selection.Segments; } if (segments != null) { foreach (var segment in segments.Reverse()) { foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse()) { transformSegment(textArea, writableSegment); } } } } textArea.Caret.BringCaretToView(); args.Handled = true; } } #endregion #region EnterLineBreak private static void OnEnter(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea != null && textArea.IsFocused) { textArea.PerformTextInput("\n"); args.Handled = true; } } #endregion #region Tab private static void OnTab(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { if (textArea.Selection.IsMultiline) { var segment = textArea.Selection.SurroundingSegment; var start = textArea.Document.GetLineByOffset(segment.Offset); var end = textArea.Document.GetLineByOffset(segment.EndOffset); // don't include the last line if no characters on it are selected if (start != end && end.Offset == segment.EndOffset) end = end.PreviousLine; var current = start; while (true) { var offset = current.Offset; if (textArea.ReadOnlySectionProvider.CanInsert(offset)) textArea.Document.Replace(offset, 0, textArea.Options.IndentationString, OffsetChangeMappingType.KeepAnchorBeforeInsertion); if (current == end) break; current = current.NextLine; } } else { var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column); textArea.ReplaceSelectionWithText(indentationString); } } textArea.Caret.BringCaretToView(); args.Handled = true; } } private static void OnShiftTab(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { var offset = line.Offset; var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset, textArea.Options.IndentationSize); if (s.Length > 0) { s = textArea.GetDeletableSegments(s).FirstOrDefault(); if (s != null && s.Length > 0) { textArea.Document.Remove(s.Offset, s.Length); } } }, target, args, DefaultSegmentType.CurrentLine); } #endregion #region Delete private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement) { return (target, args) => { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty) { var startPos = textArea.Caret.Position; var enableVirtualSpace = textArea.Options.EnableVirtualSpace; // When pressing delete; don't move the caret further into virtual space - instead delete the newline if (caretMovement == CaretMovementType.CharRight) enableVirtualSpace = false; var desiredXPos = textArea.Caret.DesiredXPos; var endPos = CaretNavigationCommandHandler.GetNewCaretPosition( textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos); // GetNewCaretPosition may return (0,0) as new position, // thus we need to validate endPos before using it in the selection. if (endPos.Line < 1 || endPos.Column < 1) endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1)); // Don't do anything if the number of lines of a rectangular selection would be changed by the deletion. if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line) return; // Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic // Reuse the existing selection, so that we continue using the same logic textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos) .ReplaceSelectionWithText(string.Empty); } else { textArea.RemoveSelectedText(); } textArea.Caret.BringCaretToView(); args.Handled = true; } }; } private static void CanDelete(object target, CanExecuteRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = true; args.Handled = true; } } #endregion #region Clipboard commands private static void CanCut(object target, CanExecuteRoutedEventArgs args) { // HasSomethingSelected for copy and cut commands var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly; args.Handled = true; } } private static void CanCopy(object target, CanExecuteRoutedEventArgs args) { // HasSomethingSelected for copy and cut commands var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty; args.Handled = true; } } private static void OnCopy(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine) { var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line); CopyWholeLine(textArea, currentLine); } else { CopySelectedText(textArea); } args.Handled = true; } } private static void OnCut(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine) { var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line); if (CopyWholeLine(textArea, currentLine)) { var segmentsToDelete = textArea.GetDeletableSegments( new SimpleSegment(currentLine.Offset, currentLine.TotalLength)); for (var i = segmentsToDelete.Length - 1; i >= 0; i--) { textArea.Document.Remove(segmentsToDelete[i]); } } } else { if (CopySelectedText(textArea)) textArea.RemoveSelectedText(); } textArea.Caret.BringCaretToView(); args.Handled = true; } } private static bool CopySelectedText(TextArea textArea) { var text = textArea.Selection.GetText(); text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); SetClipboardText(text); textArea.OnTextCopied(new TextEventArgs(text)); return true; } private static void SetClipboardText(string text) { try { Application.Current.Clipboard.SetTextAsync(text).GetAwaiter().GetResult(); } catch (Exception) { // Apparently this exception sometimes happens randomly. // The MS controls just ignore it, so we'll do the same. } } private static bool CopyWholeLine(TextArea textArea, DocumentLine line) { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); // Ignore empty line copy if(string.IsNullOrEmpty(text)) return false; // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); // TODO: formats //DataObject data = new DataObject(); //if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText)) // data.SetText(text); //// Also copy text in HTML format to clipboard - good for pasting text into Word //// or to the SharpDevelop forums. //if (ConfirmDataFormat(textArea, data, DataFormats.Html)) //{ // IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter; // HtmlClipboard.SetHtml(data, // HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine, // new HtmlOptions(textArea.Options))); //} //if (ConfirmDataFormat(textArea, data, LineSelectedType)) //{ // var lineSelected = new MemoryStream(1); // lineSelected.WriteByte(1); // data.SetData(LineSelectedType, lineSelected, false); //} //var copyingEventArgs = new DataObjectCopyingEventArgs(data, false); var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset) && !string.IsNullOrEmpty(Application.Current.Clipboard.GetTextAsync() .GetAwaiter() .GetResult()); args.Handled = true; } } private static void OnPaste(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { string text; try { text = Application.Current.Clipboard.GetTextAsync().GetAwaiter().GetResult(); } catch (Exception) { return; } string text = null; try { text = await Application.Current.Clipboard.GetTextAsync(); } catch (Exception) { textArea.Document.EndUpdate(); return; textArea.Caret.BringCaretToView(); args.Handled = true; } } if (!string.IsNullOrEmpty(text)) { textArea.ReplaceSelectionWithText(text); } textArea.Caret.BringCaretToView(); args.Handled = true; textArea.Document.EndUpdate(); } } internal static string GetTextToPaste(string text, TextArea textArea) { try { // Try retrieving the text as one of: // - the FormatToApply // - UnicodeText // - Text // (but don't try the same format twice) //if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply)) // text = (string)dataObject.GetData(pastingEventArgs.FormatToApply); //else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText && // dataObject.GetDataPresent(DataFormats.UnicodeText)) // text = (string)dataObject.GetData(DataFormats.UnicodeText); //else if (pastingEventArgs.FormatToApply != DataFormats.Text && // dataObject.GetDataPresent(DataFormats.Text)) // text = (string)dataObject.GetData(DataFormats.Text); //else // return null; // no text data format // convert text back to correct newlines for this document var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line); text = TextUtilities.NormalizeNewLines(text, newLine); text = textArea.Options.ConvertTabsToSpaces ? text.Replace("\t", new String(' ', textArea.Options.IndentationSize)) : text; return text; } catch (OutOfMemoryException) { // may happen when trying to paste a huge string return null; } } #endregion #region Toggle Overstrike private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea != null && textArea.Options.AllowToggleOverstrikeMode) textArea.OverstrikeMode = !textArea.OverstrikeMode; } #endregion #region DeleteLine private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { int firstLineIndex, lastLineIndex; if (textArea.Selection.Length == 0) { // There is no selection, simply delete current line firstLineIndex = lastLineIndex = textArea.Caret.Line; } else { // There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction) firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line, textArea.Selection.EndPosition.Line); lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line, textArea.Selection.EndPosition.Line); } var startLine = textArea.Document.GetLineByNumber(firstLineIndex); var endLine = textArea.Document.GetLineByNumber(lastLineIndex); textArea.Selection = Selection.Create(textArea, startLine.Offset, endLine.Offset + endLine.TotalLength); textArea.RemoveSelectedText(); args.Handled = true; } } #endregion #region Remove..Whitespace / Convert Tabs-Spaces private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment) { var document = textArea.Document; var endOffset = segment.EndOffset; var indentationString = new string(' ', textArea.Options.IndentationSize); for (var offset = segment.Offset; offset < endOffset; offset++) { if (document.GetCharAt(offset) == '\t') { document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace); endOffset += indentationString.Length - 1; } } } private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment) { var document = textArea.Document; var endOffset = segment.EndOffset; var indentationSize = textArea.Options.IndentationSize; var spacesCount = 0; for (var offset = segment.Offset; offset < endOffset; offset++) { if (document.GetCharAt(offset) == ' ') { spacesCount++; if (spacesCount == indentationSize) { document.Replace(offset - (indentationSize - 1), indentationSize, "\t", OffsetChangeMappingType.CharacterReplace); spacesCount = 0; offset -= indentationSize - 1; endOffset -= indentationSize - 1; } } else { spacesCount = 0; } } } #endregion #region Convert...Case private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments( delegate (TextArea textArea, ISegment segment) { var oldText = textArea.Document.GetText(segment); var newText = transformText(oldText); textArea.Document.Replace(segment.Offset, segment.Length, newText, OffsetChangeMappingType.CharacterReplace); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args); } private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args); } private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args) { throw new NotSupportedException(); //ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args); } private static void OnInvertCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(InvertCase, target, args); } private static string InvertCase(string text) { // TODO: culture //var culture = CultureInfo.CurrentCulture; var buffer = text.ToCharArray(); for (var i = 0; i < buffer.Length; ++i) { var c = buffer[i]; buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c); } return new string(buffer); } #endregion private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null && textArea.IndentationStrategy != null) { using (textArea.Document.RunUpdate()) { int start, end; if (textArea.Selection.IsEmpty) { start = 1; end = textArea.Document.LineCount; } else { start = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.Offset) .LineNumber; end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset) .LineNumber; } textArea.IndentationStrategy.IndentLines(textArea.Document, start, end); } textArea.Caret.BringCaretToView(); args.Handled = true; } } } } <MSG> fix paste from external app on linux. <DFF> @@ -24,6 +24,7 @@ using Avalonia; using AvaloniaEdit.Document; using Avalonia.Input; using AvaloniaEdit.Utils; +using System.Threading.Tasks; namespace AvaloniaEdit.Editing { @@ -469,26 +470,26 @@ namespace AvaloniaEdit.Editing var textArea = GetTextArea(target); if (textArea?.Document != null) { - args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset) - && !string.IsNullOrEmpty(Application.Current.Clipboard.GetTextAsync() - .GetAwaiter() - .GetResult()); + args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset); args.Handled = true; } } - private static void OnPaste(object target, ExecutedRoutedEventArgs args) + private static async void OnPaste(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { - string text; + textArea.Document.BeginUpdate(); + + string text = null; try { - text = Application.Current.Clipboard.GetTextAsync().GetAwaiter().GetResult(); + text = await Application.Current.Clipboard.GetTextAsync(); } catch (Exception) { + textArea.Document.EndUpdate(); return; } @@ -505,6 +506,8 @@ namespace AvaloniaEdit.Editing textArea.Caret.BringCaretToView(); args.Handled = true; + + textArea.Document.EndUpdate(); } }
10
fix paste from external app on linux.
7
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10067256
<NME> EditingCommandHandler.cs <BEF> // 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.Collections.Generic; using System.Globalization; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using Avalonia.Input; using AvaloniaEdit.Utils; namespace AvaloniaEdit.Editing { /// <summary> /// We re-use the CommandBinding and InputBinding instances between multiple text areas, /// so this class is static. /// </summary> internal class EditingCommandHandler { /// <summary> /// Creates a new <see cref="TextAreaInputHandler"/> for the text area. /// </summary> public static TextAreaInputHandler Create(TextArea textArea) { var handler = new TextAreaInputHandler(textArea); handler.CommandBindings.AddRange(CommandBindings); handler.KeyBindings.AddRange(KeyBindings); return handler; } private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>(); private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>(); private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler) { CommandBindings.Add(new RoutedCommandBinding(command, handler)); KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key)); } private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null) { CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler)); } static EditingCommandHandler() { AddBinding(EditingCommands.Delete, KeyModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight)); AddBinding(EditingCommands.DeleteNextWord, KeyModifiers.Control, Key.Delete, OnDelete(CaretMovementType.WordRight)); AddBinding(EditingCommands.Backspace, KeyModifiers.None, Key.Back, OnDelete(CaretMovementType.Backspace)); KeyBindings.Add( TextAreaDefaultInputHandler.CreateKeyBinding(EditingCommands.Backspace, KeyModifiers.Shift, Key.Back)); // make Shift-Backspace do the same as plain backspace AddBinding(EditingCommands.DeletePreviousWord, KeyModifiers.Control, Key.Back, OnDelete(CaretMovementType.WordLeft)); AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter); AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter); AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab); AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab); AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete); AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy); AddBinding(ApplicationCommands.Cut, OnCut, CanCut); AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste); AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike); AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine); AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace); AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace); AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase); AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase); AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase); AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase); AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces); AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs); AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces); AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs); AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection); } private static TextArea GetTextArea(object target) { return target as TextArea; } #region Text Transformation Helpers private enum DefaultSegmentType { WholeDocument, CurrentLine } /// <summary> /// Calls transformLine on all lines in the selected range. /// transformLine needs to handle read-only segments! /// </summary> private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target, ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { DocumentLine start, end; if (textArea.Selection.IsEmpty) { if (defaultSegmentType == DefaultSegmentType.CurrentLine) { start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line); } else if (defaultSegmentType == DefaultSegmentType.WholeDocument) { start = textArea.Document.Lines.First(); end = textArea.Document.Lines.Last(); } else { start = end = null; } } else { var segment = textArea.Selection.SurroundingSegment; start = textArea.Document.GetLineByOffset(segment.Offset); end = textArea.Document.GetLineByOffset(segment.EndOffset); // don't include the last line if no characters on it are selected if (start != end && end.Offset == segment.EndOffset) end = end.PreviousLine; } if (start != null) { transformLine(textArea, start); while (start != end) { start = start.NextLine; transformLine(textArea, start); } } } textArea.Caret.BringCaretToView(); args.Handled = true; } } /// <summary> /// Calls transformLine on all writable segment in the selected range. /// </summary> private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target, ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { IEnumerable<ISegment> segments; if (textArea.Selection.IsEmpty) { if (defaultSegmentType == DefaultSegmentType.CurrentLine) { segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) }; } else if (defaultSegmentType == DefaultSegmentType.WholeDocument) { segments = textArea.Document.Lines; } else { segments = null; } } else { segments = textArea.Selection.Segments; } if (segments != null) { foreach (var segment in segments.Reverse()) { foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse()) { transformSegment(textArea, writableSegment); } } } } textArea.Caret.BringCaretToView(); args.Handled = true; } } #endregion #region EnterLineBreak private static void OnEnter(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea != null && textArea.IsFocused) { textArea.PerformTextInput("\n"); args.Handled = true; } } #endregion #region Tab private static void OnTab(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { if (textArea.Selection.IsMultiline) { var segment = textArea.Selection.SurroundingSegment; var start = textArea.Document.GetLineByOffset(segment.Offset); var end = textArea.Document.GetLineByOffset(segment.EndOffset); // don't include the last line if no characters on it are selected if (start != end && end.Offset == segment.EndOffset) end = end.PreviousLine; var current = start; while (true) { var offset = current.Offset; if (textArea.ReadOnlySectionProvider.CanInsert(offset)) textArea.Document.Replace(offset, 0, textArea.Options.IndentationString, OffsetChangeMappingType.KeepAnchorBeforeInsertion); if (current == end) break; current = current.NextLine; } } else { var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column); textArea.ReplaceSelectionWithText(indentationString); } } textArea.Caret.BringCaretToView(); args.Handled = true; } } private static void OnShiftTab(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { var offset = line.Offset; var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset, textArea.Options.IndentationSize); if (s.Length > 0) { s = textArea.GetDeletableSegments(s).FirstOrDefault(); if (s != null && s.Length > 0) { textArea.Document.Remove(s.Offset, s.Length); } } }, target, args, DefaultSegmentType.CurrentLine); } #endregion #region Delete private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement) { return (target, args) => { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty) { var startPos = textArea.Caret.Position; var enableVirtualSpace = textArea.Options.EnableVirtualSpace; // When pressing delete; don't move the caret further into virtual space - instead delete the newline if (caretMovement == CaretMovementType.CharRight) enableVirtualSpace = false; var desiredXPos = textArea.Caret.DesiredXPos; var endPos = CaretNavigationCommandHandler.GetNewCaretPosition( textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos); // GetNewCaretPosition may return (0,0) as new position, // thus we need to validate endPos before using it in the selection. if (endPos.Line < 1 || endPos.Column < 1) endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1)); // Don't do anything if the number of lines of a rectangular selection would be changed by the deletion. if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line) return; // Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic // Reuse the existing selection, so that we continue using the same logic textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos) .ReplaceSelectionWithText(string.Empty); } else { textArea.RemoveSelectedText(); } textArea.Caret.BringCaretToView(); args.Handled = true; } }; } private static void CanDelete(object target, CanExecuteRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = true; args.Handled = true; } } #endregion #region Clipboard commands private static void CanCut(object target, CanExecuteRoutedEventArgs args) { // HasSomethingSelected for copy and cut commands var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly; args.Handled = true; } } private static void CanCopy(object target, CanExecuteRoutedEventArgs args) { // HasSomethingSelected for copy and cut commands var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty; args.Handled = true; } } private static void OnCopy(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine) { var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line); CopyWholeLine(textArea, currentLine); } else { CopySelectedText(textArea); } args.Handled = true; } } private static void OnCut(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine) { var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line); if (CopyWholeLine(textArea, currentLine)) { var segmentsToDelete = textArea.GetDeletableSegments( new SimpleSegment(currentLine.Offset, currentLine.TotalLength)); for (var i = segmentsToDelete.Length - 1; i >= 0; i--) { textArea.Document.Remove(segmentsToDelete[i]); } } } else { if (CopySelectedText(textArea)) textArea.RemoveSelectedText(); } textArea.Caret.BringCaretToView(); args.Handled = true; } } private static bool CopySelectedText(TextArea textArea) { var text = textArea.Selection.GetText(); text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); SetClipboardText(text); textArea.OnTextCopied(new TextEventArgs(text)); return true; } private static void SetClipboardText(string text) { try { Application.Current.Clipboard.SetTextAsync(text).GetAwaiter().GetResult(); } catch (Exception) { // Apparently this exception sometimes happens randomly. // The MS controls just ignore it, so we'll do the same. } } private static bool CopyWholeLine(TextArea textArea, DocumentLine line) { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); // Ignore empty line copy if(string.IsNullOrEmpty(text)) return false; // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); // TODO: formats //DataObject data = new DataObject(); //if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText)) // data.SetText(text); //// Also copy text in HTML format to clipboard - good for pasting text into Word //// or to the SharpDevelop forums. //if (ConfirmDataFormat(textArea, data, DataFormats.Html)) //{ // IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter; // HtmlClipboard.SetHtml(data, // HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine, // new HtmlOptions(textArea.Options))); //} //if (ConfirmDataFormat(textArea, data, LineSelectedType)) //{ // var lineSelected = new MemoryStream(1); // lineSelected.WriteByte(1); // data.SetData(LineSelectedType, lineSelected, false); //} //var copyingEventArgs = new DataObjectCopyingEventArgs(data, false); var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset) && !string.IsNullOrEmpty(Application.Current.Clipboard.GetTextAsync() .GetAwaiter() .GetResult()); args.Handled = true; } } private static void OnPaste(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { string text; try { text = Application.Current.Clipboard.GetTextAsync().GetAwaiter().GetResult(); } catch (Exception) { return; } string text = null; try { text = await Application.Current.Clipboard.GetTextAsync(); } catch (Exception) { textArea.Document.EndUpdate(); return; textArea.Caret.BringCaretToView(); args.Handled = true; } } if (!string.IsNullOrEmpty(text)) { textArea.ReplaceSelectionWithText(text); } textArea.Caret.BringCaretToView(); args.Handled = true; textArea.Document.EndUpdate(); } } internal static string GetTextToPaste(string text, TextArea textArea) { try { // Try retrieving the text as one of: // - the FormatToApply // - UnicodeText // - Text // (but don't try the same format twice) //if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply)) // text = (string)dataObject.GetData(pastingEventArgs.FormatToApply); //else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText && // dataObject.GetDataPresent(DataFormats.UnicodeText)) // text = (string)dataObject.GetData(DataFormats.UnicodeText); //else if (pastingEventArgs.FormatToApply != DataFormats.Text && // dataObject.GetDataPresent(DataFormats.Text)) // text = (string)dataObject.GetData(DataFormats.Text); //else // return null; // no text data format // convert text back to correct newlines for this document var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line); text = TextUtilities.NormalizeNewLines(text, newLine); text = textArea.Options.ConvertTabsToSpaces ? text.Replace("\t", new String(' ', textArea.Options.IndentationSize)) : text; return text; } catch (OutOfMemoryException) { // may happen when trying to paste a huge string return null; } } #endregion #region Toggle Overstrike private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea != null && textArea.Options.AllowToggleOverstrikeMode) textArea.OverstrikeMode = !textArea.OverstrikeMode; } #endregion #region DeleteLine private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { int firstLineIndex, lastLineIndex; if (textArea.Selection.Length == 0) { // There is no selection, simply delete current line firstLineIndex = lastLineIndex = textArea.Caret.Line; } else { // There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction) firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line, textArea.Selection.EndPosition.Line); lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line, textArea.Selection.EndPosition.Line); } var startLine = textArea.Document.GetLineByNumber(firstLineIndex); var endLine = textArea.Document.GetLineByNumber(lastLineIndex); textArea.Selection = Selection.Create(textArea, startLine.Offset, endLine.Offset + endLine.TotalLength); textArea.RemoveSelectedText(); args.Handled = true; } } #endregion #region Remove..Whitespace / Convert Tabs-Spaces private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment) { var document = textArea.Document; var endOffset = segment.EndOffset; var indentationString = new string(' ', textArea.Options.IndentationSize); for (var offset = segment.Offset; offset < endOffset; offset++) { if (document.GetCharAt(offset) == '\t') { document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace); endOffset += indentationString.Length - 1; } } } private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment) { var document = textArea.Document; var endOffset = segment.EndOffset; var indentationSize = textArea.Options.IndentationSize; var spacesCount = 0; for (var offset = segment.Offset; offset < endOffset; offset++) { if (document.GetCharAt(offset) == ' ') { spacesCount++; if (spacesCount == indentationSize) { document.Replace(offset - (indentationSize - 1), indentationSize, "\t", OffsetChangeMappingType.CharacterReplace); spacesCount = 0; offset -= indentationSize - 1; endOffset -= indentationSize - 1; } } else { spacesCount = 0; } } } #endregion #region Convert...Case private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments( delegate (TextArea textArea, ISegment segment) { var oldText = textArea.Document.GetText(segment); var newText = transformText(oldText); textArea.Document.Replace(segment.Offset, segment.Length, newText, OffsetChangeMappingType.CharacterReplace); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args); } private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args); } private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args) { throw new NotSupportedException(); //ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args); } private static void OnInvertCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(InvertCase, target, args); } private static string InvertCase(string text) { // TODO: culture //var culture = CultureInfo.CurrentCulture; var buffer = text.ToCharArray(); for (var i = 0; i < buffer.Length; ++i) { var c = buffer[i]; buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c); } return new string(buffer); } #endregion private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null && textArea.IndentationStrategy != null) { using (textArea.Document.RunUpdate()) { int start, end; if (textArea.Selection.IsEmpty) { start = 1; end = textArea.Document.LineCount; } else { start = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.Offset) .LineNumber; end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset) .LineNumber; } textArea.IndentationStrategy.IndentLines(textArea.Document, start, end); } textArea.Caret.BringCaretToView(); args.Handled = true; } } } } <MSG> fix paste from external app on linux. <DFF> @@ -24,6 +24,7 @@ using Avalonia; using AvaloniaEdit.Document; using Avalonia.Input; using AvaloniaEdit.Utils; +using System.Threading.Tasks; namespace AvaloniaEdit.Editing { @@ -469,26 +470,26 @@ namespace AvaloniaEdit.Editing var textArea = GetTextArea(target); if (textArea?.Document != null) { - args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset) - && !string.IsNullOrEmpty(Application.Current.Clipboard.GetTextAsync() - .GetAwaiter() - .GetResult()); + args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset); args.Handled = true; } } - private static void OnPaste(object target, ExecutedRoutedEventArgs args) + private static async void OnPaste(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { - string text; + textArea.Document.BeginUpdate(); + + string text = null; try { - text = Application.Current.Clipboard.GetTextAsync().GetAwaiter().GetResult(); + text = await Application.Current.Clipboard.GetTextAsync(); } catch (Exception) { + textArea.Document.EndUpdate(); return; } @@ -505,6 +506,8 @@ namespace AvaloniaEdit.Editing textArea.Caret.BringCaretToView(); args.Handled = true; + + textArea.Document.EndUpdate(); } }
10
fix paste from external app on linux.
7
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10067257
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public class TextEditorModel : AbstractLineList, IDisposable { private readonly TextDocument _document; private readonly TextView _textView; private DocumentSnapshot _documentSnapshot; private Action<Exception> _exceptionHandler; private InvalidLineRange _invalidRange; public DocumentSnapshot DocumentSnapshot { get { return _documentSnapshot; } } internal InvalidLineRange InvalidRange { get { return _invalidRange; } } public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler) { _textView = textView; _document = document; _exceptionHandler = exceptionHandler; _documentSnapshot = new DocumentSnapshot(_document); for (int i = 0; i < _document.LineCount; i++) AddLine(i); _document.Changing += DocumentOnChanging; _document.Changed += DocumentOnChanged; _document.UpdateFinished += DocumentOnUpdateFinished; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } public override void Dispose() { _document.Changing -= DocumentOnChanging; _document.Changed -= DocumentOnChanged; _document.UpdateFinished -= DocumentOnUpdateFinished; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public override void UpdateLine(int lineIndex) { } public void InvalidateViewPortLines() { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; InvalidateLineRange( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { return _documentSnapshot.GetLineLength(lineIndex); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { try { TokenizeViewPort(); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanging(object sender, DocumentChangeEventArgs e) { try { if (e.RemovalLength > 0) { var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1; for (int i = endLine; i > startLine; i--) { RemoveLine(i); } _documentSnapshot.RemoveLines(startLine, endLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanged(object sender, DocumentChangeEventArgs e) { try { int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; int endLine = startLine; if (e.InsertionLength > 0) { endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { AddLine(i); } } _documentSnapshot.Update(e); if (startLine == 0) { SetInvalidRange(startLine, endLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too SetInvalidRange(startLine - 1, endLine); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { InvalidateLineRange(startLine, endLine); return; } // we're in a document change, store the max invalid range if (_invalidRange == null) { _invalidRange = new InvalidLineRange(startLine, endLine); return; } _invalidRange.SetInvalidRange(startLine, endLine); } void DocumentOnUpdateFinished(object sender, EventArgs e) { if (_invalidRange == null) _invalidRange = null; } void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => { { _invalidRange = null; } } private void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, DispatcherPriority.MinValue); } internal class InvalidLineRange { internal int StartLine { get; private set; } internal int EndLine { get; private set; } internal InvalidLineRange(int startLine, int endLine) { StartLine = startLine; EndLine = endLine; } internal void SetInvalidRange(int startLine, int endLine) { if (startLine < StartLine) StartLine = startLine; if (endLine > EndLine) EndLine = endLine; } } } } <MSG> Add private modifiers <DFF> @@ -143,7 +143,7 @@ namespace AvaloniaEdit.TextMate } } - void SetInvalidRange(int startLine, int endLine) + private void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { @@ -167,7 +167,7 @@ namespace AvaloniaEdit.TextMate _invalidRange = null; } - void TokenizeViewPort() + private void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => {
2
Add private modifiers
2
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10067258
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public class TextEditorModel : AbstractLineList, IDisposable { private readonly TextDocument _document; private readonly TextView _textView; private DocumentSnapshot _documentSnapshot; private Action<Exception> _exceptionHandler; private InvalidLineRange _invalidRange; public DocumentSnapshot DocumentSnapshot { get { return _documentSnapshot; } } internal InvalidLineRange InvalidRange { get { return _invalidRange; } } public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler) { _textView = textView; _document = document; _exceptionHandler = exceptionHandler; _documentSnapshot = new DocumentSnapshot(_document); for (int i = 0; i < _document.LineCount; i++) AddLine(i); _document.Changing += DocumentOnChanging; _document.Changed += DocumentOnChanged; _document.UpdateFinished += DocumentOnUpdateFinished; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } public override void Dispose() { _document.Changing -= DocumentOnChanging; _document.Changed -= DocumentOnChanged; _document.UpdateFinished -= DocumentOnUpdateFinished; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public override void UpdateLine(int lineIndex) { } public void InvalidateViewPortLines() { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; InvalidateLineRange( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { return _documentSnapshot.GetLineLength(lineIndex); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { try { TokenizeViewPort(); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanging(object sender, DocumentChangeEventArgs e) { try { if (e.RemovalLength > 0) { var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1; for (int i = endLine; i > startLine; i--) { RemoveLine(i); } _documentSnapshot.RemoveLines(startLine, endLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanged(object sender, DocumentChangeEventArgs e) { try { int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; int endLine = startLine; if (e.InsertionLength > 0) { endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { AddLine(i); } } _documentSnapshot.Update(e); if (startLine == 0) { SetInvalidRange(startLine, endLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too SetInvalidRange(startLine - 1, endLine); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { InvalidateLineRange(startLine, endLine); return; } // we're in a document change, store the max invalid range if (_invalidRange == null) { _invalidRange = new InvalidLineRange(startLine, endLine); return; } _invalidRange.SetInvalidRange(startLine, endLine); } void DocumentOnUpdateFinished(object sender, EventArgs e) { if (_invalidRange == null) _invalidRange = null; } void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => { { _invalidRange = null; } } private void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, DispatcherPriority.MinValue); } internal class InvalidLineRange { internal int StartLine { get; private set; } internal int EndLine { get; private set; } internal InvalidLineRange(int startLine, int endLine) { StartLine = startLine; EndLine = endLine; } internal void SetInvalidRange(int startLine, int endLine) { if (startLine < StartLine) StartLine = startLine; if (endLine > EndLine) EndLine = endLine; } } } } <MSG> Add private modifiers <DFF> @@ -143,7 +143,7 @@ namespace AvaloniaEdit.TextMate } } - void SetInvalidRange(int startLine, int endLine) + private void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { @@ -167,7 +167,7 @@ namespace AvaloniaEdit.TextMate _invalidRange = null; } - void TokenizeViewPort() + private void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => {
2
Add private modifiers
2
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10067259
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public class TextEditorModel : AbstractLineList, IDisposable { private readonly TextDocument _document; private readonly TextView _textView; private DocumentSnapshot _documentSnapshot; private Action<Exception> _exceptionHandler; private InvalidLineRange _invalidRange; public DocumentSnapshot DocumentSnapshot { get { return _documentSnapshot; } } internal InvalidLineRange InvalidRange { get { return _invalidRange; } } public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler) { _textView = textView; _document = document; _exceptionHandler = exceptionHandler; _documentSnapshot = new DocumentSnapshot(_document); for (int i = 0; i < _document.LineCount; i++) AddLine(i); _document.Changing += DocumentOnChanging; _document.Changed += DocumentOnChanged; _document.UpdateFinished += DocumentOnUpdateFinished; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } public override void Dispose() { _document.Changing -= DocumentOnChanging; _document.Changed -= DocumentOnChanged; _document.UpdateFinished -= DocumentOnUpdateFinished; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public override void UpdateLine(int lineIndex) { } public void InvalidateViewPortLines() { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; InvalidateLineRange( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { return _documentSnapshot.GetLineLength(lineIndex); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { try { TokenizeViewPort(); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanging(object sender, DocumentChangeEventArgs e) { try { if (e.RemovalLength > 0) { var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1; for (int i = endLine; i > startLine; i--) { RemoveLine(i); } _documentSnapshot.RemoveLines(startLine, endLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanged(object sender, DocumentChangeEventArgs e) { try { int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; int endLine = startLine; if (e.InsertionLength > 0) { endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { AddLine(i); } } _documentSnapshot.Update(e); if (startLine == 0) { SetInvalidRange(startLine, endLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too SetInvalidRange(startLine - 1, endLine); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { InvalidateLineRange(startLine, endLine); return; } // we're in a document change, store the max invalid range if (_invalidRange == null) { _invalidRange = new InvalidLineRange(startLine, endLine); return; } _invalidRange.SetInvalidRange(startLine, endLine); } void DocumentOnUpdateFinished(object sender, EventArgs e) { if (_invalidRange == null) _invalidRange = null; } void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => { { _invalidRange = null; } } private void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, DispatcherPriority.MinValue); } internal class InvalidLineRange { internal int StartLine { get; private set; } internal int EndLine { get; private set; } internal InvalidLineRange(int startLine, int endLine) { StartLine = startLine; EndLine = endLine; } internal void SetInvalidRange(int startLine, int endLine) { if (startLine < StartLine) StartLine = startLine; if (endLine > EndLine) EndLine = endLine; } } } } <MSG> Add private modifiers <DFF> @@ -143,7 +143,7 @@ namespace AvaloniaEdit.TextMate } } - void SetInvalidRange(int startLine, int endLine) + private void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { @@ -167,7 +167,7 @@ namespace AvaloniaEdit.TextMate _invalidRange = null; } - void TokenizeViewPort() + private void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => {
2
Add private modifiers
2
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10067260
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public class TextEditorModel : AbstractLineList, IDisposable { private readonly TextDocument _document; private readonly TextView _textView; private DocumentSnapshot _documentSnapshot; private Action<Exception> _exceptionHandler; private InvalidLineRange _invalidRange; public DocumentSnapshot DocumentSnapshot { get { return _documentSnapshot; } } internal InvalidLineRange InvalidRange { get { return _invalidRange; } } public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler) { _textView = textView; _document = document; _exceptionHandler = exceptionHandler; _documentSnapshot = new DocumentSnapshot(_document); for (int i = 0; i < _document.LineCount; i++) AddLine(i); _document.Changing += DocumentOnChanging; _document.Changed += DocumentOnChanged; _document.UpdateFinished += DocumentOnUpdateFinished; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } public override void Dispose() { _document.Changing -= DocumentOnChanging; _document.Changed -= DocumentOnChanged; _document.UpdateFinished -= DocumentOnUpdateFinished; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public override void UpdateLine(int lineIndex) { } public void InvalidateViewPortLines() { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; InvalidateLineRange( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { return _documentSnapshot.GetLineLength(lineIndex); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { try { TokenizeViewPort(); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanging(object sender, DocumentChangeEventArgs e) { try { if (e.RemovalLength > 0) { var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1; for (int i = endLine; i > startLine; i--) { RemoveLine(i); } _documentSnapshot.RemoveLines(startLine, endLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanged(object sender, DocumentChangeEventArgs e) { try { int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; int endLine = startLine; if (e.InsertionLength > 0) { endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { AddLine(i); } } _documentSnapshot.Update(e); if (startLine == 0) { SetInvalidRange(startLine, endLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too SetInvalidRange(startLine - 1, endLine); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { InvalidateLineRange(startLine, endLine); return; } // we're in a document change, store the max invalid range if (_invalidRange == null) { _invalidRange = new InvalidLineRange(startLine, endLine); return; } _invalidRange.SetInvalidRange(startLine, endLine); } void DocumentOnUpdateFinished(object sender, EventArgs e) { if (_invalidRange == null) _invalidRange = null; } void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => { { _invalidRange = null; } } private void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, DispatcherPriority.MinValue); } internal class InvalidLineRange { internal int StartLine { get; private set; } internal int EndLine { get; private set; } internal InvalidLineRange(int startLine, int endLine) { StartLine = startLine; EndLine = endLine; } internal void SetInvalidRange(int startLine, int endLine) { if (startLine < StartLine) StartLine = startLine; if (endLine > EndLine) EndLine = endLine; } } } } <MSG> Add private modifiers <DFF> @@ -143,7 +143,7 @@ namespace AvaloniaEdit.TextMate } } - void SetInvalidRange(int startLine, int endLine) + private void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { @@ -167,7 +167,7 @@ namespace AvaloniaEdit.TextMate _invalidRange = null; } - void TokenizeViewPort() + private void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => {
2
Add private modifiers
2
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10067261
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public class TextEditorModel : AbstractLineList, IDisposable { private readonly TextDocument _document; private readonly TextView _textView; private DocumentSnapshot _documentSnapshot; private Action<Exception> _exceptionHandler; private InvalidLineRange _invalidRange; public DocumentSnapshot DocumentSnapshot { get { return _documentSnapshot; } } internal InvalidLineRange InvalidRange { get { return _invalidRange; } } public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler) { _textView = textView; _document = document; _exceptionHandler = exceptionHandler; _documentSnapshot = new DocumentSnapshot(_document); for (int i = 0; i < _document.LineCount; i++) AddLine(i); _document.Changing += DocumentOnChanging; _document.Changed += DocumentOnChanged; _document.UpdateFinished += DocumentOnUpdateFinished; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } public override void Dispose() { _document.Changing -= DocumentOnChanging; _document.Changed -= DocumentOnChanged; _document.UpdateFinished -= DocumentOnUpdateFinished; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public override void UpdateLine(int lineIndex) { } public void InvalidateViewPortLines() { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; InvalidateLineRange( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { return _documentSnapshot.GetLineLength(lineIndex); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { try { TokenizeViewPort(); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanging(object sender, DocumentChangeEventArgs e) { try { if (e.RemovalLength > 0) { var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1; for (int i = endLine; i > startLine; i--) { RemoveLine(i); } _documentSnapshot.RemoveLines(startLine, endLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanged(object sender, DocumentChangeEventArgs e) { try { int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; int endLine = startLine; if (e.InsertionLength > 0) { endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { AddLine(i); } } _documentSnapshot.Update(e); if (startLine == 0) { SetInvalidRange(startLine, endLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too SetInvalidRange(startLine - 1, endLine); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { InvalidateLineRange(startLine, endLine); return; } // we're in a document change, store the max invalid range if (_invalidRange == null) { _invalidRange = new InvalidLineRange(startLine, endLine); return; } _invalidRange.SetInvalidRange(startLine, endLine); } void DocumentOnUpdateFinished(object sender, EventArgs e) { if (_invalidRange == null) _invalidRange = null; } void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => { { _invalidRange = null; } } private void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, DispatcherPriority.MinValue); } internal class InvalidLineRange { internal int StartLine { get; private set; } internal int EndLine { get; private set; } internal InvalidLineRange(int startLine, int endLine) { StartLine = startLine; EndLine = endLine; } internal void SetInvalidRange(int startLine, int endLine) { if (startLine < StartLine) StartLine = startLine; if (endLine > EndLine) EndLine = endLine; } } } } <MSG> Add private modifiers <DFF> @@ -143,7 +143,7 @@ namespace AvaloniaEdit.TextMate } } - void SetInvalidRange(int startLine, int endLine) + private void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { @@ -167,7 +167,7 @@ namespace AvaloniaEdit.TextMate _invalidRange = null; } - void TokenizeViewPort() + private void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => {
2
Add private modifiers
2
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10067262
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public class TextEditorModel : AbstractLineList, IDisposable { private readonly TextDocument _document; private readonly TextView _textView; private DocumentSnapshot _documentSnapshot; private Action<Exception> _exceptionHandler; private InvalidLineRange _invalidRange; public DocumentSnapshot DocumentSnapshot { get { return _documentSnapshot; } } internal InvalidLineRange InvalidRange { get { return _invalidRange; } } public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler) { _textView = textView; _document = document; _exceptionHandler = exceptionHandler; _documentSnapshot = new DocumentSnapshot(_document); for (int i = 0; i < _document.LineCount; i++) AddLine(i); _document.Changing += DocumentOnChanging; _document.Changed += DocumentOnChanged; _document.UpdateFinished += DocumentOnUpdateFinished; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } public override void Dispose() { _document.Changing -= DocumentOnChanging; _document.Changed -= DocumentOnChanged; _document.UpdateFinished -= DocumentOnUpdateFinished; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public override void UpdateLine(int lineIndex) { } public void InvalidateViewPortLines() { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; InvalidateLineRange( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { return _documentSnapshot.GetLineLength(lineIndex); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { try { TokenizeViewPort(); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanging(object sender, DocumentChangeEventArgs e) { try { if (e.RemovalLength > 0) { var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1; for (int i = endLine; i > startLine; i--) { RemoveLine(i); } _documentSnapshot.RemoveLines(startLine, endLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanged(object sender, DocumentChangeEventArgs e) { try { int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; int endLine = startLine; if (e.InsertionLength > 0) { endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { AddLine(i); } } _documentSnapshot.Update(e); if (startLine == 0) { SetInvalidRange(startLine, endLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too SetInvalidRange(startLine - 1, endLine); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { InvalidateLineRange(startLine, endLine); return; } // we're in a document change, store the max invalid range if (_invalidRange == null) { _invalidRange = new InvalidLineRange(startLine, endLine); return; } _invalidRange.SetInvalidRange(startLine, endLine); } void DocumentOnUpdateFinished(object sender, EventArgs e) { if (_invalidRange == null) _invalidRange = null; } void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => { { _invalidRange = null; } } private void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, DispatcherPriority.MinValue); } internal class InvalidLineRange { internal int StartLine { get; private set; } internal int EndLine { get; private set; } internal InvalidLineRange(int startLine, int endLine) { StartLine = startLine; EndLine = endLine; } internal void SetInvalidRange(int startLine, int endLine) { if (startLine < StartLine) StartLine = startLine; if (endLine > EndLine) EndLine = endLine; } } } } <MSG> Add private modifiers <DFF> @@ -143,7 +143,7 @@ namespace AvaloniaEdit.TextMate } } - void SetInvalidRange(int startLine, int endLine) + private void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { @@ -167,7 +167,7 @@ namespace AvaloniaEdit.TextMate _invalidRange = null; } - void TokenizeViewPort() + private void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => {
2
Add private modifiers
2
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10067263
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public class TextEditorModel : AbstractLineList, IDisposable { private readonly TextDocument _document; private readonly TextView _textView; private DocumentSnapshot _documentSnapshot; private Action<Exception> _exceptionHandler; private InvalidLineRange _invalidRange; public DocumentSnapshot DocumentSnapshot { get { return _documentSnapshot; } } internal InvalidLineRange InvalidRange { get { return _invalidRange; } } public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler) { _textView = textView; _document = document; _exceptionHandler = exceptionHandler; _documentSnapshot = new DocumentSnapshot(_document); for (int i = 0; i < _document.LineCount; i++) AddLine(i); _document.Changing += DocumentOnChanging; _document.Changed += DocumentOnChanged; _document.UpdateFinished += DocumentOnUpdateFinished; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } public override void Dispose() { _document.Changing -= DocumentOnChanging; _document.Changed -= DocumentOnChanged; _document.UpdateFinished -= DocumentOnUpdateFinished; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public override void UpdateLine(int lineIndex) { } public void InvalidateViewPortLines() { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; InvalidateLineRange( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { return _documentSnapshot.GetLineLength(lineIndex); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { try { TokenizeViewPort(); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanging(object sender, DocumentChangeEventArgs e) { try { if (e.RemovalLength > 0) { var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1; for (int i = endLine; i > startLine; i--) { RemoveLine(i); } _documentSnapshot.RemoveLines(startLine, endLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanged(object sender, DocumentChangeEventArgs e) { try { int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; int endLine = startLine; if (e.InsertionLength > 0) { endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { AddLine(i); } } _documentSnapshot.Update(e); if (startLine == 0) { SetInvalidRange(startLine, endLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too SetInvalidRange(startLine - 1, endLine); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { InvalidateLineRange(startLine, endLine); return; } // we're in a document change, store the max invalid range if (_invalidRange == null) { _invalidRange = new InvalidLineRange(startLine, endLine); return; } _invalidRange.SetInvalidRange(startLine, endLine); } void DocumentOnUpdateFinished(object sender, EventArgs e) { if (_invalidRange == null) _invalidRange = null; } void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => { { _invalidRange = null; } } private void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, DispatcherPriority.MinValue); } internal class InvalidLineRange { internal int StartLine { get; private set; } internal int EndLine { get; private set; } internal InvalidLineRange(int startLine, int endLine) { StartLine = startLine; EndLine = endLine; } internal void SetInvalidRange(int startLine, int endLine) { if (startLine < StartLine) StartLine = startLine; if (endLine > EndLine) EndLine = endLine; } } } } <MSG> Add private modifiers <DFF> @@ -143,7 +143,7 @@ namespace AvaloniaEdit.TextMate } } - void SetInvalidRange(int startLine, int endLine) + private void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { @@ -167,7 +167,7 @@ namespace AvaloniaEdit.TextMate _invalidRange = null; } - void TokenizeViewPort() + private void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => {
2
Add private modifiers
2
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10067264
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public class TextEditorModel : AbstractLineList, IDisposable { private readonly TextDocument _document; private readonly TextView _textView; private DocumentSnapshot _documentSnapshot; private Action<Exception> _exceptionHandler; private InvalidLineRange _invalidRange; public DocumentSnapshot DocumentSnapshot { get { return _documentSnapshot; } } internal InvalidLineRange InvalidRange { get { return _invalidRange; } } public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler) { _textView = textView; _document = document; _exceptionHandler = exceptionHandler; _documentSnapshot = new DocumentSnapshot(_document); for (int i = 0; i < _document.LineCount; i++) AddLine(i); _document.Changing += DocumentOnChanging; _document.Changed += DocumentOnChanged; _document.UpdateFinished += DocumentOnUpdateFinished; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } public override void Dispose() { _document.Changing -= DocumentOnChanging; _document.Changed -= DocumentOnChanged; _document.UpdateFinished -= DocumentOnUpdateFinished; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public override void UpdateLine(int lineIndex) { } public void InvalidateViewPortLines() { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; InvalidateLineRange( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { return _documentSnapshot.GetLineLength(lineIndex); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { try { TokenizeViewPort(); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanging(object sender, DocumentChangeEventArgs e) { try { if (e.RemovalLength > 0) { var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1; for (int i = endLine; i > startLine; i--) { RemoveLine(i); } _documentSnapshot.RemoveLines(startLine, endLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanged(object sender, DocumentChangeEventArgs e) { try { int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; int endLine = startLine; if (e.InsertionLength > 0) { endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { AddLine(i); } } _documentSnapshot.Update(e); if (startLine == 0) { SetInvalidRange(startLine, endLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too SetInvalidRange(startLine - 1, endLine); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { InvalidateLineRange(startLine, endLine); return; } // we're in a document change, store the max invalid range if (_invalidRange == null) { _invalidRange = new InvalidLineRange(startLine, endLine); return; } _invalidRange.SetInvalidRange(startLine, endLine); } void DocumentOnUpdateFinished(object sender, EventArgs e) { if (_invalidRange == null) _invalidRange = null; } void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => { { _invalidRange = null; } } private void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, DispatcherPriority.MinValue); } internal class InvalidLineRange { internal int StartLine { get; private set; } internal int EndLine { get; private set; } internal InvalidLineRange(int startLine, int endLine) { StartLine = startLine; EndLine = endLine; } internal void SetInvalidRange(int startLine, int endLine) { if (startLine < StartLine) StartLine = startLine; if (endLine > EndLine) EndLine = endLine; } } } } <MSG> Add private modifiers <DFF> @@ -143,7 +143,7 @@ namespace AvaloniaEdit.TextMate } } - void SetInvalidRange(int startLine, int endLine) + private void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { @@ -167,7 +167,7 @@ namespace AvaloniaEdit.TextMate _invalidRange = null; } - void TokenizeViewPort() + private void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => {
2
Add private modifiers
2
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10067265
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public class TextEditorModel : AbstractLineList, IDisposable { private readonly TextDocument _document; private readonly TextView _textView; private DocumentSnapshot _documentSnapshot; private Action<Exception> _exceptionHandler; private InvalidLineRange _invalidRange; public DocumentSnapshot DocumentSnapshot { get { return _documentSnapshot; } } internal InvalidLineRange InvalidRange { get { return _invalidRange; } } public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler) { _textView = textView; _document = document; _exceptionHandler = exceptionHandler; _documentSnapshot = new DocumentSnapshot(_document); for (int i = 0; i < _document.LineCount; i++) AddLine(i); _document.Changing += DocumentOnChanging; _document.Changed += DocumentOnChanged; _document.UpdateFinished += DocumentOnUpdateFinished; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } public override void Dispose() { _document.Changing -= DocumentOnChanging; _document.Changed -= DocumentOnChanged; _document.UpdateFinished -= DocumentOnUpdateFinished; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public override void UpdateLine(int lineIndex) { } public void InvalidateViewPortLines() { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; InvalidateLineRange( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { return _documentSnapshot.GetLineLength(lineIndex); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { try { TokenizeViewPort(); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanging(object sender, DocumentChangeEventArgs e) { try { if (e.RemovalLength > 0) { var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1; for (int i = endLine; i > startLine; i--) { RemoveLine(i); } _documentSnapshot.RemoveLines(startLine, endLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanged(object sender, DocumentChangeEventArgs e) { try { int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; int endLine = startLine; if (e.InsertionLength > 0) { endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { AddLine(i); } } _documentSnapshot.Update(e); if (startLine == 0) { SetInvalidRange(startLine, endLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too SetInvalidRange(startLine - 1, endLine); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { InvalidateLineRange(startLine, endLine); return; } // we're in a document change, store the max invalid range if (_invalidRange == null) { _invalidRange = new InvalidLineRange(startLine, endLine); return; } _invalidRange.SetInvalidRange(startLine, endLine); } void DocumentOnUpdateFinished(object sender, EventArgs e) { if (_invalidRange == null) _invalidRange = null; } void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => { { _invalidRange = null; } } private void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, DispatcherPriority.MinValue); } internal class InvalidLineRange { internal int StartLine { get; private set; } internal int EndLine { get; private set; } internal InvalidLineRange(int startLine, int endLine) { StartLine = startLine; EndLine = endLine; } internal void SetInvalidRange(int startLine, int endLine) { if (startLine < StartLine) StartLine = startLine; if (endLine > EndLine) EndLine = endLine; } } } } <MSG> Add private modifiers <DFF> @@ -143,7 +143,7 @@ namespace AvaloniaEdit.TextMate } } - void SetInvalidRange(int startLine, int endLine) + private void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { @@ -167,7 +167,7 @@ namespace AvaloniaEdit.TextMate _invalidRange = null; } - void TokenizeViewPort() + private void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => {
2
Add private modifiers
2
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10067266
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public class TextEditorModel : AbstractLineList, IDisposable { private readonly TextDocument _document; private readonly TextView _textView; private DocumentSnapshot _documentSnapshot; private Action<Exception> _exceptionHandler; private InvalidLineRange _invalidRange; public DocumentSnapshot DocumentSnapshot { get { return _documentSnapshot; } } internal InvalidLineRange InvalidRange { get { return _invalidRange; } } public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler) { _textView = textView; _document = document; _exceptionHandler = exceptionHandler; _documentSnapshot = new DocumentSnapshot(_document); for (int i = 0; i < _document.LineCount; i++) AddLine(i); _document.Changing += DocumentOnChanging; _document.Changed += DocumentOnChanged; _document.UpdateFinished += DocumentOnUpdateFinished; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } public override void Dispose() { _document.Changing -= DocumentOnChanging; _document.Changed -= DocumentOnChanged; _document.UpdateFinished -= DocumentOnUpdateFinished; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public override void UpdateLine(int lineIndex) { } public void InvalidateViewPortLines() { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; InvalidateLineRange( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { return _documentSnapshot.GetLineLength(lineIndex); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { try { TokenizeViewPort(); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanging(object sender, DocumentChangeEventArgs e) { try { if (e.RemovalLength > 0) { var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1; for (int i = endLine; i > startLine; i--) { RemoveLine(i); } _documentSnapshot.RemoveLines(startLine, endLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanged(object sender, DocumentChangeEventArgs e) { try { int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; int endLine = startLine; if (e.InsertionLength > 0) { endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { AddLine(i); } } _documentSnapshot.Update(e); if (startLine == 0) { SetInvalidRange(startLine, endLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too SetInvalidRange(startLine - 1, endLine); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { InvalidateLineRange(startLine, endLine); return; } // we're in a document change, store the max invalid range if (_invalidRange == null) { _invalidRange = new InvalidLineRange(startLine, endLine); return; } _invalidRange.SetInvalidRange(startLine, endLine); } void DocumentOnUpdateFinished(object sender, EventArgs e) { if (_invalidRange == null) _invalidRange = null; } void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => { { _invalidRange = null; } } private void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, DispatcherPriority.MinValue); } internal class InvalidLineRange { internal int StartLine { get; private set; } internal int EndLine { get; private set; } internal InvalidLineRange(int startLine, int endLine) { StartLine = startLine; EndLine = endLine; } internal void SetInvalidRange(int startLine, int endLine) { if (startLine < StartLine) StartLine = startLine; if (endLine > EndLine) EndLine = endLine; } } } } <MSG> Add private modifiers <DFF> @@ -143,7 +143,7 @@ namespace AvaloniaEdit.TextMate } } - void SetInvalidRange(int startLine, int endLine) + private void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { @@ -167,7 +167,7 @@ namespace AvaloniaEdit.TextMate _invalidRange = null; } - void TokenizeViewPort() + private void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => {
2
Add private modifiers
2
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10067267
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public class TextEditorModel : AbstractLineList, IDisposable { private readonly TextDocument _document; private readonly TextView _textView; private DocumentSnapshot _documentSnapshot; private Action<Exception> _exceptionHandler; private InvalidLineRange _invalidRange; public DocumentSnapshot DocumentSnapshot { get { return _documentSnapshot; } } internal InvalidLineRange InvalidRange { get { return _invalidRange; } } public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler) { _textView = textView; _document = document; _exceptionHandler = exceptionHandler; _documentSnapshot = new DocumentSnapshot(_document); for (int i = 0; i < _document.LineCount; i++) AddLine(i); _document.Changing += DocumentOnChanging; _document.Changed += DocumentOnChanged; _document.UpdateFinished += DocumentOnUpdateFinished; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } public override void Dispose() { _document.Changing -= DocumentOnChanging; _document.Changed -= DocumentOnChanged; _document.UpdateFinished -= DocumentOnUpdateFinished; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public override void UpdateLine(int lineIndex) { } public void InvalidateViewPortLines() { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; InvalidateLineRange( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { return _documentSnapshot.GetLineLength(lineIndex); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { try { TokenizeViewPort(); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanging(object sender, DocumentChangeEventArgs e) { try { if (e.RemovalLength > 0) { var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1; for (int i = endLine; i > startLine; i--) { RemoveLine(i); } _documentSnapshot.RemoveLines(startLine, endLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanged(object sender, DocumentChangeEventArgs e) { try { int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; int endLine = startLine; if (e.InsertionLength > 0) { endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { AddLine(i); } } _documentSnapshot.Update(e); if (startLine == 0) { SetInvalidRange(startLine, endLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too SetInvalidRange(startLine - 1, endLine); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { InvalidateLineRange(startLine, endLine); return; } // we're in a document change, store the max invalid range if (_invalidRange == null) { _invalidRange = new InvalidLineRange(startLine, endLine); return; } _invalidRange.SetInvalidRange(startLine, endLine); } void DocumentOnUpdateFinished(object sender, EventArgs e) { if (_invalidRange == null) _invalidRange = null; } void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => { { _invalidRange = null; } } private void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, DispatcherPriority.MinValue); } internal class InvalidLineRange { internal int StartLine { get; private set; } internal int EndLine { get; private set; } internal InvalidLineRange(int startLine, int endLine) { StartLine = startLine; EndLine = endLine; } internal void SetInvalidRange(int startLine, int endLine) { if (startLine < StartLine) StartLine = startLine; if (endLine > EndLine) EndLine = endLine; } } } } <MSG> Add private modifiers <DFF> @@ -143,7 +143,7 @@ namespace AvaloniaEdit.TextMate } } - void SetInvalidRange(int startLine, int endLine) + private void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { @@ -167,7 +167,7 @@ namespace AvaloniaEdit.TextMate _invalidRange = null; } - void TokenizeViewPort() + private void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => {
2
Add private modifiers
2
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10067268
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public class TextEditorModel : AbstractLineList, IDisposable { private readonly TextDocument _document; private readonly TextView _textView; private DocumentSnapshot _documentSnapshot; private Action<Exception> _exceptionHandler; private InvalidLineRange _invalidRange; public DocumentSnapshot DocumentSnapshot { get { return _documentSnapshot; } } internal InvalidLineRange InvalidRange { get { return _invalidRange; } } public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler) { _textView = textView; _document = document; _exceptionHandler = exceptionHandler; _documentSnapshot = new DocumentSnapshot(_document); for (int i = 0; i < _document.LineCount; i++) AddLine(i); _document.Changing += DocumentOnChanging; _document.Changed += DocumentOnChanged; _document.UpdateFinished += DocumentOnUpdateFinished; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } public override void Dispose() { _document.Changing -= DocumentOnChanging; _document.Changed -= DocumentOnChanged; _document.UpdateFinished -= DocumentOnUpdateFinished; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public override void UpdateLine(int lineIndex) { } public void InvalidateViewPortLines() { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; InvalidateLineRange( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { return _documentSnapshot.GetLineLength(lineIndex); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { try { TokenizeViewPort(); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanging(object sender, DocumentChangeEventArgs e) { try { if (e.RemovalLength > 0) { var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1; for (int i = endLine; i > startLine; i--) { RemoveLine(i); } _documentSnapshot.RemoveLines(startLine, endLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanged(object sender, DocumentChangeEventArgs e) { try { int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; int endLine = startLine; if (e.InsertionLength > 0) { endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { AddLine(i); } } _documentSnapshot.Update(e); if (startLine == 0) { SetInvalidRange(startLine, endLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too SetInvalidRange(startLine - 1, endLine); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { InvalidateLineRange(startLine, endLine); return; } // we're in a document change, store the max invalid range if (_invalidRange == null) { _invalidRange = new InvalidLineRange(startLine, endLine); return; } _invalidRange.SetInvalidRange(startLine, endLine); } void DocumentOnUpdateFinished(object sender, EventArgs e) { if (_invalidRange == null) _invalidRange = null; } void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => { { _invalidRange = null; } } private void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, DispatcherPriority.MinValue); } internal class InvalidLineRange { internal int StartLine { get; private set; } internal int EndLine { get; private set; } internal InvalidLineRange(int startLine, int endLine) { StartLine = startLine; EndLine = endLine; } internal void SetInvalidRange(int startLine, int endLine) { if (startLine < StartLine) StartLine = startLine; if (endLine > EndLine) EndLine = endLine; } } } } <MSG> Add private modifiers <DFF> @@ -143,7 +143,7 @@ namespace AvaloniaEdit.TextMate } } - void SetInvalidRange(int startLine, int endLine) + private void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { @@ -167,7 +167,7 @@ namespace AvaloniaEdit.TextMate _invalidRange = null; } - void TokenizeViewPort() + private void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => {
2
Add private modifiers
2
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10067269
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public class TextEditorModel : AbstractLineList, IDisposable { private readonly TextDocument _document; private readonly TextView _textView; private DocumentSnapshot _documentSnapshot; private Action<Exception> _exceptionHandler; private InvalidLineRange _invalidRange; public DocumentSnapshot DocumentSnapshot { get { return _documentSnapshot; } } internal InvalidLineRange InvalidRange { get { return _invalidRange; } } public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler) { _textView = textView; _document = document; _exceptionHandler = exceptionHandler; _documentSnapshot = new DocumentSnapshot(_document); for (int i = 0; i < _document.LineCount; i++) AddLine(i); _document.Changing += DocumentOnChanging; _document.Changed += DocumentOnChanged; _document.UpdateFinished += DocumentOnUpdateFinished; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } public override void Dispose() { _document.Changing -= DocumentOnChanging; _document.Changed -= DocumentOnChanged; _document.UpdateFinished -= DocumentOnUpdateFinished; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public override void UpdateLine(int lineIndex) { } public void InvalidateViewPortLines() { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; InvalidateLineRange( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { return _documentSnapshot.GetLineLength(lineIndex); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { try { TokenizeViewPort(); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanging(object sender, DocumentChangeEventArgs e) { try { if (e.RemovalLength > 0) { var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1; for (int i = endLine; i > startLine; i--) { RemoveLine(i); } _documentSnapshot.RemoveLines(startLine, endLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanged(object sender, DocumentChangeEventArgs e) { try { int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; int endLine = startLine; if (e.InsertionLength > 0) { endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { AddLine(i); } } _documentSnapshot.Update(e); if (startLine == 0) { SetInvalidRange(startLine, endLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too SetInvalidRange(startLine - 1, endLine); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { InvalidateLineRange(startLine, endLine); return; } // we're in a document change, store the max invalid range if (_invalidRange == null) { _invalidRange = new InvalidLineRange(startLine, endLine); return; } _invalidRange.SetInvalidRange(startLine, endLine); } void DocumentOnUpdateFinished(object sender, EventArgs e) { if (_invalidRange == null) _invalidRange = null; } void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => { { _invalidRange = null; } } private void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, DispatcherPriority.MinValue); } internal class InvalidLineRange { internal int StartLine { get; private set; } internal int EndLine { get; private set; } internal InvalidLineRange(int startLine, int endLine) { StartLine = startLine; EndLine = endLine; } internal void SetInvalidRange(int startLine, int endLine) { if (startLine < StartLine) StartLine = startLine; if (endLine > EndLine) EndLine = endLine; } } } } <MSG> Add private modifiers <DFF> @@ -143,7 +143,7 @@ namespace AvaloniaEdit.TextMate } } - void SetInvalidRange(int startLine, int endLine) + private void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { @@ -167,7 +167,7 @@ namespace AvaloniaEdit.TextMate _invalidRange = null; } - void TokenizeViewPort() + private void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => {
2
Add private modifiers
2
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10067270
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public class TextEditorModel : AbstractLineList, IDisposable { private readonly TextDocument _document; private readonly TextView _textView; private DocumentSnapshot _documentSnapshot; private Action<Exception> _exceptionHandler; private InvalidLineRange _invalidRange; public DocumentSnapshot DocumentSnapshot { get { return _documentSnapshot; } } internal InvalidLineRange InvalidRange { get { return _invalidRange; } } public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler) { _textView = textView; _document = document; _exceptionHandler = exceptionHandler; _documentSnapshot = new DocumentSnapshot(_document); for (int i = 0; i < _document.LineCount; i++) AddLine(i); _document.Changing += DocumentOnChanging; _document.Changed += DocumentOnChanged; _document.UpdateFinished += DocumentOnUpdateFinished; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } public override void Dispose() { _document.Changing -= DocumentOnChanging; _document.Changed -= DocumentOnChanged; _document.UpdateFinished -= DocumentOnUpdateFinished; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public override void UpdateLine(int lineIndex) { } public void InvalidateViewPortLines() { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; InvalidateLineRange( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { return _documentSnapshot.GetLineLength(lineIndex); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { try { TokenizeViewPort(); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanging(object sender, DocumentChangeEventArgs e) { try { if (e.RemovalLength > 0) { var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1; for (int i = endLine; i > startLine; i--) { RemoveLine(i); } _documentSnapshot.RemoveLines(startLine, endLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanged(object sender, DocumentChangeEventArgs e) { try { int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; int endLine = startLine; if (e.InsertionLength > 0) { endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { AddLine(i); } } _documentSnapshot.Update(e); if (startLine == 0) { SetInvalidRange(startLine, endLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too SetInvalidRange(startLine - 1, endLine); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { InvalidateLineRange(startLine, endLine); return; } // we're in a document change, store the max invalid range if (_invalidRange == null) { _invalidRange = new InvalidLineRange(startLine, endLine); return; } _invalidRange.SetInvalidRange(startLine, endLine); } void DocumentOnUpdateFinished(object sender, EventArgs e) { if (_invalidRange == null) _invalidRange = null; } void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => { { _invalidRange = null; } } private void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, DispatcherPriority.MinValue); } internal class InvalidLineRange { internal int StartLine { get; private set; } internal int EndLine { get; private set; } internal InvalidLineRange(int startLine, int endLine) { StartLine = startLine; EndLine = endLine; } internal void SetInvalidRange(int startLine, int endLine) { if (startLine < StartLine) StartLine = startLine; if (endLine > EndLine) EndLine = endLine; } } } } <MSG> Add private modifiers <DFF> @@ -143,7 +143,7 @@ namespace AvaloniaEdit.TextMate } } - void SetInvalidRange(int startLine, int endLine) + private void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { @@ -167,7 +167,7 @@ namespace AvaloniaEdit.TextMate _invalidRange = null; } - void TokenizeViewPort() + private void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => {
2
Add private modifiers
2
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10067271
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public class TextEditorModel : AbstractLineList, IDisposable { private readonly TextDocument _document; private readonly TextView _textView; private DocumentSnapshot _documentSnapshot; private Action<Exception> _exceptionHandler; private InvalidLineRange _invalidRange; public DocumentSnapshot DocumentSnapshot { get { return _documentSnapshot; } } internal InvalidLineRange InvalidRange { get { return _invalidRange; } } public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler) { _textView = textView; _document = document; _exceptionHandler = exceptionHandler; _documentSnapshot = new DocumentSnapshot(_document); for (int i = 0; i < _document.LineCount; i++) AddLine(i); _document.Changing += DocumentOnChanging; _document.Changed += DocumentOnChanged; _document.UpdateFinished += DocumentOnUpdateFinished; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } public override void Dispose() { _document.Changing -= DocumentOnChanging; _document.Changed -= DocumentOnChanged; _document.UpdateFinished -= DocumentOnUpdateFinished; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public override void UpdateLine(int lineIndex) { } public void InvalidateViewPortLines() { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; InvalidateLineRange( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { return _documentSnapshot.GetLineLength(lineIndex); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { try { TokenizeViewPort(); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanging(object sender, DocumentChangeEventArgs e) { try { if (e.RemovalLength > 0) { var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1; for (int i = endLine; i > startLine; i--) { RemoveLine(i); } _documentSnapshot.RemoveLines(startLine, endLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanged(object sender, DocumentChangeEventArgs e) { try { int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; int endLine = startLine; if (e.InsertionLength > 0) { endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { AddLine(i); } } _documentSnapshot.Update(e); if (startLine == 0) { SetInvalidRange(startLine, endLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too SetInvalidRange(startLine - 1, endLine); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { InvalidateLineRange(startLine, endLine); return; } // we're in a document change, store the max invalid range if (_invalidRange == null) { _invalidRange = new InvalidLineRange(startLine, endLine); return; } _invalidRange.SetInvalidRange(startLine, endLine); } void DocumentOnUpdateFinished(object sender, EventArgs e) { if (_invalidRange == null) _invalidRange = null; } void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => { { _invalidRange = null; } } private void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, DispatcherPriority.MinValue); } internal class InvalidLineRange { internal int StartLine { get; private set; } internal int EndLine { get; private set; } internal InvalidLineRange(int startLine, int endLine) { StartLine = startLine; EndLine = endLine; } internal void SetInvalidRange(int startLine, int endLine) { if (startLine < StartLine) StartLine = startLine; if (endLine > EndLine) EndLine = endLine; } } } } <MSG> Add private modifiers <DFF> @@ -143,7 +143,7 @@ namespace AvaloniaEdit.TextMate } } - void SetInvalidRange(int startLine, int endLine) + private void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { @@ -167,7 +167,7 @@ namespace AvaloniaEdit.TextMate _invalidRange = null; } - void TokenizeViewPort() + private void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => {
2
Add private modifiers
2
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10067272
<NME> AvaloniaEditCommands.cs <BEF> // 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.Diagnostics.CodeAnalysis; using Avalonia; using Avalonia.Input; using Avalonia.Platform; namespace AvaloniaEdit { /// <summary> /// Custom commands for AvalonEdit. /// </summary> public static class AvaloniaEditCommands { /// <summary> /// Toggles Overstrike mode /// The default shortcut is Ins. /// </summary> public static RoutedCommand ToggleOverstrike { get; } = new RoutedCommand(nameof(ToggleOverstrike), new KeyGesture(Key.Insert)); /// <summary> /// Deletes the current line. /// The default shortcut is Ctrl+D. /// </summary> public static RoutedCommand DeleteLine { get; } = new RoutedCommand(nameof(DeleteLine), new KeyGesture(Key.D, KeyModifiers.Control)); /// <summary> /// Removes leading whitespace from the selected lines (or the whole document if the selection is empty). /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] public static RoutedCommand RemoveLeadingWhitespace { get; } = new RoutedCommand(nameof(RemoveLeadingWhitespace)); /// <summary> /// Removes trailing whitespace from the selected lines (or the whole document if the selection is empty). /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] public static RoutedCommand RemoveTrailingWhitespace { get; } = new RoutedCommand(nameof(RemoveTrailingWhitespace)); /// <summary> /// Converts the selected text to upper case. /// </summary> public static RoutedCommand ConvertToUppercase { get; } = new RoutedCommand(nameof(ConvertToUppercase)); /// <summary> /// Converts the selected text to lower case. /// </summary> public static RoutedCommand ConvertToLowercase { get; } = new RoutedCommand(nameof(ConvertToLowercase)); /// <summary> /// Converts the selected text to title case. /// </summary> public static RoutedCommand ConvertToTitleCase { get; } = new RoutedCommand(nameof(ConvertToTitleCase)); /// <summary> /// Inverts the case of the selected text. /// </summary> public static RoutedCommand InvertCase { get; } = new RoutedCommand(nameof(InvertCase)); /// <summary> /// Converts tabs to spaces in the selected text. /// </summary> public static RoutedCommand ConvertTabsToSpaces { get; } = new RoutedCommand(nameof(ConvertTabsToSpaces)); /// <summary> /// Converts spaces to tabs in the selected text. /// </summary> public static RoutedCommand ConvertSpacesToTabs { get; } = new RoutedCommand(nameof(ConvertSpacesToTabs)); /// <summary> /// Converts leading tabs to spaces in the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand ConvertLeadingTabsToSpaces { get; } = new RoutedCommand(nameof(ConvertLeadingTabsToSpaces)); /// <summary> /// Converts leading spaces to tabs in the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand ConvertLeadingSpacesToTabs { get; } = new RoutedCommand(nameof(ConvertLeadingSpacesToTabs)); /// <summary>InputModifiers /// Runs the IIndentationStrategy on the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand IndentSelection { get; } = new RoutedCommand(nameof(IndentSelection), new KeyGesture(Key.I, KeyModifiers.Control)); } public static class ApplicationCommands { private static readonly KeyModifiers PlatformCommandKey = GetPlatformCommandKey(); public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete), new KeyGesture(Key.Delete)); public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture(Key.C, KeyModifiers.Control)); public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture(Key.X, KeyModifiers.Control)); public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture(Key.V, KeyModifiers.Control)); public static RoutedCommand SelectAll { get; } = new RoutedCommand(nameof(SelectAll), new KeyGesture(Key.A, PlatformCommandKey)); public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture(Key.Z, KeyModifiers.Control)); public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture(Key.Y, KeyModifiers.Control)); public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture(Key.F, KeyModifiers.Control)); public static RoutedCommand Replace { get; } = new RoutedCommand(nameof(Replace), GetReplaceKeyGesture()); private static OperatingSystemType GetOperatingSystemType() { return AvaloniaLocator.Current.GetService<IRuntimePlatform>().GetRuntimeInfo().OperatingSystem; } private static KeyModifiers GetPlatformCommandKey() { var os = GetOperatingSystemType(); if (os == OperatingSystemType.OSX) { return KeyModifiers.Meta; } return KeyModifiers.Control; } private static KeyGesture GetReplaceKeyGesture() { var os = GetOperatingSystemType(); if (os == OperatingSystemType.OSX) { return new KeyGesture(Key.F, KeyModifiers.Meta | KeyModifiers.Alt); } return new KeyGesture(Key.H, PlatformCommandKey); } } public static class EditingCommands { public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete)); public static RoutedCommand DeleteNextWord { get; } = new RoutedCommand(nameof(DeleteNextWord)); public static RoutedCommand Backspace { get; } = new RoutedCommand(nameof(Backspace)); public static RoutedCommand DeletePreviousWord { get; } = new RoutedCommand(nameof(DeletePreviousWord)); public static RoutedCommand EnterParagraphBreak { get; } = new RoutedCommand(nameof(EnterParagraphBreak)); public static RoutedCommand EnterLineBreak { get; } = new RoutedCommand(nameof(EnterLineBreak)); public static RoutedCommand TabForward { get; } = new RoutedCommand(nameof(TabForward)); public static RoutedCommand TabBackward { get; } = new RoutedCommand(nameof(TabBackward)); public static RoutedCommand MoveLeftByCharacter { get; } = new RoutedCommand(nameof(MoveLeftByCharacter)); public static RoutedCommand SelectLeftByCharacter { get; } = new RoutedCommand(nameof(SelectLeftByCharacter)); public static RoutedCommand MoveRightByCharacter { get; } = new RoutedCommand(nameof(MoveRightByCharacter)); public static RoutedCommand SelectRightByCharacter { get; } = new RoutedCommand(nameof(SelectRightByCharacter)); public static RoutedCommand MoveLeftByWord { get; } = new RoutedCommand(nameof(MoveLeftByWord)); public static RoutedCommand SelectLeftByWord { get; } = new RoutedCommand(nameof(SelectLeftByWord)); public static RoutedCommand MoveRightByWord { get; } = new RoutedCommand(nameof(MoveRightByWord)); public static RoutedCommand SelectRightByWord { get; } = new RoutedCommand(nameof(SelectRightByWord)); public static RoutedCommand MoveUpByLine { get; } = new RoutedCommand(nameof(MoveUpByLine)); public static RoutedCommand SelectUpByLine { get; } = new RoutedCommand(nameof(SelectUpByLine)); public static RoutedCommand MoveDownByLine { get; } = new RoutedCommand(nameof(MoveDownByLine)); public static RoutedCommand SelectDownByLine { get; } = new RoutedCommand(nameof(SelectDownByLine)); public static RoutedCommand MoveDownByPage { get; } = new RoutedCommand(nameof(MoveDownByPage)); public static RoutedCommand SelectDownByPage { get; } = new RoutedCommand(nameof(SelectDownByPage)); public static RoutedCommand MoveUpByPage { get; } = new RoutedCommand(nameof(MoveUpByPage)); public static RoutedCommand SelectUpByPage { get; } = new RoutedCommand(nameof(SelectUpByPage)); public static RoutedCommand MoveToLineStart { get; } = new RoutedCommand(nameof(MoveToLineStart)); public static RoutedCommand SelectToLineStart { get; } = new RoutedCommand(nameof(SelectToLineStart)); public static RoutedCommand MoveToLineEnd { get; } = new RoutedCommand(nameof(MoveToLineEnd)); public static RoutedCommand SelectToLineEnd { get; } = new RoutedCommand(nameof(SelectToLineEnd)); public static RoutedCommand MoveToDocumentStart { get; } = new RoutedCommand(nameof(MoveToDocumentStart)); public static RoutedCommand SelectToDocumentStart { get; } = new RoutedCommand(nameof(SelectToDocumentStart)); public static RoutedCommand MoveToDocumentEnd { get; } = new RoutedCommand(nameof(MoveToDocumentEnd)); public static RoutedCommand SelectToDocumentEnd { get; } = new RoutedCommand(nameof(SelectToDocumentEnd)); } } <MSG> Fixing Mac shortcuts using the Control key instead of the Command Key <DFF> @@ -104,13 +104,13 @@ namespace AvaloniaEdit private static readonly KeyModifiers PlatformCommandKey = GetPlatformCommandKey(); public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete), new KeyGesture(Key.Delete)); - public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture(Key.C, KeyModifiers.Control)); - public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture(Key.X, KeyModifiers.Control)); - public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture(Key.V, KeyModifiers.Control)); + public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture(Key.C, PlatformCommandKey)); + public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture(Key.X, PlatformCommandKey)); + public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture(Key.V, PlatformCommandKey)); public static RoutedCommand SelectAll { get; } = new RoutedCommand(nameof(SelectAll), new KeyGesture(Key.A, PlatformCommandKey)); - public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture(Key.Z, KeyModifiers.Control)); - public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture(Key.Y, KeyModifiers.Control)); - public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture(Key.F, KeyModifiers.Control)); + public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture(Key.Z, PlatformCommandKey)); + public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture(Key.Y, PlatformCommandKey)); + public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture(Key.F, PlatformCommandKey)); public static RoutedCommand Replace { get; } = new RoutedCommand(nameof(Replace), GetReplaceKeyGesture()); private static OperatingSystemType GetOperatingSystemType()
6
Fixing Mac shortcuts using the Control key instead of the Command Key
6
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10067273
<NME> AvaloniaEditCommands.cs <BEF> // 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.Diagnostics.CodeAnalysis; using Avalonia; using Avalonia.Input; using Avalonia.Platform; namespace AvaloniaEdit { /// <summary> /// Custom commands for AvalonEdit. /// </summary> public static class AvaloniaEditCommands { /// <summary> /// Toggles Overstrike mode /// The default shortcut is Ins. /// </summary> public static RoutedCommand ToggleOverstrike { get; } = new RoutedCommand(nameof(ToggleOverstrike), new KeyGesture(Key.Insert)); /// <summary> /// Deletes the current line. /// The default shortcut is Ctrl+D. /// </summary> public static RoutedCommand DeleteLine { get; } = new RoutedCommand(nameof(DeleteLine), new KeyGesture(Key.D, KeyModifiers.Control)); /// <summary> /// Removes leading whitespace from the selected lines (or the whole document if the selection is empty). /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] public static RoutedCommand RemoveLeadingWhitespace { get; } = new RoutedCommand(nameof(RemoveLeadingWhitespace)); /// <summary> /// Removes trailing whitespace from the selected lines (or the whole document if the selection is empty). /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] public static RoutedCommand RemoveTrailingWhitespace { get; } = new RoutedCommand(nameof(RemoveTrailingWhitespace)); /// <summary> /// Converts the selected text to upper case. /// </summary> public static RoutedCommand ConvertToUppercase { get; } = new RoutedCommand(nameof(ConvertToUppercase)); /// <summary> /// Converts the selected text to lower case. /// </summary> public static RoutedCommand ConvertToLowercase { get; } = new RoutedCommand(nameof(ConvertToLowercase)); /// <summary> /// Converts the selected text to title case. /// </summary> public static RoutedCommand ConvertToTitleCase { get; } = new RoutedCommand(nameof(ConvertToTitleCase)); /// <summary> /// Inverts the case of the selected text. /// </summary> public static RoutedCommand InvertCase { get; } = new RoutedCommand(nameof(InvertCase)); /// <summary> /// Converts tabs to spaces in the selected text. /// </summary> public static RoutedCommand ConvertTabsToSpaces { get; } = new RoutedCommand(nameof(ConvertTabsToSpaces)); /// <summary> /// Converts spaces to tabs in the selected text. /// </summary> public static RoutedCommand ConvertSpacesToTabs { get; } = new RoutedCommand(nameof(ConvertSpacesToTabs)); /// <summary> /// Converts leading tabs to spaces in the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand ConvertLeadingTabsToSpaces { get; } = new RoutedCommand(nameof(ConvertLeadingTabsToSpaces)); /// <summary> /// Converts leading spaces to tabs in the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand ConvertLeadingSpacesToTabs { get; } = new RoutedCommand(nameof(ConvertLeadingSpacesToTabs)); /// <summary>InputModifiers /// Runs the IIndentationStrategy on the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand IndentSelection { get; } = new RoutedCommand(nameof(IndentSelection), new KeyGesture(Key.I, KeyModifiers.Control)); } public static class ApplicationCommands { private static readonly KeyModifiers PlatformCommandKey = GetPlatformCommandKey(); public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete), new KeyGesture(Key.Delete)); public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture(Key.C, KeyModifiers.Control)); public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture(Key.X, KeyModifiers.Control)); public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture(Key.V, KeyModifiers.Control)); public static RoutedCommand SelectAll { get; } = new RoutedCommand(nameof(SelectAll), new KeyGesture(Key.A, PlatformCommandKey)); public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture(Key.Z, KeyModifiers.Control)); public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture(Key.Y, KeyModifiers.Control)); public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture(Key.F, KeyModifiers.Control)); public static RoutedCommand Replace { get; } = new RoutedCommand(nameof(Replace), GetReplaceKeyGesture()); private static OperatingSystemType GetOperatingSystemType() { return AvaloniaLocator.Current.GetService<IRuntimePlatform>().GetRuntimeInfo().OperatingSystem; } private static KeyModifiers GetPlatformCommandKey() { var os = GetOperatingSystemType(); if (os == OperatingSystemType.OSX) { return KeyModifiers.Meta; } return KeyModifiers.Control; } private static KeyGesture GetReplaceKeyGesture() { var os = GetOperatingSystemType(); if (os == OperatingSystemType.OSX) { return new KeyGesture(Key.F, KeyModifiers.Meta | KeyModifiers.Alt); } return new KeyGesture(Key.H, PlatformCommandKey); } } public static class EditingCommands { public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete)); public static RoutedCommand DeleteNextWord { get; } = new RoutedCommand(nameof(DeleteNextWord)); public static RoutedCommand Backspace { get; } = new RoutedCommand(nameof(Backspace)); public static RoutedCommand DeletePreviousWord { get; } = new RoutedCommand(nameof(DeletePreviousWord)); public static RoutedCommand EnterParagraphBreak { get; } = new RoutedCommand(nameof(EnterParagraphBreak)); public static RoutedCommand EnterLineBreak { get; } = new RoutedCommand(nameof(EnterLineBreak)); public static RoutedCommand TabForward { get; } = new RoutedCommand(nameof(TabForward)); public static RoutedCommand TabBackward { get; } = new RoutedCommand(nameof(TabBackward)); public static RoutedCommand MoveLeftByCharacter { get; } = new RoutedCommand(nameof(MoveLeftByCharacter)); public static RoutedCommand SelectLeftByCharacter { get; } = new RoutedCommand(nameof(SelectLeftByCharacter)); public static RoutedCommand MoveRightByCharacter { get; } = new RoutedCommand(nameof(MoveRightByCharacter)); public static RoutedCommand SelectRightByCharacter { get; } = new RoutedCommand(nameof(SelectRightByCharacter)); public static RoutedCommand MoveLeftByWord { get; } = new RoutedCommand(nameof(MoveLeftByWord)); public static RoutedCommand SelectLeftByWord { get; } = new RoutedCommand(nameof(SelectLeftByWord)); public static RoutedCommand MoveRightByWord { get; } = new RoutedCommand(nameof(MoveRightByWord)); public static RoutedCommand SelectRightByWord { get; } = new RoutedCommand(nameof(SelectRightByWord)); public static RoutedCommand MoveUpByLine { get; } = new RoutedCommand(nameof(MoveUpByLine)); public static RoutedCommand SelectUpByLine { get; } = new RoutedCommand(nameof(SelectUpByLine)); public static RoutedCommand MoveDownByLine { get; } = new RoutedCommand(nameof(MoveDownByLine)); public static RoutedCommand SelectDownByLine { get; } = new RoutedCommand(nameof(SelectDownByLine)); public static RoutedCommand MoveDownByPage { get; } = new RoutedCommand(nameof(MoveDownByPage)); public static RoutedCommand SelectDownByPage { get; } = new RoutedCommand(nameof(SelectDownByPage)); public static RoutedCommand MoveUpByPage { get; } = new RoutedCommand(nameof(MoveUpByPage)); public static RoutedCommand SelectUpByPage { get; } = new RoutedCommand(nameof(SelectUpByPage)); public static RoutedCommand MoveToLineStart { get; } = new RoutedCommand(nameof(MoveToLineStart)); public static RoutedCommand SelectToLineStart { get; } = new RoutedCommand(nameof(SelectToLineStart)); public static RoutedCommand MoveToLineEnd { get; } = new RoutedCommand(nameof(MoveToLineEnd)); public static RoutedCommand SelectToLineEnd { get; } = new RoutedCommand(nameof(SelectToLineEnd)); public static RoutedCommand MoveToDocumentStart { get; } = new RoutedCommand(nameof(MoveToDocumentStart)); public static RoutedCommand SelectToDocumentStart { get; } = new RoutedCommand(nameof(SelectToDocumentStart)); public static RoutedCommand MoveToDocumentEnd { get; } = new RoutedCommand(nameof(MoveToDocumentEnd)); public static RoutedCommand SelectToDocumentEnd { get; } = new RoutedCommand(nameof(SelectToDocumentEnd)); } } <MSG> Fixing Mac shortcuts using the Control key instead of the Command Key <DFF> @@ -104,13 +104,13 @@ namespace AvaloniaEdit private static readonly KeyModifiers PlatformCommandKey = GetPlatformCommandKey(); public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete), new KeyGesture(Key.Delete)); - public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture(Key.C, KeyModifiers.Control)); - public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture(Key.X, KeyModifiers.Control)); - public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture(Key.V, KeyModifiers.Control)); + public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture(Key.C, PlatformCommandKey)); + public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture(Key.X, PlatformCommandKey)); + public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture(Key.V, PlatformCommandKey)); public static RoutedCommand SelectAll { get; } = new RoutedCommand(nameof(SelectAll), new KeyGesture(Key.A, PlatformCommandKey)); - public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture(Key.Z, KeyModifiers.Control)); - public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture(Key.Y, KeyModifiers.Control)); - public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture(Key.F, KeyModifiers.Control)); + public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture(Key.Z, PlatformCommandKey)); + public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture(Key.Y, PlatformCommandKey)); + public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture(Key.F, PlatformCommandKey)); public static RoutedCommand Replace { get; } = new RoutedCommand(nameof(Replace), GetReplaceKeyGesture()); private static OperatingSystemType GetOperatingSystemType()
6
Fixing Mac shortcuts using the Control key instead of the Command Key
6
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10067274
<NME> AvaloniaEditCommands.cs <BEF> // 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.Diagnostics.CodeAnalysis; using Avalonia; using Avalonia.Input; using Avalonia.Platform; namespace AvaloniaEdit { /// <summary> /// Custom commands for AvalonEdit. /// </summary> public static class AvaloniaEditCommands { /// <summary> /// Toggles Overstrike mode /// The default shortcut is Ins. /// </summary> public static RoutedCommand ToggleOverstrike { get; } = new RoutedCommand(nameof(ToggleOverstrike), new KeyGesture(Key.Insert)); /// <summary> /// Deletes the current line. /// The default shortcut is Ctrl+D. /// </summary> public static RoutedCommand DeleteLine { get; } = new RoutedCommand(nameof(DeleteLine), new KeyGesture(Key.D, KeyModifiers.Control)); /// <summary> /// Removes leading whitespace from the selected lines (or the whole document if the selection is empty). /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] public static RoutedCommand RemoveLeadingWhitespace { get; } = new RoutedCommand(nameof(RemoveLeadingWhitespace)); /// <summary> /// Removes trailing whitespace from the selected lines (or the whole document if the selection is empty). /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] public static RoutedCommand RemoveTrailingWhitespace { get; } = new RoutedCommand(nameof(RemoveTrailingWhitespace)); /// <summary> /// Converts the selected text to upper case. /// </summary> public static RoutedCommand ConvertToUppercase { get; } = new RoutedCommand(nameof(ConvertToUppercase)); /// <summary> /// Converts the selected text to lower case. /// </summary> public static RoutedCommand ConvertToLowercase { get; } = new RoutedCommand(nameof(ConvertToLowercase)); /// <summary> /// Converts the selected text to title case. /// </summary> public static RoutedCommand ConvertToTitleCase { get; } = new RoutedCommand(nameof(ConvertToTitleCase)); /// <summary> /// Inverts the case of the selected text. /// </summary> public static RoutedCommand InvertCase { get; } = new RoutedCommand(nameof(InvertCase)); /// <summary> /// Converts tabs to spaces in the selected text. /// </summary> public static RoutedCommand ConvertTabsToSpaces { get; } = new RoutedCommand(nameof(ConvertTabsToSpaces)); /// <summary> /// Converts spaces to tabs in the selected text. /// </summary> public static RoutedCommand ConvertSpacesToTabs { get; } = new RoutedCommand(nameof(ConvertSpacesToTabs)); /// <summary> /// Converts leading tabs to spaces in the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand ConvertLeadingTabsToSpaces { get; } = new RoutedCommand(nameof(ConvertLeadingTabsToSpaces)); /// <summary> /// Converts leading spaces to tabs in the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand ConvertLeadingSpacesToTabs { get; } = new RoutedCommand(nameof(ConvertLeadingSpacesToTabs)); /// <summary>InputModifiers /// Runs the IIndentationStrategy on the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand IndentSelection { get; } = new RoutedCommand(nameof(IndentSelection), new KeyGesture(Key.I, KeyModifiers.Control)); } public static class ApplicationCommands { private static readonly KeyModifiers PlatformCommandKey = GetPlatformCommandKey(); public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete), new KeyGesture(Key.Delete)); public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture(Key.C, KeyModifiers.Control)); public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture(Key.X, KeyModifiers.Control)); public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture(Key.V, KeyModifiers.Control)); public static RoutedCommand SelectAll { get; } = new RoutedCommand(nameof(SelectAll), new KeyGesture(Key.A, PlatformCommandKey)); public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture(Key.Z, KeyModifiers.Control)); public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture(Key.Y, KeyModifiers.Control)); public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture(Key.F, KeyModifiers.Control)); public static RoutedCommand Replace { get; } = new RoutedCommand(nameof(Replace), GetReplaceKeyGesture()); private static OperatingSystemType GetOperatingSystemType() { return AvaloniaLocator.Current.GetService<IRuntimePlatform>().GetRuntimeInfo().OperatingSystem; } private static KeyModifiers GetPlatformCommandKey() { var os = GetOperatingSystemType(); if (os == OperatingSystemType.OSX) { return KeyModifiers.Meta; } return KeyModifiers.Control; } private static KeyGesture GetReplaceKeyGesture() { var os = GetOperatingSystemType(); if (os == OperatingSystemType.OSX) { return new KeyGesture(Key.F, KeyModifiers.Meta | KeyModifiers.Alt); } return new KeyGesture(Key.H, PlatformCommandKey); } } public static class EditingCommands { public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete)); public static RoutedCommand DeleteNextWord { get; } = new RoutedCommand(nameof(DeleteNextWord)); public static RoutedCommand Backspace { get; } = new RoutedCommand(nameof(Backspace)); public static RoutedCommand DeletePreviousWord { get; } = new RoutedCommand(nameof(DeletePreviousWord)); public static RoutedCommand EnterParagraphBreak { get; } = new RoutedCommand(nameof(EnterParagraphBreak)); public static RoutedCommand EnterLineBreak { get; } = new RoutedCommand(nameof(EnterLineBreak)); public static RoutedCommand TabForward { get; } = new RoutedCommand(nameof(TabForward)); public static RoutedCommand TabBackward { get; } = new RoutedCommand(nameof(TabBackward)); public static RoutedCommand MoveLeftByCharacter { get; } = new RoutedCommand(nameof(MoveLeftByCharacter)); public static RoutedCommand SelectLeftByCharacter { get; } = new RoutedCommand(nameof(SelectLeftByCharacter)); public static RoutedCommand MoveRightByCharacter { get; } = new RoutedCommand(nameof(MoveRightByCharacter)); public static RoutedCommand SelectRightByCharacter { get; } = new RoutedCommand(nameof(SelectRightByCharacter)); public static RoutedCommand MoveLeftByWord { get; } = new RoutedCommand(nameof(MoveLeftByWord)); public static RoutedCommand SelectLeftByWord { get; } = new RoutedCommand(nameof(SelectLeftByWord)); public static RoutedCommand MoveRightByWord { get; } = new RoutedCommand(nameof(MoveRightByWord)); public static RoutedCommand SelectRightByWord { get; } = new RoutedCommand(nameof(SelectRightByWord)); public static RoutedCommand MoveUpByLine { get; } = new RoutedCommand(nameof(MoveUpByLine)); public static RoutedCommand SelectUpByLine { get; } = new RoutedCommand(nameof(SelectUpByLine)); public static RoutedCommand MoveDownByLine { get; } = new RoutedCommand(nameof(MoveDownByLine)); public static RoutedCommand SelectDownByLine { get; } = new RoutedCommand(nameof(SelectDownByLine)); public static RoutedCommand MoveDownByPage { get; } = new RoutedCommand(nameof(MoveDownByPage)); public static RoutedCommand SelectDownByPage { get; } = new RoutedCommand(nameof(SelectDownByPage)); public static RoutedCommand MoveUpByPage { get; } = new RoutedCommand(nameof(MoveUpByPage)); public static RoutedCommand SelectUpByPage { get; } = new RoutedCommand(nameof(SelectUpByPage)); public static RoutedCommand MoveToLineStart { get; } = new RoutedCommand(nameof(MoveToLineStart)); public static RoutedCommand SelectToLineStart { get; } = new RoutedCommand(nameof(SelectToLineStart)); public static RoutedCommand MoveToLineEnd { get; } = new RoutedCommand(nameof(MoveToLineEnd)); public static RoutedCommand SelectToLineEnd { get; } = new RoutedCommand(nameof(SelectToLineEnd)); public static RoutedCommand MoveToDocumentStart { get; } = new RoutedCommand(nameof(MoveToDocumentStart)); public static RoutedCommand SelectToDocumentStart { get; } = new RoutedCommand(nameof(SelectToDocumentStart)); public static RoutedCommand MoveToDocumentEnd { get; } = new RoutedCommand(nameof(MoveToDocumentEnd)); public static RoutedCommand SelectToDocumentEnd { get; } = new RoutedCommand(nameof(SelectToDocumentEnd)); } } <MSG> Fixing Mac shortcuts using the Control key instead of the Command Key <DFF> @@ -104,13 +104,13 @@ namespace AvaloniaEdit private static readonly KeyModifiers PlatformCommandKey = GetPlatformCommandKey(); public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete), new KeyGesture(Key.Delete)); - public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture(Key.C, KeyModifiers.Control)); - public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture(Key.X, KeyModifiers.Control)); - public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture(Key.V, KeyModifiers.Control)); + public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture(Key.C, PlatformCommandKey)); + public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture(Key.X, PlatformCommandKey)); + public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture(Key.V, PlatformCommandKey)); public static RoutedCommand SelectAll { get; } = new RoutedCommand(nameof(SelectAll), new KeyGesture(Key.A, PlatformCommandKey)); - public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture(Key.Z, KeyModifiers.Control)); - public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture(Key.Y, KeyModifiers.Control)); - public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture(Key.F, KeyModifiers.Control)); + public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture(Key.Z, PlatformCommandKey)); + public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture(Key.Y, PlatformCommandKey)); + public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture(Key.F, PlatformCommandKey)); public static RoutedCommand Replace { get; } = new RoutedCommand(nameof(Replace), GetReplaceKeyGesture()); private static OperatingSystemType GetOperatingSystemType()
6
Fixing Mac shortcuts using the Control key instead of the Command Key
6
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10067275
<NME> AvaloniaEditCommands.cs <BEF> // 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.Diagnostics.CodeAnalysis; using Avalonia; using Avalonia.Input; using Avalonia.Platform; namespace AvaloniaEdit { /// <summary> /// Custom commands for AvalonEdit. /// </summary> public static class AvaloniaEditCommands { /// <summary> /// Toggles Overstrike mode /// The default shortcut is Ins. /// </summary> public static RoutedCommand ToggleOverstrike { get; } = new RoutedCommand(nameof(ToggleOverstrike), new KeyGesture(Key.Insert)); /// <summary> /// Deletes the current line. /// The default shortcut is Ctrl+D. /// </summary> public static RoutedCommand DeleteLine { get; } = new RoutedCommand(nameof(DeleteLine), new KeyGesture(Key.D, KeyModifiers.Control)); /// <summary> /// Removes leading whitespace from the selected lines (or the whole document if the selection is empty). /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] public static RoutedCommand RemoveLeadingWhitespace { get; } = new RoutedCommand(nameof(RemoveLeadingWhitespace)); /// <summary> /// Removes trailing whitespace from the selected lines (or the whole document if the selection is empty). /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] public static RoutedCommand RemoveTrailingWhitespace { get; } = new RoutedCommand(nameof(RemoveTrailingWhitespace)); /// <summary> /// Converts the selected text to upper case. /// </summary> public static RoutedCommand ConvertToUppercase { get; } = new RoutedCommand(nameof(ConvertToUppercase)); /// <summary> /// Converts the selected text to lower case. /// </summary> public static RoutedCommand ConvertToLowercase { get; } = new RoutedCommand(nameof(ConvertToLowercase)); /// <summary> /// Converts the selected text to title case. /// </summary> public static RoutedCommand ConvertToTitleCase { get; } = new RoutedCommand(nameof(ConvertToTitleCase)); /// <summary> /// Inverts the case of the selected text. /// </summary> public static RoutedCommand InvertCase { get; } = new RoutedCommand(nameof(InvertCase)); /// <summary> /// Converts tabs to spaces in the selected text. /// </summary> public static RoutedCommand ConvertTabsToSpaces { get; } = new RoutedCommand(nameof(ConvertTabsToSpaces)); /// <summary> /// Converts spaces to tabs in the selected text. /// </summary> public static RoutedCommand ConvertSpacesToTabs { get; } = new RoutedCommand(nameof(ConvertSpacesToTabs)); /// <summary> /// Converts leading tabs to spaces in the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand ConvertLeadingTabsToSpaces { get; } = new RoutedCommand(nameof(ConvertLeadingTabsToSpaces)); /// <summary> /// Converts leading spaces to tabs in the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand ConvertLeadingSpacesToTabs { get; } = new RoutedCommand(nameof(ConvertLeadingSpacesToTabs)); /// <summary>InputModifiers /// Runs the IIndentationStrategy on the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand IndentSelection { get; } = new RoutedCommand(nameof(IndentSelection), new KeyGesture(Key.I, KeyModifiers.Control)); } public static class ApplicationCommands { private static readonly KeyModifiers PlatformCommandKey = GetPlatformCommandKey(); public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete), new KeyGesture(Key.Delete)); public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture(Key.C, KeyModifiers.Control)); public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture(Key.X, KeyModifiers.Control)); public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture(Key.V, KeyModifiers.Control)); public static RoutedCommand SelectAll { get; } = new RoutedCommand(nameof(SelectAll), new KeyGesture(Key.A, PlatformCommandKey)); public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture(Key.Z, KeyModifiers.Control)); public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture(Key.Y, KeyModifiers.Control)); public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture(Key.F, KeyModifiers.Control)); public static RoutedCommand Replace { get; } = new RoutedCommand(nameof(Replace), GetReplaceKeyGesture()); private static OperatingSystemType GetOperatingSystemType() { return AvaloniaLocator.Current.GetService<IRuntimePlatform>().GetRuntimeInfo().OperatingSystem; } private static KeyModifiers GetPlatformCommandKey() { var os = GetOperatingSystemType(); if (os == OperatingSystemType.OSX) { return KeyModifiers.Meta; } return KeyModifiers.Control; } private static KeyGesture GetReplaceKeyGesture() { var os = GetOperatingSystemType(); if (os == OperatingSystemType.OSX) { return new KeyGesture(Key.F, KeyModifiers.Meta | KeyModifiers.Alt); } return new KeyGesture(Key.H, PlatformCommandKey); } } public static class EditingCommands { public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete)); public static RoutedCommand DeleteNextWord { get; } = new RoutedCommand(nameof(DeleteNextWord)); public static RoutedCommand Backspace { get; } = new RoutedCommand(nameof(Backspace)); public static RoutedCommand DeletePreviousWord { get; } = new RoutedCommand(nameof(DeletePreviousWord)); public static RoutedCommand EnterParagraphBreak { get; } = new RoutedCommand(nameof(EnterParagraphBreak)); public static RoutedCommand EnterLineBreak { get; } = new RoutedCommand(nameof(EnterLineBreak)); public static RoutedCommand TabForward { get; } = new RoutedCommand(nameof(TabForward)); public static RoutedCommand TabBackward { get; } = new RoutedCommand(nameof(TabBackward)); public static RoutedCommand MoveLeftByCharacter { get; } = new RoutedCommand(nameof(MoveLeftByCharacter)); public static RoutedCommand SelectLeftByCharacter { get; } = new RoutedCommand(nameof(SelectLeftByCharacter)); public static RoutedCommand MoveRightByCharacter { get; } = new RoutedCommand(nameof(MoveRightByCharacter)); public static RoutedCommand SelectRightByCharacter { get; } = new RoutedCommand(nameof(SelectRightByCharacter)); public static RoutedCommand MoveLeftByWord { get; } = new RoutedCommand(nameof(MoveLeftByWord)); public static RoutedCommand SelectLeftByWord { get; } = new RoutedCommand(nameof(SelectLeftByWord)); public static RoutedCommand MoveRightByWord { get; } = new RoutedCommand(nameof(MoveRightByWord)); public static RoutedCommand SelectRightByWord { get; } = new RoutedCommand(nameof(SelectRightByWord)); public static RoutedCommand MoveUpByLine { get; } = new RoutedCommand(nameof(MoveUpByLine)); public static RoutedCommand SelectUpByLine { get; } = new RoutedCommand(nameof(SelectUpByLine)); public static RoutedCommand MoveDownByLine { get; } = new RoutedCommand(nameof(MoveDownByLine)); public static RoutedCommand SelectDownByLine { get; } = new RoutedCommand(nameof(SelectDownByLine)); public static RoutedCommand MoveDownByPage { get; } = new RoutedCommand(nameof(MoveDownByPage)); public static RoutedCommand SelectDownByPage { get; } = new RoutedCommand(nameof(SelectDownByPage)); public static RoutedCommand MoveUpByPage { get; } = new RoutedCommand(nameof(MoveUpByPage)); public static RoutedCommand SelectUpByPage { get; } = new RoutedCommand(nameof(SelectUpByPage)); public static RoutedCommand MoveToLineStart { get; } = new RoutedCommand(nameof(MoveToLineStart)); public static RoutedCommand SelectToLineStart { get; } = new RoutedCommand(nameof(SelectToLineStart)); public static RoutedCommand MoveToLineEnd { get; } = new RoutedCommand(nameof(MoveToLineEnd)); public static RoutedCommand SelectToLineEnd { get; } = new RoutedCommand(nameof(SelectToLineEnd)); public static RoutedCommand MoveToDocumentStart { get; } = new RoutedCommand(nameof(MoveToDocumentStart)); public static RoutedCommand SelectToDocumentStart { get; } = new RoutedCommand(nameof(SelectToDocumentStart)); public static RoutedCommand MoveToDocumentEnd { get; } = new RoutedCommand(nameof(MoveToDocumentEnd)); public static RoutedCommand SelectToDocumentEnd { get; } = new RoutedCommand(nameof(SelectToDocumentEnd)); } } <MSG> Fixing Mac shortcuts using the Control key instead of the Command Key <DFF> @@ -104,13 +104,13 @@ namespace AvaloniaEdit private static readonly KeyModifiers PlatformCommandKey = GetPlatformCommandKey(); public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete), new KeyGesture(Key.Delete)); - public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture(Key.C, KeyModifiers.Control)); - public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture(Key.X, KeyModifiers.Control)); - public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture(Key.V, KeyModifiers.Control)); + public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture(Key.C, PlatformCommandKey)); + public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture(Key.X, PlatformCommandKey)); + public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture(Key.V, PlatformCommandKey)); public static RoutedCommand SelectAll { get; } = new RoutedCommand(nameof(SelectAll), new KeyGesture(Key.A, PlatformCommandKey)); - public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture(Key.Z, KeyModifiers.Control)); - public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture(Key.Y, KeyModifiers.Control)); - public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture(Key.F, KeyModifiers.Control)); + public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture(Key.Z, PlatformCommandKey)); + public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture(Key.Y, PlatformCommandKey)); + public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture(Key.F, PlatformCommandKey)); public static RoutedCommand Replace { get; } = new RoutedCommand(nameof(Replace), GetReplaceKeyGesture()); private static OperatingSystemType GetOperatingSystemType()
6
Fixing Mac shortcuts using the Control key instead of the Command Key
6
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10067276
<NME> AvaloniaEditCommands.cs <BEF> // 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.Diagnostics.CodeAnalysis; using Avalonia; using Avalonia.Input; using Avalonia.Platform; namespace AvaloniaEdit { /// <summary> /// Custom commands for AvalonEdit. /// </summary> public static class AvaloniaEditCommands { /// <summary> /// Toggles Overstrike mode /// The default shortcut is Ins. /// </summary> public static RoutedCommand ToggleOverstrike { get; } = new RoutedCommand(nameof(ToggleOverstrike), new KeyGesture(Key.Insert)); /// <summary> /// Deletes the current line. /// The default shortcut is Ctrl+D. /// </summary> public static RoutedCommand DeleteLine { get; } = new RoutedCommand(nameof(DeleteLine), new KeyGesture(Key.D, KeyModifiers.Control)); /// <summary> /// Removes leading whitespace from the selected lines (or the whole document if the selection is empty). /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] public static RoutedCommand RemoveLeadingWhitespace { get; } = new RoutedCommand(nameof(RemoveLeadingWhitespace)); /// <summary> /// Removes trailing whitespace from the selected lines (or the whole document if the selection is empty). /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] public static RoutedCommand RemoveTrailingWhitespace { get; } = new RoutedCommand(nameof(RemoveTrailingWhitespace)); /// <summary> /// Converts the selected text to upper case. /// </summary> public static RoutedCommand ConvertToUppercase { get; } = new RoutedCommand(nameof(ConvertToUppercase)); /// <summary> /// Converts the selected text to lower case. /// </summary> public static RoutedCommand ConvertToLowercase { get; } = new RoutedCommand(nameof(ConvertToLowercase)); /// <summary> /// Converts the selected text to title case. /// </summary> public static RoutedCommand ConvertToTitleCase { get; } = new RoutedCommand(nameof(ConvertToTitleCase)); /// <summary> /// Inverts the case of the selected text. /// </summary> public static RoutedCommand InvertCase { get; } = new RoutedCommand(nameof(InvertCase)); /// <summary> /// Converts tabs to spaces in the selected text. /// </summary> public static RoutedCommand ConvertTabsToSpaces { get; } = new RoutedCommand(nameof(ConvertTabsToSpaces)); /// <summary> /// Converts spaces to tabs in the selected text. /// </summary> public static RoutedCommand ConvertSpacesToTabs { get; } = new RoutedCommand(nameof(ConvertSpacesToTabs)); /// <summary> /// Converts leading tabs to spaces in the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand ConvertLeadingTabsToSpaces { get; } = new RoutedCommand(nameof(ConvertLeadingTabsToSpaces)); /// <summary> /// Converts leading spaces to tabs in the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand ConvertLeadingSpacesToTabs { get; } = new RoutedCommand(nameof(ConvertLeadingSpacesToTabs)); /// <summary>InputModifiers /// Runs the IIndentationStrategy on the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand IndentSelection { get; } = new RoutedCommand(nameof(IndentSelection), new KeyGesture(Key.I, KeyModifiers.Control)); } public static class ApplicationCommands { private static readonly KeyModifiers PlatformCommandKey = GetPlatformCommandKey(); public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete), new KeyGesture(Key.Delete)); public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture(Key.C, KeyModifiers.Control)); public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture(Key.X, KeyModifiers.Control)); public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture(Key.V, KeyModifiers.Control)); public static RoutedCommand SelectAll { get; } = new RoutedCommand(nameof(SelectAll), new KeyGesture(Key.A, PlatformCommandKey)); public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture(Key.Z, KeyModifiers.Control)); public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture(Key.Y, KeyModifiers.Control)); public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture(Key.F, KeyModifiers.Control)); public static RoutedCommand Replace { get; } = new RoutedCommand(nameof(Replace), GetReplaceKeyGesture()); private static OperatingSystemType GetOperatingSystemType() { return AvaloniaLocator.Current.GetService<IRuntimePlatform>().GetRuntimeInfo().OperatingSystem; } private static KeyModifiers GetPlatformCommandKey() { var os = GetOperatingSystemType(); if (os == OperatingSystemType.OSX) { return KeyModifiers.Meta; } return KeyModifiers.Control; } private static KeyGesture GetReplaceKeyGesture() { var os = GetOperatingSystemType(); if (os == OperatingSystemType.OSX) { return new KeyGesture(Key.F, KeyModifiers.Meta | KeyModifiers.Alt); } return new KeyGesture(Key.H, PlatformCommandKey); } } public static class EditingCommands { public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete)); public static RoutedCommand DeleteNextWord { get; } = new RoutedCommand(nameof(DeleteNextWord)); public static RoutedCommand Backspace { get; } = new RoutedCommand(nameof(Backspace)); public static RoutedCommand DeletePreviousWord { get; } = new RoutedCommand(nameof(DeletePreviousWord)); public static RoutedCommand EnterParagraphBreak { get; } = new RoutedCommand(nameof(EnterParagraphBreak)); public static RoutedCommand EnterLineBreak { get; } = new RoutedCommand(nameof(EnterLineBreak)); public static RoutedCommand TabForward { get; } = new RoutedCommand(nameof(TabForward)); public static RoutedCommand TabBackward { get; } = new RoutedCommand(nameof(TabBackward)); public static RoutedCommand MoveLeftByCharacter { get; } = new RoutedCommand(nameof(MoveLeftByCharacter)); public static RoutedCommand SelectLeftByCharacter { get; } = new RoutedCommand(nameof(SelectLeftByCharacter)); public static RoutedCommand MoveRightByCharacter { get; } = new RoutedCommand(nameof(MoveRightByCharacter)); public static RoutedCommand SelectRightByCharacter { get; } = new RoutedCommand(nameof(SelectRightByCharacter)); public static RoutedCommand MoveLeftByWord { get; } = new RoutedCommand(nameof(MoveLeftByWord)); public static RoutedCommand SelectLeftByWord { get; } = new RoutedCommand(nameof(SelectLeftByWord)); public static RoutedCommand MoveRightByWord { get; } = new RoutedCommand(nameof(MoveRightByWord)); public static RoutedCommand SelectRightByWord { get; } = new RoutedCommand(nameof(SelectRightByWord)); public static RoutedCommand MoveUpByLine { get; } = new RoutedCommand(nameof(MoveUpByLine)); public static RoutedCommand SelectUpByLine { get; } = new RoutedCommand(nameof(SelectUpByLine)); public static RoutedCommand MoveDownByLine { get; } = new RoutedCommand(nameof(MoveDownByLine)); public static RoutedCommand SelectDownByLine { get; } = new RoutedCommand(nameof(SelectDownByLine)); public static RoutedCommand MoveDownByPage { get; } = new RoutedCommand(nameof(MoveDownByPage)); public static RoutedCommand SelectDownByPage { get; } = new RoutedCommand(nameof(SelectDownByPage)); public static RoutedCommand MoveUpByPage { get; } = new RoutedCommand(nameof(MoveUpByPage)); public static RoutedCommand SelectUpByPage { get; } = new RoutedCommand(nameof(SelectUpByPage)); public static RoutedCommand MoveToLineStart { get; } = new RoutedCommand(nameof(MoveToLineStart)); public static RoutedCommand SelectToLineStart { get; } = new RoutedCommand(nameof(SelectToLineStart)); public static RoutedCommand MoveToLineEnd { get; } = new RoutedCommand(nameof(MoveToLineEnd)); public static RoutedCommand SelectToLineEnd { get; } = new RoutedCommand(nameof(SelectToLineEnd)); public static RoutedCommand MoveToDocumentStart { get; } = new RoutedCommand(nameof(MoveToDocumentStart)); public static RoutedCommand SelectToDocumentStart { get; } = new RoutedCommand(nameof(SelectToDocumentStart)); public static RoutedCommand MoveToDocumentEnd { get; } = new RoutedCommand(nameof(MoveToDocumentEnd)); public static RoutedCommand SelectToDocumentEnd { get; } = new RoutedCommand(nameof(SelectToDocumentEnd)); } } <MSG> Fixing Mac shortcuts using the Control key instead of the Command Key <DFF> @@ -104,13 +104,13 @@ namespace AvaloniaEdit private static readonly KeyModifiers PlatformCommandKey = GetPlatformCommandKey(); public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete), new KeyGesture(Key.Delete)); - public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture(Key.C, KeyModifiers.Control)); - public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture(Key.X, KeyModifiers.Control)); - public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture(Key.V, KeyModifiers.Control)); + public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture(Key.C, PlatformCommandKey)); + public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture(Key.X, PlatformCommandKey)); + public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture(Key.V, PlatformCommandKey)); public static RoutedCommand SelectAll { get; } = new RoutedCommand(nameof(SelectAll), new KeyGesture(Key.A, PlatformCommandKey)); - public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture(Key.Z, KeyModifiers.Control)); - public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture(Key.Y, KeyModifiers.Control)); - public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture(Key.F, KeyModifiers.Control)); + public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture(Key.Z, PlatformCommandKey)); + public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture(Key.Y, PlatformCommandKey)); + public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture(Key.F, PlatformCommandKey)); public static RoutedCommand Replace { get; } = new RoutedCommand(nameof(Replace), GetReplaceKeyGesture()); private static OperatingSystemType GetOperatingSystemType()
6
Fixing Mac shortcuts using the Control key instead of the Command Key
6
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10067277
<NME> AvaloniaEditCommands.cs <BEF> // 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.Diagnostics.CodeAnalysis; using Avalonia; using Avalonia.Input; using Avalonia.Platform; namespace AvaloniaEdit { /// <summary> /// Custom commands for AvalonEdit. /// </summary> public static class AvaloniaEditCommands { /// <summary> /// Toggles Overstrike mode /// The default shortcut is Ins. /// </summary> public static RoutedCommand ToggleOverstrike { get; } = new RoutedCommand(nameof(ToggleOverstrike), new KeyGesture(Key.Insert)); /// <summary> /// Deletes the current line. /// The default shortcut is Ctrl+D. /// </summary> public static RoutedCommand DeleteLine { get; } = new RoutedCommand(nameof(DeleteLine), new KeyGesture(Key.D, KeyModifiers.Control)); /// <summary> /// Removes leading whitespace from the selected lines (or the whole document if the selection is empty). /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] public static RoutedCommand RemoveLeadingWhitespace { get; } = new RoutedCommand(nameof(RemoveLeadingWhitespace)); /// <summary> /// Removes trailing whitespace from the selected lines (or the whole document if the selection is empty). /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] public static RoutedCommand RemoveTrailingWhitespace { get; } = new RoutedCommand(nameof(RemoveTrailingWhitespace)); /// <summary> /// Converts the selected text to upper case. /// </summary> public static RoutedCommand ConvertToUppercase { get; } = new RoutedCommand(nameof(ConvertToUppercase)); /// <summary> /// Converts the selected text to lower case. /// </summary> public static RoutedCommand ConvertToLowercase { get; } = new RoutedCommand(nameof(ConvertToLowercase)); /// <summary> /// Converts the selected text to title case. /// </summary> public static RoutedCommand ConvertToTitleCase { get; } = new RoutedCommand(nameof(ConvertToTitleCase)); /// <summary> /// Inverts the case of the selected text. /// </summary> public static RoutedCommand InvertCase { get; } = new RoutedCommand(nameof(InvertCase)); /// <summary> /// Converts tabs to spaces in the selected text. /// </summary> public static RoutedCommand ConvertTabsToSpaces { get; } = new RoutedCommand(nameof(ConvertTabsToSpaces)); /// <summary> /// Converts spaces to tabs in the selected text. /// </summary> public static RoutedCommand ConvertSpacesToTabs { get; } = new RoutedCommand(nameof(ConvertSpacesToTabs)); /// <summary> /// Converts leading tabs to spaces in the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand ConvertLeadingTabsToSpaces { get; } = new RoutedCommand(nameof(ConvertLeadingTabsToSpaces)); /// <summary> /// Converts leading spaces to tabs in the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand ConvertLeadingSpacesToTabs { get; } = new RoutedCommand(nameof(ConvertLeadingSpacesToTabs)); /// <summary>InputModifiers /// Runs the IIndentationStrategy on the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand IndentSelection { get; } = new RoutedCommand(nameof(IndentSelection), new KeyGesture(Key.I, KeyModifiers.Control)); } public static class ApplicationCommands { private static readonly KeyModifiers PlatformCommandKey = GetPlatformCommandKey(); public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete), new KeyGesture(Key.Delete)); public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture(Key.C, KeyModifiers.Control)); public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture(Key.X, KeyModifiers.Control)); public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture(Key.V, KeyModifiers.Control)); public static RoutedCommand SelectAll { get; } = new RoutedCommand(nameof(SelectAll), new KeyGesture(Key.A, PlatformCommandKey)); public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture(Key.Z, KeyModifiers.Control)); public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture(Key.Y, KeyModifiers.Control)); public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture(Key.F, KeyModifiers.Control)); public static RoutedCommand Replace { get; } = new RoutedCommand(nameof(Replace), GetReplaceKeyGesture()); private static OperatingSystemType GetOperatingSystemType() { return AvaloniaLocator.Current.GetService<IRuntimePlatform>().GetRuntimeInfo().OperatingSystem; } private static KeyModifiers GetPlatformCommandKey() { var os = GetOperatingSystemType(); if (os == OperatingSystemType.OSX) { return KeyModifiers.Meta; } return KeyModifiers.Control; } private static KeyGesture GetReplaceKeyGesture() { var os = GetOperatingSystemType(); if (os == OperatingSystemType.OSX) { return new KeyGesture(Key.F, KeyModifiers.Meta | KeyModifiers.Alt); } return new KeyGesture(Key.H, PlatformCommandKey); } } public static class EditingCommands { public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete)); public static RoutedCommand DeleteNextWord { get; } = new RoutedCommand(nameof(DeleteNextWord)); public static RoutedCommand Backspace { get; } = new RoutedCommand(nameof(Backspace)); public static RoutedCommand DeletePreviousWord { get; } = new RoutedCommand(nameof(DeletePreviousWord)); public static RoutedCommand EnterParagraphBreak { get; } = new RoutedCommand(nameof(EnterParagraphBreak)); public static RoutedCommand EnterLineBreak { get; } = new RoutedCommand(nameof(EnterLineBreak)); public static RoutedCommand TabForward { get; } = new RoutedCommand(nameof(TabForward)); public static RoutedCommand TabBackward { get; } = new RoutedCommand(nameof(TabBackward)); public static RoutedCommand MoveLeftByCharacter { get; } = new RoutedCommand(nameof(MoveLeftByCharacter)); public static RoutedCommand SelectLeftByCharacter { get; } = new RoutedCommand(nameof(SelectLeftByCharacter)); public static RoutedCommand MoveRightByCharacter { get; } = new RoutedCommand(nameof(MoveRightByCharacter)); public static RoutedCommand SelectRightByCharacter { get; } = new RoutedCommand(nameof(SelectRightByCharacter)); public static RoutedCommand MoveLeftByWord { get; } = new RoutedCommand(nameof(MoveLeftByWord)); public static RoutedCommand SelectLeftByWord { get; } = new RoutedCommand(nameof(SelectLeftByWord)); public static RoutedCommand MoveRightByWord { get; } = new RoutedCommand(nameof(MoveRightByWord)); public static RoutedCommand SelectRightByWord { get; } = new RoutedCommand(nameof(SelectRightByWord)); public static RoutedCommand MoveUpByLine { get; } = new RoutedCommand(nameof(MoveUpByLine)); public static RoutedCommand SelectUpByLine { get; } = new RoutedCommand(nameof(SelectUpByLine)); public static RoutedCommand MoveDownByLine { get; } = new RoutedCommand(nameof(MoveDownByLine)); public static RoutedCommand SelectDownByLine { get; } = new RoutedCommand(nameof(SelectDownByLine)); public static RoutedCommand MoveDownByPage { get; } = new RoutedCommand(nameof(MoveDownByPage)); public static RoutedCommand SelectDownByPage { get; } = new RoutedCommand(nameof(SelectDownByPage)); public static RoutedCommand MoveUpByPage { get; } = new RoutedCommand(nameof(MoveUpByPage)); public static RoutedCommand SelectUpByPage { get; } = new RoutedCommand(nameof(SelectUpByPage)); public static RoutedCommand MoveToLineStart { get; } = new RoutedCommand(nameof(MoveToLineStart)); public static RoutedCommand SelectToLineStart { get; } = new RoutedCommand(nameof(SelectToLineStart)); public static RoutedCommand MoveToLineEnd { get; } = new RoutedCommand(nameof(MoveToLineEnd)); public static RoutedCommand SelectToLineEnd { get; } = new RoutedCommand(nameof(SelectToLineEnd)); public static RoutedCommand MoveToDocumentStart { get; } = new RoutedCommand(nameof(MoveToDocumentStart)); public static RoutedCommand SelectToDocumentStart { get; } = new RoutedCommand(nameof(SelectToDocumentStart)); public static RoutedCommand MoveToDocumentEnd { get; } = new RoutedCommand(nameof(MoveToDocumentEnd)); public static RoutedCommand SelectToDocumentEnd { get; } = new RoutedCommand(nameof(SelectToDocumentEnd)); } } <MSG> Fixing Mac shortcuts using the Control key instead of the Command Key <DFF> @@ -104,13 +104,13 @@ namespace AvaloniaEdit private static readonly KeyModifiers PlatformCommandKey = GetPlatformCommandKey(); public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete), new KeyGesture(Key.Delete)); - public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture(Key.C, KeyModifiers.Control)); - public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture(Key.X, KeyModifiers.Control)); - public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture(Key.V, KeyModifiers.Control)); + public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture(Key.C, PlatformCommandKey)); + public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture(Key.X, PlatformCommandKey)); + public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture(Key.V, PlatformCommandKey)); public static RoutedCommand SelectAll { get; } = new RoutedCommand(nameof(SelectAll), new KeyGesture(Key.A, PlatformCommandKey)); - public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture(Key.Z, KeyModifiers.Control)); - public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture(Key.Y, KeyModifiers.Control)); - public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture(Key.F, KeyModifiers.Control)); + public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture(Key.Z, PlatformCommandKey)); + public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture(Key.Y, PlatformCommandKey)); + public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture(Key.F, PlatformCommandKey)); public static RoutedCommand Replace { get; } = new RoutedCommand(nameof(Replace), GetReplaceKeyGesture()); private static OperatingSystemType GetOperatingSystemType()
6
Fixing Mac shortcuts using the Control key instead of the Command Key
6
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10067278
<NME> AvaloniaEditCommands.cs <BEF> // 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.Diagnostics.CodeAnalysis; using Avalonia; using Avalonia.Input; using Avalonia.Platform; namespace AvaloniaEdit { /// <summary> /// Custom commands for AvalonEdit. /// </summary> public static class AvaloniaEditCommands { /// <summary> /// Toggles Overstrike mode /// The default shortcut is Ins. /// </summary> public static RoutedCommand ToggleOverstrike { get; } = new RoutedCommand(nameof(ToggleOverstrike), new KeyGesture(Key.Insert)); /// <summary> /// Deletes the current line. /// The default shortcut is Ctrl+D. /// </summary> public static RoutedCommand DeleteLine { get; } = new RoutedCommand(nameof(DeleteLine), new KeyGesture(Key.D, KeyModifiers.Control)); /// <summary> /// Removes leading whitespace from the selected lines (or the whole document if the selection is empty). /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] public static RoutedCommand RemoveLeadingWhitespace { get; } = new RoutedCommand(nameof(RemoveLeadingWhitespace)); /// <summary> /// Removes trailing whitespace from the selected lines (or the whole document if the selection is empty). /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] public static RoutedCommand RemoveTrailingWhitespace { get; } = new RoutedCommand(nameof(RemoveTrailingWhitespace)); /// <summary> /// Converts the selected text to upper case. /// </summary> public static RoutedCommand ConvertToUppercase { get; } = new RoutedCommand(nameof(ConvertToUppercase)); /// <summary> /// Converts the selected text to lower case. /// </summary> public static RoutedCommand ConvertToLowercase { get; } = new RoutedCommand(nameof(ConvertToLowercase)); /// <summary> /// Converts the selected text to title case. /// </summary> public static RoutedCommand ConvertToTitleCase { get; } = new RoutedCommand(nameof(ConvertToTitleCase)); /// <summary> /// Inverts the case of the selected text. /// </summary> public static RoutedCommand InvertCase { get; } = new RoutedCommand(nameof(InvertCase)); /// <summary> /// Converts tabs to spaces in the selected text. /// </summary> public static RoutedCommand ConvertTabsToSpaces { get; } = new RoutedCommand(nameof(ConvertTabsToSpaces)); /// <summary> /// Converts spaces to tabs in the selected text. /// </summary> public static RoutedCommand ConvertSpacesToTabs { get; } = new RoutedCommand(nameof(ConvertSpacesToTabs)); /// <summary> /// Converts leading tabs to spaces in the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand ConvertLeadingTabsToSpaces { get; } = new RoutedCommand(nameof(ConvertLeadingTabsToSpaces)); /// <summary> /// Converts leading spaces to tabs in the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand ConvertLeadingSpacesToTabs { get; } = new RoutedCommand(nameof(ConvertLeadingSpacesToTabs)); /// <summary>InputModifiers /// Runs the IIndentationStrategy on the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand IndentSelection { get; } = new RoutedCommand(nameof(IndentSelection), new KeyGesture(Key.I, KeyModifiers.Control)); } public static class ApplicationCommands { private static readonly KeyModifiers PlatformCommandKey = GetPlatformCommandKey(); public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete), new KeyGesture(Key.Delete)); public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture(Key.C, KeyModifiers.Control)); public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture(Key.X, KeyModifiers.Control)); public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture(Key.V, KeyModifiers.Control)); public static RoutedCommand SelectAll { get; } = new RoutedCommand(nameof(SelectAll), new KeyGesture(Key.A, PlatformCommandKey)); public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture(Key.Z, KeyModifiers.Control)); public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture(Key.Y, KeyModifiers.Control)); public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture(Key.F, KeyModifiers.Control)); public static RoutedCommand Replace { get; } = new RoutedCommand(nameof(Replace), GetReplaceKeyGesture()); private static OperatingSystemType GetOperatingSystemType() { return AvaloniaLocator.Current.GetService<IRuntimePlatform>().GetRuntimeInfo().OperatingSystem; } private static KeyModifiers GetPlatformCommandKey() { var os = GetOperatingSystemType(); if (os == OperatingSystemType.OSX) { return KeyModifiers.Meta; } return KeyModifiers.Control; } private static KeyGesture GetReplaceKeyGesture() { var os = GetOperatingSystemType(); if (os == OperatingSystemType.OSX) { return new KeyGesture(Key.F, KeyModifiers.Meta | KeyModifiers.Alt); } return new KeyGesture(Key.H, PlatformCommandKey); } } public static class EditingCommands { public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete)); public static RoutedCommand DeleteNextWord { get; } = new RoutedCommand(nameof(DeleteNextWord)); public static RoutedCommand Backspace { get; } = new RoutedCommand(nameof(Backspace)); public static RoutedCommand DeletePreviousWord { get; } = new RoutedCommand(nameof(DeletePreviousWord)); public static RoutedCommand EnterParagraphBreak { get; } = new RoutedCommand(nameof(EnterParagraphBreak)); public static RoutedCommand EnterLineBreak { get; } = new RoutedCommand(nameof(EnterLineBreak)); public static RoutedCommand TabForward { get; } = new RoutedCommand(nameof(TabForward)); public static RoutedCommand TabBackward { get; } = new RoutedCommand(nameof(TabBackward)); public static RoutedCommand MoveLeftByCharacter { get; } = new RoutedCommand(nameof(MoveLeftByCharacter)); public static RoutedCommand SelectLeftByCharacter { get; } = new RoutedCommand(nameof(SelectLeftByCharacter)); public static RoutedCommand MoveRightByCharacter { get; } = new RoutedCommand(nameof(MoveRightByCharacter)); public static RoutedCommand SelectRightByCharacter { get; } = new RoutedCommand(nameof(SelectRightByCharacter)); public static RoutedCommand MoveLeftByWord { get; } = new RoutedCommand(nameof(MoveLeftByWord)); public static RoutedCommand SelectLeftByWord { get; } = new RoutedCommand(nameof(SelectLeftByWord)); public static RoutedCommand MoveRightByWord { get; } = new RoutedCommand(nameof(MoveRightByWord)); public static RoutedCommand SelectRightByWord { get; } = new RoutedCommand(nameof(SelectRightByWord)); public static RoutedCommand MoveUpByLine { get; } = new RoutedCommand(nameof(MoveUpByLine)); public static RoutedCommand SelectUpByLine { get; } = new RoutedCommand(nameof(SelectUpByLine)); public static RoutedCommand MoveDownByLine { get; } = new RoutedCommand(nameof(MoveDownByLine)); public static RoutedCommand SelectDownByLine { get; } = new RoutedCommand(nameof(SelectDownByLine)); public static RoutedCommand MoveDownByPage { get; } = new RoutedCommand(nameof(MoveDownByPage)); public static RoutedCommand SelectDownByPage { get; } = new RoutedCommand(nameof(SelectDownByPage)); public static RoutedCommand MoveUpByPage { get; } = new RoutedCommand(nameof(MoveUpByPage)); public static RoutedCommand SelectUpByPage { get; } = new RoutedCommand(nameof(SelectUpByPage)); public static RoutedCommand MoveToLineStart { get; } = new RoutedCommand(nameof(MoveToLineStart)); public static RoutedCommand SelectToLineStart { get; } = new RoutedCommand(nameof(SelectToLineStart)); public static RoutedCommand MoveToLineEnd { get; } = new RoutedCommand(nameof(MoveToLineEnd)); public static RoutedCommand SelectToLineEnd { get; } = new RoutedCommand(nameof(SelectToLineEnd)); public static RoutedCommand MoveToDocumentStart { get; } = new RoutedCommand(nameof(MoveToDocumentStart)); public static RoutedCommand SelectToDocumentStart { get; } = new RoutedCommand(nameof(SelectToDocumentStart)); public static RoutedCommand MoveToDocumentEnd { get; } = new RoutedCommand(nameof(MoveToDocumentEnd)); public static RoutedCommand SelectToDocumentEnd { get; } = new RoutedCommand(nameof(SelectToDocumentEnd)); } } <MSG> Fixing Mac shortcuts using the Control key instead of the Command Key <DFF> @@ -104,13 +104,13 @@ namespace AvaloniaEdit private static readonly KeyModifiers PlatformCommandKey = GetPlatformCommandKey(); public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete), new KeyGesture(Key.Delete)); - public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture(Key.C, KeyModifiers.Control)); - public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture(Key.X, KeyModifiers.Control)); - public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture(Key.V, KeyModifiers.Control)); + public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture(Key.C, PlatformCommandKey)); + public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture(Key.X, PlatformCommandKey)); + public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture(Key.V, PlatformCommandKey)); public static RoutedCommand SelectAll { get; } = new RoutedCommand(nameof(SelectAll), new KeyGesture(Key.A, PlatformCommandKey)); - public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture(Key.Z, KeyModifiers.Control)); - public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture(Key.Y, KeyModifiers.Control)); - public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture(Key.F, KeyModifiers.Control)); + public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture(Key.Z, PlatformCommandKey)); + public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture(Key.Y, PlatformCommandKey)); + public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture(Key.F, PlatformCommandKey)); public static RoutedCommand Replace { get; } = new RoutedCommand(nameof(Replace), GetReplaceKeyGesture()); private static OperatingSystemType GetOperatingSystemType()
6
Fixing Mac shortcuts using the Control key instead of the Command Key
6
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10067279
<NME> AvaloniaEditCommands.cs <BEF> // 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.Diagnostics.CodeAnalysis; using Avalonia; using Avalonia.Input; using Avalonia.Platform; namespace AvaloniaEdit { /// <summary> /// Custom commands for AvalonEdit. /// </summary> public static class AvaloniaEditCommands { /// <summary> /// Toggles Overstrike mode /// The default shortcut is Ins. /// </summary> public static RoutedCommand ToggleOverstrike { get; } = new RoutedCommand(nameof(ToggleOverstrike), new KeyGesture(Key.Insert)); /// <summary> /// Deletes the current line. /// The default shortcut is Ctrl+D. /// </summary> public static RoutedCommand DeleteLine { get; } = new RoutedCommand(nameof(DeleteLine), new KeyGesture(Key.D, KeyModifiers.Control)); /// <summary> /// Removes leading whitespace from the selected lines (or the whole document if the selection is empty). /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] public static RoutedCommand RemoveLeadingWhitespace { get; } = new RoutedCommand(nameof(RemoveLeadingWhitespace)); /// <summary> /// Removes trailing whitespace from the selected lines (or the whole document if the selection is empty). /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] public static RoutedCommand RemoveTrailingWhitespace { get; } = new RoutedCommand(nameof(RemoveTrailingWhitespace)); /// <summary> /// Converts the selected text to upper case. /// </summary> public static RoutedCommand ConvertToUppercase { get; } = new RoutedCommand(nameof(ConvertToUppercase)); /// <summary> /// Converts the selected text to lower case. /// </summary> public static RoutedCommand ConvertToLowercase { get; } = new RoutedCommand(nameof(ConvertToLowercase)); /// <summary> /// Converts the selected text to title case. /// </summary> public static RoutedCommand ConvertToTitleCase { get; } = new RoutedCommand(nameof(ConvertToTitleCase)); /// <summary> /// Inverts the case of the selected text. /// </summary> public static RoutedCommand InvertCase { get; } = new RoutedCommand(nameof(InvertCase)); /// <summary> /// Converts tabs to spaces in the selected text. /// </summary> public static RoutedCommand ConvertTabsToSpaces { get; } = new RoutedCommand(nameof(ConvertTabsToSpaces)); /// <summary> /// Converts spaces to tabs in the selected text. /// </summary> public static RoutedCommand ConvertSpacesToTabs { get; } = new RoutedCommand(nameof(ConvertSpacesToTabs)); /// <summary> /// Converts leading tabs to spaces in the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand ConvertLeadingTabsToSpaces { get; } = new RoutedCommand(nameof(ConvertLeadingTabsToSpaces)); /// <summary> /// Converts leading spaces to tabs in the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand ConvertLeadingSpacesToTabs { get; } = new RoutedCommand(nameof(ConvertLeadingSpacesToTabs)); /// <summary>InputModifiers /// Runs the IIndentationStrategy on the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand IndentSelection { get; } = new RoutedCommand(nameof(IndentSelection), new KeyGesture(Key.I, KeyModifiers.Control)); } public static class ApplicationCommands { private static readonly KeyModifiers PlatformCommandKey = GetPlatformCommandKey(); public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete), new KeyGesture(Key.Delete)); public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture(Key.C, KeyModifiers.Control)); public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture(Key.X, KeyModifiers.Control)); public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture(Key.V, KeyModifiers.Control)); public static RoutedCommand SelectAll { get; } = new RoutedCommand(nameof(SelectAll), new KeyGesture(Key.A, PlatformCommandKey)); public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture(Key.Z, KeyModifiers.Control)); public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture(Key.Y, KeyModifiers.Control)); public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture(Key.F, KeyModifiers.Control)); public static RoutedCommand Replace { get; } = new RoutedCommand(nameof(Replace), GetReplaceKeyGesture()); private static OperatingSystemType GetOperatingSystemType() { return AvaloniaLocator.Current.GetService<IRuntimePlatform>().GetRuntimeInfo().OperatingSystem; } private static KeyModifiers GetPlatformCommandKey() { var os = GetOperatingSystemType(); if (os == OperatingSystemType.OSX) { return KeyModifiers.Meta; } return KeyModifiers.Control; } private static KeyGesture GetReplaceKeyGesture() { var os = GetOperatingSystemType(); if (os == OperatingSystemType.OSX) { return new KeyGesture(Key.F, KeyModifiers.Meta | KeyModifiers.Alt); } return new KeyGesture(Key.H, PlatformCommandKey); } } public static class EditingCommands { public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete)); public static RoutedCommand DeleteNextWord { get; } = new RoutedCommand(nameof(DeleteNextWord)); public static RoutedCommand Backspace { get; } = new RoutedCommand(nameof(Backspace)); public static RoutedCommand DeletePreviousWord { get; } = new RoutedCommand(nameof(DeletePreviousWord)); public static RoutedCommand EnterParagraphBreak { get; } = new RoutedCommand(nameof(EnterParagraphBreak)); public static RoutedCommand EnterLineBreak { get; } = new RoutedCommand(nameof(EnterLineBreak)); public static RoutedCommand TabForward { get; } = new RoutedCommand(nameof(TabForward)); public static RoutedCommand TabBackward { get; } = new RoutedCommand(nameof(TabBackward)); public static RoutedCommand MoveLeftByCharacter { get; } = new RoutedCommand(nameof(MoveLeftByCharacter)); public static RoutedCommand SelectLeftByCharacter { get; } = new RoutedCommand(nameof(SelectLeftByCharacter)); public static RoutedCommand MoveRightByCharacter { get; } = new RoutedCommand(nameof(MoveRightByCharacter)); public static RoutedCommand SelectRightByCharacter { get; } = new RoutedCommand(nameof(SelectRightByCharacter)); public static RoutedCommand MoveLeftByWord { get; } = new RoutedCommand(nameof(MoveLeftByWord)); public static RoutedCommand SelectLeftByWord { get; } = new RoutedCommand(nameof(SelectLeftByWord)); public static RoutedCommand MoveRightByWord { get; } = new RoutedCommand(nameof(MoveRightByWord)); public static RoutedCommand SelectRightByWord { get; } = new RoutedCommand(nameof(SelectRightByWord)); public static RoutedCommand MoveUpByLine { get; } = new RoutedCommand(nameof(MoveUpByLine)); public static RoutedCommand SelectUpByLine { get; } = new RoutedCommand(nameof(SelectUpByLine)); public static RoutedCommand MoveDownByLine { get; } = new RoutedCommand(nameof(MoveDownByLine)); public static RoutedCommand SelectDownByLine { get; } = new RoutedCommand(nameof(SelectDownByLine)); public static RoutedCommand MoveDownByPage { get; } = new RoutedCommand(nameof(MoveDownByPage)); public static RoutedCommand SelectDownByPage { get; } = new RoutedCommand(nameof(SelectDownByPage)); public static RoutedCommand MoveUpByPage { get; } = new RoutedCommand(nameof(MoveUpByPage)); public static RoutedCommand SelectUpByPage { get; } = new RoutedCommand(nameof(SelectUpByPage)); public static RoutedCommand MoveToLineStart { get; } = new RoutedCommand(nameof(MoveToLineStart)); public static RoutedCommand SelectToLineStart { get; } = new RoutedCommand(nameof(SelectToLineStart)); public static RoutedCommand MoveToLineEnd { get; } = new RoutedCommand(nameof(MoveToLineEnd)); public static RoutedCommand SelectToLineEnd { get; } = new RoutedCommand(nameof(SelectToLineEnd)); public static RoutedCommand MoveToDocumentStart { get; } = new RoutedCommand(nameof(MoveToDocumentStart)); public static RoutedCommand SelectToDocumentStart { get; } = new RoutedCommand(nameof(SelectToDocumentStart)); public static RoutedCommand MoveToDocumentEnd { get; } = new RoutedCommand(nameof(MoveToDocumentEnd)); public static RoutedCommand SelectToDocumentEnd { get; } = new RoutedCommand(nameof(SelectToDocumentEnd)); } } <MSG> Fixing Mac shortcuts using the Control key instead of the Command Key <DFF> @@ -104,13 +104,13 @@ namespace AvaloniaEdit private static readonly KeyModifiers PlatformCommandKey = GetPlatformCommandKey(); public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete), new KeyGesture(Key.Delete)); - public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture(Key.C, KeyModifiers.Control)); - public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture(Key.X, KeyModifiers.Control)); - public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture(Key.V, KeyModifiers.Control)); + public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture(Key.C, PlatformCommandKey)); + public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture(Key.X, PlatformCommandKey)); + public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture(Key.V, PlatformCommandKey)); public static RoutedCommand SelectAll { get; } = new RoutedCommand(nameof(SelectAll), new KeyGesture(Key.A, PlatformCommandKey)); - public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture(Key.Z, KeyModifiers.Control)); - public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture(Key.Y, KeyModifiers.Control)); - public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture(Key.F, KeyModifiers.Control)); + public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture(Key.Z, PlatformCommandKey)); + public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture(Key.Y, PlatformCommandKey)); + public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture(Key.F, PlatformCommandKey)); public static RoutedCommand Replace { get; } = new RoutedCommand(nameof(Replace), GetReplaceKeyGesture()); private static OperatingSystemType GetOperatingSystemType()
6
Fixing Mac shortcuts using the Control key instead of the Command Key
6
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10067280
<NME> AvaloniaEditCommands.cs <BEF> // 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.Diagnostics.CodeAnalysis; using Avalonia; using Avalonia.Input; using Avalonia.Platform; namespace AvaloniaEdit { /// <summary> /// Custom commands for AvalonEdit. /// </summary> public static class AvaloniaEditCommands { /// <summary> /// Toggles Overstrike mode /// The default shortcut is Ins. /// </summary> public static RoutedCommand ToggleOverstrike { get; } = new RoutedCommand(nameof(ToggleOverstrike), new KeyGesture(Key.Insert)); /// <summary> /// Deletes the current line. /// The default shortcut is Ctrl+D. /// </summary> public static RoutedCommand DeleteLine { get; } = new RoutedCommand(nameof(DeleteLine), new KeyGesture(Key.D, KeyModifiers.Control)); /// <summary> /// Removes leading whitespace from the selected lines (or the whole document if the selection is empty). /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] public static RoutedCommand RemoveLeadingWhitespace { get; } = new RoutedCommand(nameof(RemoveLeadingWhitespace)); /// <summary> /// Removes trailing whitespace from the selected lines (or the whole document if the selection is empty). /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] public static RoutedCommand RemoveTrailingWhitespace { get; } = new RoutedCommand(nameof(RemoveTrailingWhitespace)); /// <summary> /// Converts the selected text to upper case. /// </summary> public static RoutedCommand ConvertToUppercase { get; } = new RoutedCommand(nameof(ConvertToUppercase)); /// <summary> /// Converts the selected text to lower case. /// </summary> public static RoutedCommand ConvertToLowercase { get; } = new RoutedCommand(nameof(ConvertToLowercase)); /// <summary> /// Converts the selected text to title case. /// </summary> public static RoutedCommand ConvertToTitleCase { get; } = new RoutedCommand(nameof(ConvertToTitleCase)); /// <summary> /// Inverts the case of the selected text. /// </summary> public static RoutedCommand InvertCase { get; } = new RoutedCommand(nameof(InvertCase)); /// <summary> /// Converts tabs to spaces in the selected text. /// </summary> public static RoutedCommand ConvertTabsToSpaces { get; } = new RoutedCommand(nameof(ConvertTabsToSpaces)); /// <summary> /// Converts spaces to tabs in the selected text. /// </summary> public static RoutedCommand ConvertSpacesToTabs { get; } = new RoutedCommand(nameof(ConvertSpacesToTabs)); /// <summary> /// Converts leading tabs to spaces in the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand ConvertLeadingTabsToSpaces { get; } = new RoutedCommand(nameof(ConvertLeadingTabsToSpaces)); /// <summary> /// Converts leading spaces to tabs in the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand ConvertLeadingSpacesToTabs { get; } = new RoutedCommand(nameof(ConvertLeadingSpacesToTabs)); /// <summary>InputModifiers /// Runs the IIndentationStrategy on the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand IndentSelection { get; } = new RoutedCommand(nameof(IndentSelection), new KeyGesture(Key.I, KeyModifiers.Control)); } public static class ApplicationCommands { private static readonly KeyModifiers PlatformCommandKey = GetPlatformCommandKey(); public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete), new KeyGesture(Key.Delete)); public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture(Key.C, KeyModifiers.Control)); public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture(Key.X, KeyModifiers.Control)); public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture(Key.V, KeyModifiers.Control)); public static RoutedCommand SelectAll { get; } = new RoutedCommand(nameof(SelectAll), new KeyGesture(Key.A, PlatformCommandKey)); public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture(Key.Z, KeyModifiers.Control)); public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture(Key.Y, KeyModifiers.Control)); public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture(Key.F, KeyModifiers.Control)); public static RoutedCommand Replace { get; } = new RoutedCommand(nameof(Replace), GetReplaceKeyGesture()); private static OperatingSystemType GetOperatingSystemType() { return AvaloniaLocator.Current.GetService<IRuntimePlatform>().GetRuntimeInfo().OperatingSystem; } private static KeyModifiers GetPlatformCommandKey() { var os = GetOperatingSystemType(); if (os == OperatingSystemType.OSX) { return KeyModifiers.Meta; } return KeyModifiers.Control; } private static KeyGesture GetReplaceKeyGesture() { var os = GetOperatingSystemType(); if (os == OperatingSystemType.OSX) { return new KeyGesture(Key.F, KeyModifiers.Meta | KeyModifiers.Alt); } return new KeyGesture(Key.H, PlatformCommandKey); } } public static class EditingCommands { public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete)); public static RoutedCommand DeleteNextWord { get; } = new RoutedCommand(nameof(DeleteNextWord)); public static RoutedCommand Backspace { get; } = new RoutedCommand(nameof(Backspace)); public static RoutedCommand DeletePreviousWord { get; } = new RoutedCommand(nameof(DeletePreviousWord)); public static RoutedCommand EnterParagraphBreak { get; } = new RoutedCommand(nameof(EnterParagraphBreak)); public static RoutedCommand EnterLineBreak { get; } = new RoutedCommand(nameof(EnterLineBreak)); public static RoutedCommand TabForward { get; } = new RoutedCommand(nameof(TabForward)); public static RoutedCommand TabBackward { get; } = new RoutedCommand(nameof(TabBackward)); public static RoutedCommand MoveLeftByCharacter { get; } = new RoutedCommand(nameof(MoveLeftByCharacter)); public static RoutedCommand SelectLeftByCharacter { get; } = new RoutedCommand(nameof(SelectLeftByCharacter)); public static RoutedCommand MoveRightByCharacter { get; } = new RoutedCommand(nameof(MoveRightByCharacter)); public static RoutedCommand SelectRightByCharacter { get; } = new RoutedCommand(nameof(SelectRightByCharacter)); public static RoutedCommand MoveLeftByWord { get; } = new RoutedCommand(nameof(MoveLeftByWord)); public static RoutedCommand SelectLeftByWord { get; } = new RoutedCommand(nameof(SelectLeftByWord)); public static RoutedCommand MoveRightByWord { get; } = new RoutedCommand(nameof(MoveRightByWord)); public static RoutedCommand SelectRightByWord { get; } = new RoutedCommand(nameof(SelectRightByWord)); public static RoutedCommand MoveUpByLine { get; } = new RoutedCommand(nameof(MoveUpByLine)); public static RoutedCommand SelectUpByLine { get; } = new RoutedCommand(nameof(SelectUpByLine)); public static RoutedCommand MoveDownByLine { get; } = new RoutedCommand(nameof(MoveDownByLine)); public static RoutedCommand SelectDownByLine { get; } = new RoutedCommand(nameof(SelectDownByLine)); public static RoutedCommand MoveDownByPage { get; } = new RoutedCommand(nameof(MoveDownByPage)); public static RoutedCommand SelectDownByPage { get; } = new RoutedCommand(nameof(SelectDownByPage)); public static RoutedCommand MoveUpByPage { get; } = new RoutedCommand(nameof(MoveUpByPage)); public static RoutedCommand SelectUpByPage { get; } = new RoutedCommand(nameof(SelectUpByPage)); public static RoutedCommand MoveToLineStart { get; } = new RoutedCommand(nameof(MoveToLineStart)); public static RoutedCommand SelectToLineStart { get; } = new RoutedCommand(nameof(SelectToLineStart)); public static RoutedCommand MoveToLineEnd { get; } = new RoutedCommand(nameof(MoveToLineEnd)); public static RoutedCommand SelectToLineEnd { get; } = new RoutedCommand(nameof(SelectToLineEnd)); public static RoutedCommand MoveToDocumentStart { get; } = new RoutedCommand(nameof(MoveToDocumentStart)); public static RoutedCommand SelectToDocumentStart { get; } = new RoutedCommand(nameof(SelectToDocumentStart)); public static RoutedCommand MoveToDocumentEnd { get; } = new RoutedCommand(nameof(MoveToDocumentEnd)); public static RoutedCommand SelectToDocumentEnd { get; } = new RoutedCommand(nameof(SelectToDocumentEnd)); } } <MSG> Fixing Mac shortcuts using the Control key instead of the Command Key <DFF> @@ -104,13 +104,13 @@ namespace AvaloniaEdit private static readonly KeyModifiers PlatformCommandKey = GetPlatformCommandKey(); public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete), new KeyGesture(Key.Delete)); - public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture(Key.C, KeyModifiers.Control)); - public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture(Key.X, KeyModifiers.Control)); - public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture(Key.V, KeyModifiers.Control)); + public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture(Key.C, PlatformCommandKey)); + public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture(Key.X, PlatformCommandKey)); + public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture(Key.V, PlatformCommandKey)); public static RoutedCommand SelectAll { get; } = new RoutedCommand(nameof(SelectAll), new KeyGesture(Key.A, PlatformCommandKey)); - public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture(Key.Z, KeyModifiers.Control)); - public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture(Key.Y, KeyModifiers.Control)); - public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture(Key.F, KeyModifiers.Control)); + public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture(Key.Z, PlatformCommandKey)); + public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture(Key.Y, PlatformCommandKey)); + public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture(Key.F, PlatformCommandKey)); public static RoutedCommand Replace { get; } = new RoutedCommand(nameof(Replace), GetReplaceKeyGesture()); private static OperatingSystemType GetOperatingSystemType()
6
Fixing Mac shortcuts using the Control key instead of the Command Key
6
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10067281
<NME> AvaloniaEditCommands.cs <BEF> // 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.Diagnostics.CodeAnalysis; using Avalonia; using Avalonia.Input; using Avalonia.Platform; namespace AvaloniaEdit { /// <summary> /// Custom commands for AvalonEdit. /// </summary> public static class AvaloniaEditCommands { /// <summary> /// Toggles Overstrike mode /// The default shortcut is Ins. /// </summary> public static RoutedCommand ToggleOverstrike { get; } = new RoutedCommand(nameof(ToggleOverstrike), new KeyGesture(Key.Insert)); /// <summary> /// Deletes the current line. /// The default shortcut is Ctrl+D. /// </summary> public static RoutedCommand DeleteLine { get; } = new RoutedCommand(nameof(DeleteLine), new KeyGesture(Key.D, KeyModifiers.Control)); /// <summary> /// Removes leading whitespace from the selected lines (or the whole document if the selection is empty). /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] public static RoutedCommand RemoveLeadingWhitespace { get; } = new RoutedCommand(nameof(RemoveLeadingWhitespace)); /// <summary> /// Removes trailing whitespace from the selected lines (or the whole document if the selection is empty). /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] public static RoutedCommand RemoveTrailingWhitespace { get; } = new RoutedCommand(nameof(RemoveTrailingWhitespace)); /// <summary> /// Converts the selected text to upper case. /// </summary> public static RoutedCommand ConvertToUppercase { get; } = new RoutedCommand(nameof(ConvertToUppercase)); /// <summary> /// Converts the selected text to lower case. /// </summary> public static RoutedCommand ConvertToLowercase { get; } = new RoutedCommand(nameof(ConvertToLowercase)); /// <summary> /// Converts the selected text to title case. /// </summary> public static RoutedCommand ConvertToTitleCase { get; } = new RoutedCommand(nameof(ConvertToTitleCase)); /// <summary> /// Inverts the case of the selected text. /// </summary> public static RoutedCommand InvertCase { get; } = new RoutedCommand(nameof(InvertCase)); /// <summary> /// Converts tabs to spaces in the selected text. /// </summary> public static RoutedCommand ConvertTabsToSpaces { get; } = new RoutedCommand(nameof(ConvertTabsToSpaces)); /// <summary> /// Converts spaces to tabs in the selected text. /// </summary> public static RoutedCommand ConvertSpacesToTabs { get; } = new RoutedCommand(nameof(ConvertSpacesToTabs)); /// <summary> /// Converts leading tabs to spaces in the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand ConvertLeadingTabsToSpaces { get; } = new RoutedCommand(nameof(ConvertLeadingTabsToSpaces)); /// <summary> /// Converts leading spaces to tabs in the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand ConvertLeadingSpacesToTabs { get; } = new RoutedCommand(nameof(ConvertLeadingSpacesToTabs)); /// <summary>InputModifiers /// Runs the IIndentationStrategy on the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand IndentSelection { get; } = new RoutedCommand(nameof(IndentSelection), new KeyGesture(Key.I, KeyModifiers.Control)); } public static class ApplicationCommands { private static readonly KeyModifiers PlatformCommandKey = GetPlatformCommandKey(); public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete), new KeyGesture(Key.Delete)); public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture(Key.C, KeyModifiers.Control)); public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture(Key.X, KeyModifiers.Control)); public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture(Key.V, KeyModifiers.Control)); public static RoutedCommand SelectAll { get; } = new RoutedCommand(nameof(SelectAll), new KeyGesture(Key.A, PlatformCommandKey)); public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture(Key.Z, KeyModifiers.Control)); public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture(Key.Y, KeyModifiers.Control)); public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture(Key.F, KeyModifiers.Control)); public static RoutedCommand Replace { get; } = new RoutedCommand(nameof(Replace), GetReplaceKeyGesture()); private static OperatingSystemType GetOperatingSystemType() { return AvaloniaLocator.Current.GetService<IRuntimePlatform>().GetRuntimeInfo().OperatingSystem; } private static KeyModifiers GetPlatformCommandKey() { var os = GetOperatingSystemType(); if (os == OperatingSystemType.OSX) { return KeyModifiers.Meta; } return KeyModifiers.Control; } private static KeyGesture GetReplaceKeyGesture() { var os = GetOperatingSystemType(); if (os == OperatingSystemType.OSX) { return new KeyGesture(Key.F, KeyModifiers.Meta | KeyModifiers.Alt); } return new KeyGesture(Key.H, PlatformCommandKey); } } public static class EditingCommands { public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete)); public static RoutedCommand DeleteNextWord { get; } = new RoutedCommand(nameof(DeleteNextWord)); public static RoutedCommand Backspace { get; } = new RoutedCommand(nameof(Backspace)); public static RoutedCommand DeletePreviousWord { get; } = new RoutedCommand(nameof(DeletePreviousWord)); public static RoutedCommand EnterParagraphBreak { get; } = new RoutedCommand(nameof(EnterParagraphBreak)); public static RoutedCommand EnterLineBreak { get; } = new RoutedCommand(nameof(EnterLineBreak)); public static RoutedCommand TabForward { get; } = new RoutedCommand(nameof(TabForward)); public static RoutedCommand TabBackward { get; } = new RoutedCommand(nameof(TabBackward)); public static RoutedCommand MoveLeftByCharacter { get; } = new RoutedCommand(nameof(MoveLeftByCharacter)); public static RoutedCommand SelectLeftByCharacter { get; } = new RoutedCommand(nameof(SelectLeftByCharacter)); public static RoutedCommand MoveRightByCharacter { get; } = new RoutedCommand(nameof(MoveRightByCharacter)); public static RoutedCommand SelectRightByCharacter { get; } = new RoutedCommand(nameof(SelectRightByCharacter)); public static RoutedCommand MoveLeftByWord { get; } = new RoutedCommand(nameof(MoveLeftByWord)); public static RoutedCommand SelectLeftByWord { get; } = new RoutedCommand(nameof(SelectLeftByWord)); public static RoutedCommand MoveRightByWord { get; } = new RoutedCommand(nameof(MoveRightByWord)); public static RoutedCommand SelectRightByWord { get; } = new RoutedCommand(nameof(SelectRightByWord)); public static RoutedCommand MoveUpByLine { get; } = new RoutedCommand(nameof(MoveUpByLine)); public static RoutedCommand SelectUpByLine { get; } = new RoutedCommand(nameof(SelectUpByLine)); public static RoutedCommand MoveDownByLine { get; } = new RoutedCommand(nameof(MoveDownByLine)); public static RoutedCommand SelectDownByLine { get; } = new RoutedCommand(nameof(SelectDownByLine)); public static RoutedCommand MoveDownByPage { get; } = new RoutedCommand(nameof(MoveDownByPage)); public static RoutedCommand SelectDownByPage { get; } = new RoutedCommand(nameof(SelectDownByPage)); public static RoutedCommand MoveUpByPage { get; } = new RoutedCommand(nameof(MoveUpByPage)); public static RoutedCommand SelectUpByPage { get; } = new RoutedCommand(nameof(SelectUpByPage)); public static RoutedCommand MoveToLineStart { get; } = new RoutedCommand(nameof(MoveToLineStart)); public static RoutedCommand SelectToLineStart { get; } = new RoutedCommand(nameof(SelectToLineStart)); public static RoutedCommand MoveToLineEnd { get; } = new RoutedCommand(nameof(MoveToLineEnd)); public static RoutedCommand SelectToLineEnd { get; } = new RoutedCommand(nameof(SelectToLineEnd)); public static RoutedCommand MoveToDocumentStart { get; } = new RoutedCommand(nameof(MoveToDocumentStart)); public static RoutedCommand SelectToDocumentStart { get; } = new RoutedCommand(nameof(SelectToDocumentStart)); public static RoutedCommand MoveToDocumentEnd { get; } = new RoutedCommand(nameof(MoveToDocumentEnd)); public static RoutedCommand SelectToDocumentEnd { get; } = new RoutedCommand(nameof(SelectToDocumentEnd)); } } <MSG> Fixing Mac shortcuts using the Control key instead of the Command Key <DFF> @@ -104,13 +104,13 @@ namespace AvaloniaEdit private static readonly KeyModifiers PlatformCommandKey = GetPlatformCommandKey(); public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete), new KeyGesture(Key.Delete)); - public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture(Key.C, KeyModifiers.Control)); - public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture(Key.X, KeyModifiers.Control)); - public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture(Key.V, KeyModifiers.Control)); + public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture(Key.C, PlatformCommandKey)); + public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture(Key.X, PlatformCommandKey)); + public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture(Key.V, PlatformCommandKey)); public static RoutedCommand SelectAll { get; } = new RoutedCommand(nameof(SelectAll), new KeyGesture(Key.A, PlatformCommandKey)); - public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture(Key.Z, KeyModifiers.Control)); - public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture(Key.Y, KeyModifiers.Control)); - public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture(Key.F, KeyModifiers.Control)); + public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture(Key.Z, PlatformCommandKey)); + public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture(Key.Y, PlatformCommandKey)); + public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture(Key.F, PlatformCommandKey)); public static RoutedCommand Replace { get; } = new RoutedCommand(nameof(Replace), GetReplaceKeyGesture()); private static OperatingSystemType GetOperatingSystemType()
6
Fixing Mac shortcuts using the Control key instead of the Command Key
6
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10067282
<NME> AvaloniaEditCommands.cs <BEF> // 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.Diagnostics.CodeAnalysis; using Avalonia; using Avalonia.Input; using Avalonia.Platform; namespace AvaloniaEdit { /// <summary> /// Custom commands for AvalonEdit. /// </summary> public static class AvaloniaEditCommands { /// <summary> /// Toggles Overstrike mode /// The default shortcut is Ins. /// </summary> public static RoutedCommand ToggleOverstrike { get; } = new RoutedCommand(nameof(ToggleOverstrike), new KeyGesture(Key.Insert)); /// <summary> /// Deletes the current line. /// The default shortcut is Ctrl+D. /// </summary> public static RoutedCommand DeleteLine { get; } = new RoutedCommand(nameof(DeleteLine), new KeyGesture(Key.D, KeyModifiers.Control)); /// <summary> /// Removes leading whitespace from the selected lines (or the whole document if the selection is empty). /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] public static RoutedCommand RemoveLeadingWhitespace { get; } = new RoutedCommand(nameof(RemoveLeadingWhitespace)); /// <summary> /// Removes trailing whitespace from the selected lines (or the whole document if the selection is empty). /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] public static RoutedCommand RemoveTrailingWhitespace { get; } = new RoutedCommand(nameof(RemoveTrailingWhitespace)); /// <summary> /// Converts the selected text to upper case. /// </summary> public static RoutedCommand ConvertToUppercase { get; } = new RoutedCommand(nameof(ConvertToUppercase)); /// <summary> /// Converts the selected text to lower case. /// </summary> public static RoutedCommand ConvertToLowercase { get; } = new RoutedCommand(nameof(ConvertToLowercase)); /// <summary> /// Converts the selected text to title case. /// </summary> public static RoutedCommand ConvertToTitleCase { get; } = new RoutedCommand(nameof(ConvertToTitleCase)); /// <summary> /// Inverts the case of the selected text. /// </summary> public static RoutedCommand InvertCase { get; } = new RoutedCommand(nameof(InvertCase)); /// <summary> /// Converts tabs to spaces in the selected text. /// </summary> public static RoutedCommand ConvertTabsToSpaces { get; } = new RoutedCommand(nameof(ConvertTabsToSpaces)); /// <summary> /// Converts spaces to tabs in the selected text. /// </summary> public static RoutedCommand ConvertSpacesToTabs { get; } = new RoutedCommand(nameof(ConvertSpacesToTabs)); /// <summary> /// Converts leading tabs to spaces in the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand ConvertLeadingTabsToSpaces { get; } = new RoutedCommand(nameof(ConvertLeadingTabsToSpaces)); /// <summary> /// Converts leading spaces to tabs in the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand ConvertLeadingSpacesToTabs { get; } = new RoutedCommand(nameof(ConvertLeadingSpacesToTabs)); /// <summary>InputModifiers /// Runs the IIndentationStrategy on the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand IndentSelection { get; } = new RoutedCommand(nameof(IndentSelection), new KeyGesture(Key.I, KeyModifiers.Control)); } public static class ApplicationCommands { private static readonly KeyModifiers PlatformCommandKey = GetPlatformCommandKey(); public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete), new KeyGesture(Key.Delete)); public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture(Key.C, KeyModifiers.Control)); public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture(Key.X, KeyModifiers.Control)); public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture(Key.V, KeyModifiers.Control)); public static RoutedCommand SelectAll { get; } = new RoutedCommand(nameof(SelectAll), new KeyGesture(Key.A, PlatformCommandKey)); public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture(Key.Z, KeyModifiers.Control)); public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture(Key.Y, KeyModifiers.Control)); public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture(Key.F, KeyModifiers.Control)); public static RoutedCommand Replace { get; } = new RoutedCommand(nameof(Replace), GetReplaceKeyGesture()); private static OperatingSystemType GetOperatingSystemType() { return AvaloniaLocator.Current.GetService<IRuntimePlatform>().GetRuntimeInfo().OperatingSystem; } private static KeyModifiers GetPlatformCommandKey() { var os = GetOperatingSystemType(); if (os == OperatingSystemType.OSX) { return KeyModifiers.Meta; } return KeyModifiers.Control; } private static KeyGesture GetReplaceKeyGesture() { var os = GetOperatingSystemType(); if (os == OperatingSystemType.OSX) { return new KeyGesture(Key.F, KeyModifiers.Meta | KeyModifiers.Alt); } return new KeyGesture(Key.H, PlatformCommandKey); } } public static class EditingCommands { public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete)); public static RoutedCommand DeleteNextWord { get; } = new RoutedCommand(nameof(DeleteNextWord)); public static RoutedCommand Backspace { get; } = new RoutedCommand(nameof(Backspace)); public static RoutedCommand DeletePreviousWord { get; } = new RoutedCommand(nameof(DeletePreviousWord)); public static RoutedCommand EnterParagraphBreak { get; } = new RoutedCommand(nameof(EnterParagraphBreak)); public static RoutedCommand EnterLineBreak { get; } = new RoutedCommand(nameof(EnterLineBreak)); public static RoutedCommand TabForward { get; } = new RoutedCommand(nameof(TabForward)); public static RoutedCommand TabBackward { get; } = new RoutedCommand(nameof(TabBackward)); public static RoutedCommand MoveLeftByCharacter { get; } = new RoutedCommand(nameof(MoveLeftByCharacter)); public static RoutedCommand SelectLeftByCharacter { get; } = new RoutedCommand(nameof(SelectLeftByCharacter)); public static RoutedCommand MoveRightByCharacter { get; } = new RoutedCommand(nameof(MoveRightByCharacter)); public static RoutedCommand SelectRightByCharacter { get; } = new RoutedCommand(nameof(SelectRightByCharacter)); public static RoutedCommand MoveLeftByWord { get; } = new RoutedCommand(nameof(MoveLeftByWord)); public static RoutedCommand SelectLeftByWord { get; } = new RoutedCommand(nameof(SelectLeftByWord)); public static RoutedCommand MoveRightByWord { get; } = new RoutedCommand(nameof(MoveRightByWord)); public static RoutedCommand SelectRightByWord { get; } = new RoutedCommand(nameof(SelectRightByWord)); public static RoutedCommand MoveUpByLine { get; } = new RoutedCommand(nameof(MoveUpByLine)); public static RoutedCommand SelectUpByLine { get; } = new RoutedCommand(nameof(SelectUpByLine)); public static RoutedCommand MoveDownByLine { get; } = new RoutedCommand(nameof(MoveDownByLine)); public static RoutedCommand SelectDownByLine { get; } = new RoutedCommand(nameof(SelectDownByLine)); public static RoutedCommand MoveDownByPage { get; } = new RoutedCommand(nameof(MoveDownByPage)); public static RoutedCommand SelectDownByPage { get; } = new RoutedCommand(nameof(SelectDownByPage)); public static RoutedCommand MoveUpByPage { get; } = new RoutedCommand(nameof(MoveUpByPage)); public static RoutedCommand SelectUpByPage { get; } = new RoutedCommand(nameof(SelectUpByPage)); public static RoutedCommand MoveToLineStart { get; } = new RoutedCommand(nameof(MoveToLineStart)); public static RoutedCommand SelectToLineStart { get; } = new RoutedCommand(nameof(SelectToLineStart)); public static RoutedCommand MoveToLineEnd { get; } = new RoutedCommand(nameof(MoveToLineEnd)); public static RoutedCommand SelectToLineEnd { get; } = new RoutedCommand(nameof(SelectToLineEnd)); public static RoutedCommand MoveToDocumentStart { get; } = new RoutedCommand(nameof(MoveToDocumentStart)); public static RoutedCommand SelectToDocumentStart { get; } = new RoutedCommand(nameof(SelectToDocumentStart)); public static RoutedCommand MoveToDocumentEnd { get; } = new RoutedCommand(nameof(MoveToDocumentEnd)); public static RoutedCommand SelectToDocumentEnd { get; } = new RoutedCommand(nameof(SelectToDocumentEnd)); } } <MSG> Fixing Mac shortcuts using the Control key instead of the Command Key <DFF> @@ -104,13 +104,13 @@ namespace AvaloniaEdit private static readonly KeyModifiers PlatformCommandKey = GetPlatformCommandKey(); public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete), new KeyGesture(Key.Delete)); - public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture(Key.C, KeyModifiers.Control)); - public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture(Key.X, KeyModifiers.Control)); - public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture(Key.V, KeyModifiers.Control)); + public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture(Key.C, PlatformCommandKey)); + public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture(Key.X, PlatformCommandKey)); + public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture(Key.V, PlatformCommandKey)); public static RoutedCommand SelectAll { get; } = new RoutedCommand(nameof(SelectAll), new KeyGesture(Key.A, PlatformCommandKey)); - public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture(Key.Z, KeyModifiers.Control)); - public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture(Key.Y, KeyModifiers.Control)); - public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture(Key.F, KeyModifiers.Control)); + public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture(Key.Z, PlatformCommandKey)); + public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture(Key.Y, PlatformCommandKey)); + public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture(Key.F, PlatformCommandKey)); public static RoutedCommand Replace { get; } = new RoutedCommand(nameof(Replace), GetReplaceKeyGesture()); private static OperatingSystemType GetOperatingSystemType()
6
Fixing Mac shortcuts using the Control key instead of the Command Key
6
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10067283
<NME> AvaloniaEditCommands.cs <BEF> // 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.Diagnostics.CodeAnalysis; using Avalonia; using Avalonia.Input; using Avalonia.Platform; namespace AvaloniaEdit { /// <summary> /// Custom commands for AvalonEdit. /// </summary> public static class AvaloniaEditCommands { /// <summary> /// Toggles Overstrike mode /// The default shortcut is Ins. /// </summary> public static RoutedCommand ToggleOverstrike { get; } = new RoutedCommand(nameof(ToggleOverstrike), new KeyGesture(Key.Insert)); /// <summary> /// Deletes the current line. /// The default shortcut is Ctrl+D. /// </summary> public static RoutedCommand DeleteLine { get; } = new RoutedCommand(nameof(DeleteLine), new KeyGesture(Key.D, KeyModifiers.Control)); /// <summary> /// Removes leading whitespace from the selected lines (or the whole document if the selection is empty). /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] public static RoutedCommand RemoveLeadingWhitespace { get; } = new RoutedCommand(nameof(RemoveLeadingWhitespace)); /// <summary> /// Removes trailing whitespace from the selected lines (or the whole document if the selection is empty). /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] public static RoutedCommand RemoveTrailingWhitespace { get; } = new RoutedCommand(nameof(RemoveTrailingWhitespace)); /// <summary> /// Converts the selected text to upper case. /// </summary> public static RoutedCommand ConvertToUppercase { get; } = new RoutedCommand(nameof(ConvertToUppercase)); /// <summary> /// Converts the selected text to lower case. /// </summary> public static RoutedCommand ConvertToLowercase { get; } = new RoutedCommand(nameof(ConvertToLowercase)); /// <summary> /// Converts the selected text to title case. /// </summary> public static RoutedCommand ConvertToTitleCase { get; } = new RoutedCommand(nameof(ConvertToTitleCase)); /// <summary> /// Inverts the case of the selected text. /// </summary> public static RoutedCommand InvertCase { get; } = new RoutedCommand(nameof(InvertCase)); /// <summary> /// Converts tabs to spaces in the selected text. /// </summary> public static RoutedCommand ConvertTabsToSpaces { get; } = new RoutedCommand(nameof(ConvertTabsToSpaces)); /// <summary> /// Converts spaces to tabs in the selected text. /// </summary> public static RoutedCommand ConvertSpacesToTabs { get; } = new RoutedCommand(nameof(ConvertSpacesToTabs)); /// <summary> /// Converts leading tabs to spaces in the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand ConvertLeadingTabsToSpaces { get; } = new RoutedCommand(nameof(ConvertLeadingTabsToSpaces)); /// <summary> /// Converts leading spaces to tabs in the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand ConvertLeadingSpacesToTabs { get; } = new RoutedCommand(nameof(ConvertLeadingSpacesToTabs)); /// <summary>InputModifiers /// Runs the IIndentationStrategy on the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand IndentSelection { get; } = new RoutedCommand(nameof(IndentSelection), new KeyGesture(Key.I, KeyModifiers.Control)); } public static class ApplicationCommands { private static readonly KeyModifiers PlatformCommandKey = GetPlatformCommandKey(); public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete), new KeyGesture(Key.Delete)); public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture(Key.C, KeyModifiers.Control)); public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture(Key.X, KeyModifiers.Control)); public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture(Key.V, KeyModifiers.Control)); public static RoutedCommand SelectAll { get; } = new RoutedCommand(nameof(SelectAll), new KeyGesture(Key.A, PlatformCommandKey)); public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture(Key.Z, KeyModifiers.Control)); public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture(Key.Y, KeyModifiers.Control)); public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture(Key.F, KeyModifiers.Control)); public static RoutedCommand Replace { get; } = new RoutedCommand(nameof(Replace), GetReplaceKeyGesture()); private static OperatingSystemType GetOperatingSystemType() { return AvaloniaLocator.Current.GetService<IRuntimePlatform>().GetRuntimeInfo().OperatingSystem; } private static KeyModifiers GetPlatformCommandKey() { var os = GetOperatingSystemType(); if (os == OperatingSystemType.OSX) { return KeyModifiers.Meta; } return KeyModifiers.Control; } private static KeyGesture GetReplaceKeyGesture() { var os = GetOperatingSystemType(); if (os == OperatingSystemType.OSX) { return new KeyGesture(Key.F, KeyModifiers.Meta | KeyModifiers.Alt); } return new KeyGesture(Key.H, PlatformCommandKey); } } public static class EditingCommands { public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete)); public static RoutedCommand DeleteNextWord { get; } = new RoutedCommand(nameof(DeleteNextWord)); public static RoutedCommand Backspace { get; } = new RoutedCommand(nameof(Backspace)); public static RoutedCommand DeletePreviousWord { get; } = new RoutedCommand(nameof(DeletePreviousWord)); public static RoutedCommand EnterParagraphBreak { get; } = new RoutedCommand(nameof(EnterParagraphBreak)); public static RoutedCommand EnterLineBreak { get; } = new RoutedCommand(nameof(EnterLineBreak)); public static RoutedCommand TabForward { get; } = new RoutedCommand(nameof(TabForward)); public static RoutedCommand TabBackward { get; } = new RoutedCommand(nameof(TabBackward)); public static RoutedCommand MoveLeftByCharacter { get; } = new RoutedCommand(nameof(MoveLeftByCharacter)); public static RoutedCommand SelectLeftByCharacter { get; } = new RoutedCommand(nameof(SelectLeftByCharacter)); public static RoutedCommand MoveRightByCharacter { get; } = new RoutedCommand(nameof(MoveRightByCharacter)); public static RoutedCommand SelectRightByCharacter { get; } = new RoutedCommand(nameof(SelectRightByCharacter)); public static RoutedCommand MoveLeftByWord { get; } = new RoutedCommand(nameof(MoveLeftByWord)); public static RoutedCommand SelectLeftByWord { get; } = new RoutedCommand(nameof(SelectLeftByWord)); public static RoutedCommand MoveRightByWord { get; } = new RoutedCommand(nameof(MoveRightByWord)); public static RoutedCommand SelectRightByWord { get; } = new RoutedCommand(nameof(SelectRightByWord)); public static RoutedCommand MoveUpByLine { get; } = new RoutedCommand(nameof(MoveUpByLine)); public static RoutedCommand SelectUpByLine { get; } = new RoutedCommand(nameof(SelectUpByLine)); public static RoutedCommand MoveDownByLine { get; } = new RoutedCommand(nameof(MoveDownByLine)); public static RoutedCommand SelectDownByLine { get; } = new RoutedCommand(nameof(SelectDownByLine)); public static RoutedCommand MoveDownByPage { get; } = new RoutedCommand(nameof(MoveDownByPage)); public static RoutedCommand SelectDownByPage { get; } = new RoutedCommand(nameof(SelectDownByPage)); public static RoutedCommand MoveUpByPage { get; } = new RoutedCommand(nameof(MoveUpByPage)); public static RoutedCommand SelectUpByPage { get; } = new RoutedCommand(nameof(SelectUpByPage)); public static RoutedCommand MoveToLineStart { get; } = new RoutedCommand(nameof(MoveToLineStart)); public static RoutedCommand SelectToLineStart { get; } = new RoutedCommand(nameof(SelectToLineStart)); public static RoutedCommand MoveToLineEnd { get; } = new RoutedCommand(nameof(MoveToLineEnd)); public static RoutedCommand SelectToLineEnd { get; } = new RoutedCommand(nameof(SelectToLineEnd)); public static RoutedCommand MoveToDocumentStart { get; } = new RoutedCommand(nameof(MoveToDocumentStart)); public static RoutedCommand SelectToDocumentStart { get; } = new RoutedCommand(nameof(SelectToDocumentStart)); public static RoutedCommand MoveToDocumentEnd { get; } = new RoutedCommand(nameof(MoveToDocumentEnd)); public static RoutedCommand SelectToDocumentEnd { get; } = new RoutedCommand(nameof(SelectToDocumentEnd)); } } <MSG> Fixing Mac shortcuts using the Control key instead of the Command Key <DFF> @@ -104,13 +104,13 @@ namespace AvaloniaEdit private static readonly KeyModifiers PlatformCommandKey = GetPlatformCommandKey(); public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete), new KeyGesture(Key.Delete)); - public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture(Key.C, KeyModifiers.Control)); - public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture(Key.X, KeyModifiers.Control)); - public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture(Key.V, KeyModifiers.Control)); + public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture(Key.C, PlatformCommandKey)); + public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture(Key.X, PlatformCommandKey)); + public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture(Key.V, PlatformCommandKey)); public static RoutedCommand SelectAll { get; } = new RoutedCommand(nameof(SelectAll), new KeyGesture(Key.A, PlatformCommandKey)); - public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture(Key.Z, KeyModifiers.Control)); - public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture(Key.Y, KeyModifiers.Control)); - public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture(Key.F, KeyModifiers.Control)); + public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture(Key.Z, PlatformCommandKey)); + public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture(Key.Y, PlatformCommandKey)); + public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture(Key.F, PlatformCommandKey)); public static RoutedCommand Replace { get; } = new RoutedCommand(nameof(Replace), GetReplaceKeyGesture()); private static OperatingSystemType GetOperatingSystemType()
6
Fixing Mac shortcuts using the Control key instead of the Command Key
6
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10067284
<NME> AvaloniaEditCommands.cs <BEF> // 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.Diagnostics.CodeAnalysis; using Avalonia; using Avalonia.Input; using Avalonia.Platform; namespace AvaloniaEdit { /// <summary> /// Custom commands for AvalonEdit. /// </summary> public static class AvaloniaEditCommands { /// <summary> /// Toggles Overstrike mode /// The default shortcut is Ins. /// </summary> public static RoutedCommand ToggleOverstrike { get; } = new RoutedCommand(nameof(ToggleOverstrike), new KeyGesture(Key.Insert)); /// <summary> /// Deletes the current line. /// The default shortcut is Ctrl+D. /// </summary> public static RoutedCommand DeleteLine { get; } = new RoutedCommand(nameof(DeleteLine), new KeyGesture(Key.D, KeyModifiers.Control)); /// <summary> /// Removes leading whitespace from the selected lines (or the whole document if the selection is empty). /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] public static RoutedCommand RemoveLeadingWhitespace { get; } = new RoutedCommand(nameof(RemoveLeadingWhitespace)); /// <summary> /// Removes trailing whitespace from the selected lines (or the whole document if the selection is empty). /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] public static RoutedCommand RemoveTrailingWhitespace { get; } = new RoutedCommand(nameof(RemoveTrailingWhitespace)); /// <summary> /// Converts the selected text to upper case. /// </summary> public static RoutedCommand ConvertToUppercase { get; } = new RoutedCommand(nameof(ConvertToUppercase)); /// <summary> /// Converts the selected text to lower case. /// </summary> public static RoutedCommand ConvertToLowercase { get; } = new RoutedCommand(nameof(ConvertToLowercase)); /// <summary> /// Converts the selected text to title case. /// </summary> public static RoutedCommand ConvertToTitleCase { get; } = new RoutedCommand(nameof(ConvertToTitleCase)); /// <summary> /// Inverts the case of the selected text. /// </summary> public static RoutedCommand InvertCase { get; } = new RoutedCommand(nameof(InvertCase)); /// <summary> /// Converts tabs to spaces in the selected text. /// </summary> public static RoutedCommand ConvertTabsToSpaces { get; } = new RoutedCommand(nameof(ConvertTabsToSpaces)); /// <summary> /// Converts spaces to tabs in the selected text. /// </summary> public static RoutedCommand ConvertSpacesToTabs { get; } = new RoutedCommand(nameof(ConvertSpacesToTabs)); /// <summary> /// Converts leading tabs to spaces in the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand ConvertLeadingTabsToSpaces { get; } = new RoutedCommand(nameof(ConvertLeadingTabsToSpaces)); /// <summary> /// Converts leading spaces to tabs in the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand ConvertLeadingSpacesToTabs { get; } = new RoutedCommand(nameof(ConvertLeadingSpacesToTabs)); /// <summary>InputModifiers /// Runs the IIndentationStrategy on the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand IndentSelection { get; } = new RoutedCommand(nameof(IndentSelection), new KeyGesture(Key.I, KeyModifiers.Control)); } public static class ApplicationCommands { private static readonly KeyModifiers PlatformCommandKey = GetPlatformCommandKey(); public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete), new KeyGesture(Key.Delete)); public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture(Key.C, KeyModifiers.Control)); public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture(Key.X, KeyModifiers.Control)); public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture(Key.V, KeyModifiers.Control)); public static RoutedCommand SelectAll { get; } = new RoutedCommand(nameof(SelectAll), new KeyGesture(Key.A, PlatformCommandKey)); public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture(Key.Z, KeyModifiers.Control)); public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture(Key.Y, KeyModifiers.Control)); public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture(Key.F, KeyModifiers.Control)); public static RoutedCommand Replace { get; } = new RoutedCommand(nameof(Replace), GetReplaceKeyGesture()); private static OperatingSystemType GetOperatingSystemType() { return AvaloniaLocator.Current.GetService<IRuntimePlatform>().GetRuntimeInfo().OperatingSystem; } private static KeyModifiers GetPlatformCommandKey() { var os = GetOperatingSystemType(); if (os == OperatingSystemType.OSX) { return KeyModifiers.Meta; } return KeyModifiers.Control; } private static KeyGesture GetReplaceKeyGesture() { var os = GetOperatingSystemType(); if (os == OperatingSystemType.OSX) { return new KeyGesture(Key.F, KeyModifiers.Meta | KeyModifiers.Alt); } return new KeyGesture(Key.H, PlatformCommandKey); } } public static class EditingCommands { public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete)); public static RoutedCommand DeleteNextWord { get; } = new RoutedCommand(nameof(DeleteNextWord)); public static RoutedCommand Backspace { get; } = new RoutedCommand(nameof(Backspace)); public static RoutedCommand DeletePreviousWord { get; } = new RoutedCommand(nameof(DeletePreviousWord)); public static RoutedCommand EnterParagraphBreak { get; } = new RoutedCommand(nameof(EnterParagraphBreak)); public static RoutedCommand EnterLineBreak { get; } = new RoutedCommand(nameof(EnterLineBreak)); public static RoutedCommand TabForward { get; } = new RoutedCommand(nameof(TabForward)); public static RoutedCommand TabBackward { get; } = new RoutedCommand(nameof(TabBackward)); public static RoutedCommand MoveLeftByCharacter { get; } = new RoutedCommand(nameof(MoveLeftByCharacter)); public static RoutedCommand SelectLeftByCharacter { get; } = new RoutedCommand(nameof(SelectLeftByCharacter)); public static RoutedCommand MoveRightByCharacter { get; } = new RoutedCommand(nameof(MoveRightByCharacter)); public static RoutedCommand SelectRightByCharacter { get; } = new RoutedCommand(nameof(SelectRightByCharacter)); public static RoutedCommand MoveLeftByWord { get; } = new RoutedCommand(nameof(MoveLeftByWord)); public static RoutedCommand SelectLeftByWord { get; } = new RoutedCommand(nameof(SelectLeftByWord)); public static RoutedCommand MoveRightByWord { get; } = new RoutedCommand(nameof(MoveRightByWord)); public static RoutedCommand SelectRightByWord { get; } = new RoutedCommand(nameof(SelectRightByWord)); public static RoutedCommand MoveUpByLine { get; } = new RoutedCommand(nameof(MoveUpByLine)); public static RoutedCommand SelectUpByLine { get; } = new RoutedCommand(nameof(SelectUpByLine)); public static RoutedCommand MoveDownByLine { get; } = new RoutedCommand(nameof(MoveDownByLine)); public static RoutedCommand SelectDownByLine { get; } = new RoutedCommand(nameof(SelectDownByLine)); public static RoutedCommand MoveDownByPage { get; } = new RoutedCommand(nameof(MoveDownByPage)); public static RoutedCommand SelectDownByPage { get; } = new RoutedCommand(nameof(SelectDownByPage)); public static RoutedCommand MoveUpByPage { get; } = new RoutedCommand(nameof(MoveUpByPage)); public static RoutedCommand SelectUpByPage { get; } = new RoutedCommand(nameof(SelectUpByPage)); public static RoutedCommand MoveToLineStart { get; } = new RoutedCommand(nameof(MoveToLineStart)); public static RoutedCommand SelectToLineStart { get; } = new RoutedCommand(nameof(SelectToLineStart)); public static RoutedCommand MoveToLineEnd { get; } = new RoutedCommand(nameof(MoveToLineEnd)); public static RoutedCommand SelectToLineEnd { get; } = new RoutedCommand(nameof(SelectToLineEnd)); public static RoutedCommand MoveToDocumentStart { get; } = new RoutedCommand(nameof(MoveToDocumentStart)); public static RoutedCommand SelectToDocumentStart { get; } = new RoutedCommand(nameof(SelectToDocumentStart)); public static RoutedCommand MoveToDocumentEnd { get; } = new RoutedCommand(nameof(MoveToDocumentEnd)); public static RoutedCommand SelectToDocumentEnd { get; } = new RoutedCommand(nameof(SelectToDocumentEnd)); } } <MSG> Fixing Mac shortcuts using the Control key instead of the Command Key <DFF> @@ -104,13 +104,13 @@ namespace AvaloniaEdit private static readonly KeyModifiers PlatformCommandKey = GetPlatformCommandKey(); public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete), new KeyGesture(Key.Delete)); - public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture(Key.C, KeyModifiers.Control)); - public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture(Key.X, KeyModifiers.Control)); - public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture(Key.V, KeyModifiers.Control)); + public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture(Key.C, PlatformCommandKey)); + public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture(Key.X, PlatformCommandKey)); + public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture(Key.V, PlatformCommandKey)); public static RoutedCommand SelectAll { get; } = new RoutedCommand(nameof(SelectAll), new KeyGesture(Key.A, PlatformCommandKey)); - public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture(Key.Z, KeyModifiers.Control)); - public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture(Key.Y, KeyModifiers.Control)); - public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture(Key.F, KeyModifiers.Control)); + public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture(Key.Z, PlatformCommandKey)); + public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture(Key.Y, PlatformCommandKey)); + public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture(Key.F, PlatformCommandKey)); public static RoutedCommand Replace { get; } = new RoutedCommand(nameof(Replace), GetReplaceKeyGesture()); private static OperatingSystemType GetOperatingSystemType()
6
Fixing Mac shortcuts using the Control key instead of the Command Key
6
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10067285
<NME> AvaloniaEditCommands.cs <BEF> // 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.Diagnostics.CodeAnalysis; using Avalonia; using Avalonia.Input; using Avalonia.Platform; namespace AvaloniaEdit { /// <summary> /// Custom commands for AvalonEdit. /// </summary> public static class AvaloniaEditCommands { /// <summary> /// Toggles Overstrike mode /// The default shortcut is Ins. /// </summary> public static RoutedCommand ToggleOverstrike { get; } = new RoutedCommand(nameof(ToggleOverstrike), new KeyGesture(Key.Insert)); /// <summary> /// Deletes the current line. /// The default shortcut is Ctrl+D. /// </summary> public static RoutedCommand DeleteLine { get; } = new RoutedCommand(nameof(DeleteLine), new KeyGesture(Key.D, KeyModifiers.Control)); /// <summary> /// Removes leading whitespace from the selected lines (or the whole document if the selection is empty). /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] public static RoutedCommand RemoveLeadingWhitespace { get; } = new RoutedCommand(nameof(RemoveLeadingWhitespace)); /// <summary> /// Removes trailing whitespace from the selected lines (or the whole document if the selection is empty). /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] public static RoutedCommand RemoveTrailingWhitespace { get; } = new RoutedCommand(nameof(RemoveTrailingWhitespace)); /// <summary> /// Converts the selected text to upper case. /// </summary> public static RoutedCommand ConvertToUppercase { get; } = new RoutedCommand(nameof(ConvertToUppercase)); /// <summary> /// Converts the selected text to lower case. /// </summary> public static RoutedCommand ConvertToLowercase { get; } = new RoutedCommand(nameof(ConvertToLowercase)); /// <summary> /// Converts the selected text to title case. /// </summary> public static RoutedCommand ConvertToTitleCase { get; } = new RoutedCommand(nameof(ConvertToTitleCase)); /// <summary> /// Inverts the case of the selected text. /// </summary> public static RoutedCommand InvertCase { get; } = new RoutedCommand(nameof(InvertCase)); /// <summary> /// Converts tabs to spaces in the selected text. /// </summary> public static RoutedCommand ConvertTabsToSpaces { get; } = new RoutedCommand(nameof(ConvertTabsToSpaces)); /// <summary> /// Converts spaces to tabs in the selected text. /// </summary> public static RoutedCommand ConvertSpacesToTabs { get; } = new RoutedCommand(nameof(ConvertSpacesToTabs)); /// <summary> /// Converts leading tabs to spaces in the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand ConvertLeadingTabsToSpaces { get; } = new RoutedCommand(nameof(ConvertLeadingTabsToSpaces)); /// <summary> /// Converts leading spaces to tabs in the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand ConvertLeadingSpacesToTabs { get; } = new RoutedCommand(nameof(ConvertLeadingSpacesToTabs)); /// <summary>InputModifiers /// Runs the IIndentationStrategy on the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand IndentSelection { get; } = new RoutedCommand(nameof(IndentSelection), new KeyGesture(Key.I, KeyModifiers.Control)); } public static class ApplicationCommands { private static readonly KeyModifiers PlatformCommandKey = GetPlatformCommandKey(); public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete), new KeyGesture(Key.Delete)); public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture(Key.C, KeyModifiers.Control)); public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture(Key.X, KeyModifiers.Control)); public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture(Key.V, KeyModifiers.Control)); public static RoutedCommand SelectAll { get; } = new RoutedCommand(nameof(SelectAll), new KeyGesture(Key.A, PlatformCommandKey)); public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture(Key.Z, KeyModifiers.Control)); public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture(Key.Y, KeyModifiers.Control)); public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture(Key.F, KeyModifiers.Control)); public static RoutedCommand Replace { get; } = new RoutedCommand(nameof(Replace), GetReplaceKeyGesture()); private static OperatingSystemType GetOperatingSystemType() { return AvaloniaLocator.Current.GetService<IRuntimePlatform>().GetRuntimeInfo().OperatingSystem; } private static KeyModifiers GetPlatformCommandKey() { var os = GetOperatingSystemType(); if (os == OperatingSystemType.OSX) { return KeyModifiers.Meta; } return KeyModifiers.Control; } private static KeyGesture GetReplaceKeyGesture() { var os = GetOperatingSystemType(); if (os == OperatingSystemType.OSX) { return new KeyGesture(Key.F, KeyModifiers.Meta | KeyModifiers.Alt); } return new KeyGesture(Key.H, PlatformCommandKey); } } public static class EditingCommands { public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete)); public static RoutedCommand DeleteNextWord { get; } = new RoutedCommand(nameof(DeleteNextWord)); public static RoutedCommand Backspace { get; } = new RoutedCommand(nameof(Backspace)); public static RoutedCommand DeletePreviousWord { get; } = new RoutedCommand(nameof(DeletePreviousWord)); public static RoutedCommand EnterParagraphBreak { get; } = new RoutedCommand(nameof(EnterParagraphBreak)); public static RoutedCommand EnterLineBreak { get; } = new RoutedCommand(nameof(EnterLineBreak)); public static RoutedCommand TabForward { get; } = new RoutedCommand(nameof(TabForward)); public static RoutedCommand TabBackward { get; } = new RoutedCommand(nameof(TabBackward)); public static RoutedCommand MoveLeftByCharacter { get; } = new RoutedCommand(nameof(MoveLeftByCharacter)); public static RoutedCommand SelectLeftByCharacter { get; } = new RoutedCommand(nameof(SelectLeftByCharacter)); public static RoutedCommand MoveRightByCharacter { get; } = new RoutedCommand(nameof(MoveRightByCharacter)); public static RoutedCommand SelectRightByCharacter { get; } = new RoutedCommand(nameof(SelectRightByCharacter)); public static RoutedCommand MoveLeftByWord { get; } = new RoutedCommand(nameof(MoveLeftByWord)); public static RoutedCommand SelectLeftByWord { get; } = new RoutedCommand(nameof(SelectLeftByWord)); public static RoutedCommand MoveRightByWord { get; } = new RoutedCommand(nameof(MoveRightByWord)); public static RoutedCommand SelectRightByWord { get; } = new RoutedCommand(nameof(SelectRightByWord)); public static RoutedCommand MoveUpByLine { get; } = new RoutedCommand(nameof(MoveUpByLine)); public static RoutedCommand SelectUpByLine { get; } = new RoutedCommand(nameof(SelectUpByLine)); public static RoutedCommand MoveDownByLine { get; } = new RoutedCommand(nameof(MoveDownByLine)); public static RoutedCommand SelectDownByLine { get; } = new RoutedCommand(nameof(SelectDownByLine)); public static RoutedCommand MoveDownByPage { get; } = new RoutedCommand(nameof(MoveDownByPage)); public static RoutedCommand SelectDownByPage { get; } = new RoutedCommand(nameof(SelectDownByPage)); public static RoutedCommand MoveUpByPage { get; } = new RoutedCommand(nameof(MoveUpByPage)); public static RoutedCommand SelectUpByPage { get; } = new RoutedCommand(nameof(SelectUpByPage)); public static RoutedCommand MoveToLineStart { get; } = new RoutedCommand(nameof(MoveToLineStart)); public static RoutedCommand SelectToLineStart { get; } = new RoutedCommand(nameof(SelectToLineStart)); public static RoutedCommand MoveToLineEnd { get; } = new RoutedCommand(nameof(MoveToLineEnd)); public static RoutedCommand SelectToLineEnd { get; } = new RoutedCommand(nameof(SelectToLineEnd)); public static RoutedCommand MoveToDocumentStart { get; } = new RoutedCommand(nameof(MoveToDocumentStart)); public static RoutedCommand SelectToDocumentStart { get; } = new RoutedCommand(nameof(SelectToDocumentStart)); public static RoutedCommand MoveToDocumentEnd { get; } = new RoutedCommand(nameof(MoveToDocumentEnd)); public static RoutedCommand SelectToDocumentEnd { get; } = new RoutedCommand(nameof(SelectToDocumentEnd)); } } <MSG> Fixing Mac shortcuts using the Control key instead of the Command Key <DFF> @@ -104,13 +104,13 @@ namespace AvaloniaEdit private static readonly KeyModifiers PlatformCommandKey = GetPlatformCommandKey(); public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete), new KeyGesture(Key.Delete)); - public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture(Key.C, KeyModifiers.Control)); - public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture(Key.X, KeyModifiers.Control)); - public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture(Key.V, KeyModifiers.Control)); + public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture(Key.C, PlatformCommandKey)); + public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture(Key.X, PlatformCommandKey)); + public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture(Key.V, PlatformCommandKey)); public static RoutedCommand SelectAll { get; } = new RoutedCommand(nameof(SelectAll), new KeyGesture(Key.A, PlatformCommandKey)); - public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture(Key.Z, KeyModifiers.Control)); - public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture(Key.Y, KeyModifiers.Control)); - public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture(Key.F, KeyModifiers.Control)); + public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture(Key.Z, PlatformCommandKey)); + public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture(Key.Y, PlatformCommandKey)); + public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture(Key.F, PlatformCommandKey)); public static RoutedCommand Replace { get; } = new RoutedCommand(nameof(Replace), GetReplaceKeyGesture()); private static OperatingSystemType GetOperatingSystemType()
6
Fixing Mac shortcuts using the Control key instead of the Command Key
6
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10067286
<NME> AvaloniaEditCommands.cs <BEF> // 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.Diagnostics.CodeAnalysis; using Avalonia; using Avalonia.Input; using Avalonia.Platform; namespace AvaloniaEdit { /// <summary> /// Custom commands for AvalonEdit. /// </summary> public static class AvaloniaEditCommands { /// <summary> /// Toggles Overstrike mode /// The default shortcut is Ins. /// </summary> public static RoutedCommand ToggleOverstrike { get; } = new RoutedCommand(nameof(ToggleOverstrike), new KeyGesture(Key.Insert)); /// <summary> /// Deletes the current line. /// The default shortcut is Ctrl+D. /// </summary> public static RoutedCommand DeleteLine { get; } = new RoutedCommand(nameof(DeleteLine), new KeyGesture(Key.D, KeyModifiers.Control)); /// <summary> /// Removes leading whitespace from the selected lines (or the whole document if the selection is empty). /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] public static RoutedCommand RemoveLeadingWhitespace { get; } = new RoutedCommand(nameof(RemoveLeadingWhitespace)); /// <summary> /// Removes trailing whitespace from the selected lines (or the whole document if the selection is empty). /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] public static RoutedCommand RemoveTrailingWhitespace { get; } = new RoutedCommand(nameof(RemoveTrailingWhitespace)); /// <summary> /// Converts the selected text to upper case. /// </summary> public static RoutedCommand ConvertToUppercase { get; } = new RoutedCommand(nameof(ConvertToUppercase)); /// <summary> /// Converts the selected text to lower case. /// </summary> public static RoutedCommand ConvertToLowercase { get; } = new RoutedCommand(nameof(ConvertToLowercase)); /// <summary> /// Converts the selected text to title case. /// </summary> public static RoutedCommand ConvertToTitleCase { get; } = new RoutedCommand(nameof(ConvertToTitleCase)); /// <summary> /// Inverts the case of the selected text. /// </summary> public static RoutedCommand InvertCase { get; } = new RoutedCommand(nameof(InvertCase)); /// <summary> /// Converts tabs to spaces in the selected text. /// </summary> public static RoutedCommand ConvertTabsToSpaces { get; } = new RoutedCommand(nameof(ConvertTabsToSpaces)); /// <summary> /// Converts spaces to tabs in the selected text. /// </summary> public static RoutedCommand ConvertSpacesToTabs { get; } = new RoutedCommand(nameof(ConvertSpacesToTabs)); /// <summary> /// Converts leading tabs to spaces in the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand ConvertLeadingTabsToSpaces { get; } = new RoutedCommand(nameof(ConvertLeadingTabsToSpaces)); /// <summary> /// Converts leading spaces to tabs in the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand ConvertLeadingSpacesToTabs { get; } = new RoutedCommand(nameof(ConvertLeadingSpacesToTabs)); /// <summary>InputModifiers /// Runs the IIndentationStrategy on the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand IndentSelection { get; } = new RoutedCommand(nameof(IndentSelection), new KeyGesture(Key.I, KeyModifiers.Control)); } public static class ApplicationCommands { private static readonly KeyModifiers PlatformCommandKey = GetPlatformCommandKey(); public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete), new KeyGesture(Key.Delete)); public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture(Key.C, KeyModifiers.Control)); public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture(Key.X, KeyModifiers.Control)); public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture(Key.V, KeyModifiers.Control)); public static RoutedCommand SelectAll { get; } = new RoutedCommand(nameof(SelectAll), new KeyGesture(Key.A, PlatformCommandKey)); public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture(Key.Z, KeyModifiers.Control)); public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture(Key.Y, KeyModifiers.Control)); public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture(Key.F, KeyModifiers.Control)); public static RoutedCommand Replace { get; } = new RoutedCommand(nameof(Replace), GetReplaceKeyGesture()); private static OperatingSystemType GetOperatingSystemType() { return AvaloniaLocator.Current.GetService<IRuntimePlatform>().GetRuntimeInfo().OperatingSystem; } private static KeyModifiers GetPlatformCommandKey() { var os = GetOperatingSystemType(); if (os == OperatingSystemType.OSX) { return KeyModifiers.Meta; } return KeyModifiers.Control; } private static KeyGesture GetReplaceKeyGesture() { var os = GetOperatingSystemType(); if (os == OperatingSystemType.OSX) { return new KeyGesture(Key.F, KeyModifiers.Meta | KeyModifiers.Alt); } return new KeyGesture(Key.H, PlatformCommandKey); } } public static class EditingCommands { public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete)); public static RoutedCommand DeleteNextWord { get; } = new RoutedCommand(nameof(DeleteNextWord)); public static RoutedCommand Backspace { get; } = new RoutedCommand(nameof(Backspace)); public static RoutedCommand DeletePreviousWord { get; } = new RoutedCommand(nameof(DeletePreviousWord)); public static RoutedCommand EnterParagraphBreak { get; } = new RoutedCommand(nameof(EnterParagraphBreak)); public static RoutedCommand EnterLineBreak { get; } = new RoutedCommand(nameof(EnterLineBreak)); public static RoutedCommand TabForward { get; } = new RoutedCommand(nameof(TabForward)); public static RoutedCommand TabBackward { get; } = new RoutedCommand(nameof(TabBackward)); public static RoutedCommand MoveLeftByCharacter { get; } = new RoutedCommand(nameof(MoveLeftByCharacter)); public static RoutedCommand SelectLeftByCharacter { get; } = new RoutedCommand(nameof(SelectLeftByCharacter)); public static RoutedCommand MoveRightByCharacter { get; } = new RoutedCommand(nameof(MoveRightByCharacter)); public static RoutedCommand SelectRightByCharacter { get; } = new RoutedCommand(nameof(SelectRightByCharacter)); public static RoutedCommand MoveLeftByWord { get; } = new RoutedCommand(nameof(MoveLeftByWord)); public static RoutedCommand SelectLeftByWord { get; } = new RoutedCommand(nameof(SelectLeftByWord)); public static RoutedCommand MoveRightByWord { get; } = new RoutedCommand(nameof(MoveRightByWord)); public static RoutedCommand SelectRightByWord { get; } = new RoutedCommand(nameof(SelectRightByWord)); public static RoutedCommand MoveUpByLine { get; } = new RoutedCommand(nameof(MoveUpByLine)); public static RoutedCommand SelectUpByLine { get; } = new RoutedCommand(nameof(SelectUpByLine)); public static RoutedCommand MoveDownByLine { get; } = new RoutedCommand(nameof(MoveDownByLine)); public static RoutedCommand SelectDownByLine { get; } = new RoutedCommand(nameof(SelectDownByLine)); public static RoutedCommand MoveDownByPage { get; } = new RoutedCommand(nameof(MoveDownByPage)); public static RoutedCommand SelectDownByPage { get; } = new RoutedCommand(nameof(SelectDownByPage)); public static RoutedCommand MoveUpByPage { get; } = new RoutedCommand(nameof(MoveUpByPage)); public static RoutedCommand SelectUpByPage { get; } = new RoutedCommand(nameof(SelectUpByPage)); public static RoutedCommand MoveToLineStart { get; } = new RoutedCommand(nameof(MoveToLineStart)); public static RoutedCommand SelectToLineStart { get; } = new RoutedCommand(nameof(SelectToLineStart)); public static RoutedCommand MoveToLineEnd { get; } = new RoutedCommand(nameof(MoveToLineEnd)); public static RoutedCommand SelectToLineEnd { get; } = new RoutedCommand(nameof(SelectToLineEnd)); public static RoutedCommand MoveToDocumentStart { get; } = new RoutedCommand(nameof(MoveToDocumentStart)); public static RoutedCommand SelectToDocumentStart { get; } = new RoutedCommand(nameof(SelectToDocumentStart)); public static RoutedCommand MoveToDocumentEnd { get; } = new RoutedCommand(nameof(MoveToDocumentEnd)); public static RoutedCommand SelectToDocumentEnd { get; } = new RoutedCommand(nameof(SelectToDocumentEnd)); } } <MSG> Fixing Mac shortcuts using the Control key instead of the Command Key <DFF> @@ -104,13 +104,13 @@ namespace AvaloniaEdit private static readonly KeyModifiers PlatformCommandKey = GetPlatformCommandKey(); public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete), new KeyGesture(Key.Delete)); - public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture(Key.C, KeyModifiers.Control)); - public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture(Key.X, KeyModifiers.Control)); - public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture(Key.V, KeyModifiers.Control)); + public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture(Key.C, PlatformCommandKey)); + public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture(Key.X, PlatformCommandKey)); + public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture(Key.V, PlatformCommandKey)); public static RoutedCommand SelectAll { get; } = new RoutedCommand(nameof(SelectAll), new KeyGesture(Key.A, PlatformCommandKey)); - public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture(Key.Z, KeyModifiers.Control)); - public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture(Key.Y, KeyModifiers.Control)); - public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture(Key.F, KeyModifiers.Control)); + public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture(Key.Z, PlatformCommandKey)); + public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture(Key.Y, PlatformCommandKey)); + public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture(Key.F, PlatformCommandKey)); public static RoutedCommand Replace { get; } = new RoutedCommand(nameof(Replace), GetReplaceKeyGesture()); private static OperatingSystemType GetOperatingSystemType()
6
Fixing Mac shortcuts using the Control key instead of the Command Key
6
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10067287
<NME> TextTransformation.cs <BEF> using System; using Avalonia.Media; using AvaloniaEdit.Document; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { public TextTransformation(object tag, int startOffset, int endOffset) { Tag = tag; StartOffset = startOffset; EndOffset = endOffset; } public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); public object Tag { get; } } public class ForegroundTextTransformation : TextTransformation { public ForegroundTextTransformation(object tag, int startOffset, int endOffset, IBrush foreground) : base(tag, startOffset, endOffset) { Foreground = foreground; } public IBrush Foreground { get; set; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { } var formattedOffset = 0; var endOffset = line.EndOffset; if (StartOffset > line.Offset) { formattedOffset = StartOffset - line.Offset; } if (EndOffset < line.EndOffset) { endOffset = EndOffset; } endOffset = EndOffset; } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, Foreground); } } } catch(Exception ex) { ExceptionHandler?.Invoke(ex); } } AM.FontStyle GetFontStyle() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) return AM.FontStyle.Italic; return AM.FontStyle.Normal; } AM.FontWeight GetFontWeight() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) return AM.FontWeight.Bold; return AM.FontWeight.Regular; } bool IsUnderline() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) return true; return false; } } } <MSG> add a highlighter based on text segment collection. <DFF> @@ -1,34 +1,33 @@ using System; +using System.Collections.Generic; using Avalonia.Media; using AvaloniaEdit.Document; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { - public abstract class TextTransformation : TextSegment { - public TextTransformation(object tag, int startOffset, int endOffset) + public TextTransformation(int startOffset, int endOffset) { - Tag = tag; StartOffset = startOffset; EndOffset = endOffset; } public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); - - public object Tag { get; } } public class ForegroundTextTransformation : TextTransformation { - public ForegroundTextTransformation(object tag, int startOffset, int endOffset, IBrush foreground) : base(tag, - startOffset, endOffset) + private readonly Dictionary<int, IBrush> _brushCache; + + public ForegroundTextTransformation(Dictionary<int, IBrush> brushCache, int startOffset, int endOffset, int brushId) : base(startOffset, endOffset) { - Foreground = foreground; + _brushCache = brushCache; + Foreground = brushId; } - public IBrush Foreground { get; set; } + public int Foreground { get; set; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { @@ -50,7 +49,7 @@ namespace AvaloniaEdit.TextMate endOffset = EndOffset; } - transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, Foreground); + transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, _brushCache[Foreground]); } } } \ No newline at end of file
9
add a highlighter based on text segment collection.
10
.cs
TextMate/TextTransformation
mit
AvaloniaUI/AvaloniaEdit
10067288
<NME> TextTransformation.cs <BEF> using System; using Avalonia.Media; using AvaloniaEdit.Document; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { public TextTransformation(object tag, int startOffset, int endOffset) { Tag = tag; StartOffset = startOffset; EndOffset = endOffset; } public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); public object Tag { get; } } public class ForegroundTextTransformation : TextTransformation { public ForegroundTextTransformation(object tag, int startOffset, int endOffset, IBrush foreground) : base(tag, startOffset, endOffset) { Foreground = foreground; } public IBrush Foreground { get; set; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { } var formattedOffset = 0; var endOffset = line.EndOffset; if (StartOffset > line.Offset) { formattedOffset = StartOffset - line.Offset; } if (EndOffset < line.EndOffset) { endOffset = EndOffset; } endOffset = EndOffset; } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, Foreground); } } } catch(Exception ex) { ExceptionHandler?.Invoke(ex); } } AM.FontStyle GetFontStyle() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) return AM.FontStyle.Italic; return AM.FontStyle.Normal; } AM.FontWeight GetFontWeight() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) return AM.FontWeight.Bold; return AM.FontWeight.Regular; } bool IsUnderline() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) return true; return false; } } } <MSG> add a highlighter based on text segment collection. <DFF> @@ -1,34 +1,33 @@ using System; +using System.Collections.Generic; using Avalonia.Media; using AvaloniaEdit.Document; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { - public abstract class TextTransformation : TextSegment { - public TextTransformation(object tag, int startOffset, int endOffset) + public TextTransformation(int startOffset, int endOffset) { - Tag = tag; StartOffset = startOffset; EndOffset = endOffset; } public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); - - public object Tag { get; } } public class ForegroundTextTransformation : TextTransformation { - public ForegroundTextTransformation(object tag, int startOffset, int endOffset, IBrush foreground) : base(tag, - startOffset, endOffset) + private readonly Dictionary<int, IBrush> _brushCache; + + public ForegroundTextTransformation(Dictionary<int, IBrush> brushCache, int startOffset, int endOffset, int brushId) : base(startOffset, endOffset) { - Foreground = foreground; + _brushCache = brushCache; + Foreground = brushId; } - public IBrush Foreground { get; set; } + public int Foreground { get; set; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { @@ -50,7 +49,7 @@ namespace AvaloniaEdit.TextMate endOffset = EndOffset; } - transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, Foreground); + transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, _brushCache[Foreground]); } } } \ No newline at end of file
9
add a highlighter based on text segment collection.
10
.cs
TextMate/TextTransformation
mit
AvaloniaUI/AvaloniaEdit
10067289
<NME> TextTransformation.cs <BEF> using System; using Avalonia.Media; using AvaloniaEdit.Document; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { public TextTransformation(object tag, int startOffset, int endOffset) { Tag = tag; StartOffset = startOffset; EndOffset = endOffset; } public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); public object Tag { get; } } public class ForegroundTextTransformation : TextTransformation { public ForegroundTextTransformation(object tag, int startOffset, int endOffset, IBrush foreground) : base(tag, startOffset, endOffset) { Foreground = foreground; } public IBrush Foreground { get; set; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { } var formattedOffset = 0; var endOffset = line.EndOffset; if (StartOffset > line.Offset) { formattedOffset = StartOffset - line.Offset; } if (EndOffset < line.EndOffset) { endOffset = EndOffset; } endOffset = EndOffset; } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, Foreground); } } } catch(Exception ex) { ExceptionHandler?.Invoke(ex); } } AM.FontStyle GetFontStyle() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) return AM.FontStyle.Italic; return AM.FontStyle.Normal; } AM.FontWeight GetFontWeight() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) return AM.FontWeight.Bold; return AM.FontWeight.Regular; } bool IsUnderline() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) return true; return false; } } } <MSG> add a highlighter based on text segment collection. <DFF> @@ -1,34 +1,33 @@ using System; +using System.Collections.Generic; using Avalonia.Media; using AvaloniaEdit.Document; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { - public abstract class TextTransformation : TextSegment { - public TextTransformation(object tag, int startOffset, int endOffset) + public TextTransformation(int startOffset, int endOffset) { - Tag = tag; StartOffset = startOffset; EndOffset = endOffset; } public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); - - public object Tag { get; } } public class ForegroundTextTransformation : TextTransformation { - public ForegroundTextTransformation(object tag, int startOffset, int endOffset, IBrush foreground) : base(tag, - startOffset, endOffset) + private readonly Dictionary<int, IBrush> _brushCache; + + public ForegroundTextTransformation(Dictionary<int, IBrush> brushCache, int startOffset, int endOffset, int brushId) : base(startOffset, endOffset) { - Foreground = foreground; + _brushCache = brushCache; + Foreground = brushId; } - public IBrush Foreground { get; set; } + public int Foreground { get; set; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { @@ -50,7 +49,7 @@ namespace AvaloniaEdit.TextMate endOffset = EndOffset; } - transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, Foreground); + transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, _brushCache[Foreground]); } } } \ No newline at end of file
9
add a highlighter based on text segment collection.
10
.cs
TextMate/TextTransformation
mit
AvaloniaUI/AvaloniaEdit
10067290
<NME> TextTransformation.cs <BEF> using System; using Avalonia.Media; using AvaloniaEdit.Document; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { public TextTransformation(object tag, int startOffset, int endOffset) { Tag = tag; StartOffset = startOffset; EndOffset = endOffset; } public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); public object Tag { get; } } public class ForegroundTextTransformation : TextTransformation { public ForegroundTextTransformation(object tag, int startOffset, int endOffset, IBrush foreground) : base(tag, startOffset, endOffset) { Foreground = foreground; } public IBrush Foreground { get; set; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { } var formattedOffset = 0; var endOffset = line.EndOffset; if (StartOffset > line.Offset) { formattedOffset = StartOffset - line.Offset; } if (EndOffset < line.EndOffset) { endOffset = EndOffset; } endOffset = EndOffset; } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, Foreground); } } } catch(Exception ex) { ExceptionHandler?.Invoke(ex); } } AM.FontStyle GetFontStyle() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) return AM.FontStyle.Italic; return AM.FontStyle.Normal; } AM.FontWeight GetFontWeight() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) return AM.FontWeight.Bold; return AM.FontWeight.Regular; } bool IsUnderline() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) return true; return false; } } } <MSG> add a highlighter based on text segment collection. <DFF> @@ -1,34 +1,33 @@ using System; +using System.Collections.Generic; using Avalonia.Media; using AvaloniaEdit.Document; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { - public abstract class TextTransformation : TextSegment { - public TextTransformation(object tag, int startOffset, int endOffset) + public TextTransformation(int startOffset, int endOffset) { - Tag = tag; StartOffset = startOffset; EndOffset = endOffset; } public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); - - public object Tag { get; } } public class ForegroundTextTransformation : TextTransformation { - public ForegroundTextTransformation(object tag, int startOffset, int endOffset, IBrush foreground) : base(tag, - startOffset, endOffset) + private readonly Dictionary<int, IBrush> _brushCache; + + public ForegroundTextTransformation(Dictionary<int, IBrush> brushCache, int startOffset, int endOffset, int brushId) : base(startOffset, endOffset) { - Foreground = foreground; + _brushCache = brushCache; + Foreground = brushId; } - public IBrush Foreground { get; set; } + public int Foreground { get; set; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { @@ -50,7 +49,7 @@ namespace AvaloniaEdit.TextMate endOffset = EndOffset; } - transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, Foreground); + transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, _brushCache[Foreground]); } } } \ No newline at end of file
9
add a highlighter based on text segment collection.
10
.cs
TextMate/TextTransformation
mit
AvaloniaUI/AvaloniaEdit
10067291
<NME> TextTransformation.cs <BEF> using System; using Avalonia.Media; using AvaloniaEdit.Document; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { public TextTransformation(object tag, int startOffset, int endOffset) { Tag = tag; StartOffset = startOffset; EndOffset = endOffset; } public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); public object Tag { get; } } public class ForegroundTextTransformation : TextTransformation { public ForegroundTextTransformation(object tag, int startOffset, int endOffset, IBrush foreground) : base(tag, startOffset, endOffset) { Foreground = foreground; } public IBrush Foreground { get; set; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { } var formattedOffset = 0; var endOffset = line.EndOffset; if (StartOffset > line.Offset) { formattedOffset = StartOffset - line.Offset; } if (EndOffset < line.EndOffset) { endOffset = EndOffset; } endOffset = EndOffset; } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, Foreground); } } } catch(Exception ex) { ExceptionHandler?.Invoke(ex); } } AM.FontStyle GetFontStyle() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) return AM.FontStyle.Italic; return AM.FontStyle.Normal; } AM.FontWeight GetFontWeight() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) return AM.FontWeight.Bold; return AM.FontWeight.Regular; } bool IsUnderline() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) return true; return false; } } } <MSG> add a highlighter based on text segment collection. <DFF> @@ -1,34 +1,33 @@ using System; +using System.Collections.Generic; using Avalonia.Media; using AvaloniaEdit.Document; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { - public abstract class TextTransformation : TextSegment { - public TextTransformation(object tag, int startOffset, int endOffset) + public TextTransformation(int startOffset, int endOffset) { - Tag = tag; StartOffset = startOffset; EndOffset = endOffset; } public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); - - public object Tag { get; } } public class ForegroundTextTransformation : TextTransformation { - public ForegroundTextTransformation(object tag, int startOffset, int endOffset, IBrush foreground) : base(tag, - startOffset, endOffset) + private readonly Dictionary<int, IBrush> _brushCache; + + public ForegroundTextTransformation(Dictionary<int, IBrush> brushCache, int startOffset, int endOffset, int brushId) : base(startOffset, endOffset) { - Foreground = foreground; + _brushCache = brushCache; + Foreground = brushId; } - public IBrush Foreground { get; set; } + public int Foreground { get; set; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { @@ -50,7 +49,7 @@ namespace AvaloniaEdit.TextMate endOffset = EndOffset; } - transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, Foreground); + transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, _brushCache[Foreground]); } } } \ No newline at end of file
9
add a highlighter based on text segment collection.
10
.cs
TextMate/TextTransformation
mit
AvaloniaUI/AvaloniaEdit
10067292
<NME> TextTransformation.cs <BEF> using System; using Avalonia.Media; using AvaloniaEdit.Document; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { public TextTransformation(object tag, int startOffset, int endOffset) { Tag = tag; StartOffset = startOffset; EndOffset = endOffset; } public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); public object Tag { get; } } public class ForegroundTextTransformation : TextTransformation { public ForegroundTextTransformation(object tag, int startOffset, int endOffset, IBrush foreground) : base(tag, startOffset, endOffset) { Foreground = foreground; } public IBrush Foreground { get; set; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { } var formattedOffset = 0; var endOffset = line.EndOffset; if (StartOffset > line.Offset) { formattedOffset = StartOffset - line.Offset; } if (EndOffset < line.EndOffset) { endOffset = EndOffset; } endOffset = EndOffset; } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, Foreground); } } } catch(Exception ex) { ExceptionHandler?.Invoke(ex); } } AM.FontStyle GetFontStyle() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) return AM.FontStyle.Italic; return AM.FontStyle.Normal; } AM.FontWeight GetFontWeight() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) return AM.FontWeight.Bold; return AM.FontWeight.Regular; } bool IsUnderline() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) return true; return false; } } } <MSG> add a highlighter based on text segment collection. <DFF> @@ -1,34 +1,33 @@ using System; +using System.Collections.Generic; using Avalonia.Media; using AvaloniaEdit.Document; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { - public abstract class TextTransformation : TextSegment { - public TextTransformation(object tag, int startOffset, int endOffset) + public TextTransformation(int startOffset, int endOffset) { - Tag = tag; StartOffset = startOffset; EndOffset = endOffset; } public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); - - public object Tag { get; } } public class ForegroundTextTransformation : TextTransformation { - public ForegroundTextTransformation(object tag, int startOffset, int endOffset, IBrush foreground) : base(tag, - startOffset, endOffset) + private readonly Dictionary<int, IBrush> _brushCache; + + public ForegroundTextTransformation(Dictionary<int, IBrush> brushCache, int startOffset, int endOffset, int brushId) : base(startOffset, endOffset) { - Foreground = foreground; + _brushCache = brushCache; + Foreground = brushId; } - public IBrush Foreground { get; set; } + public int Foreground { get; set; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { @@ -50,7 +49,7 @@ namespace AvaloniaEdit.TextMate endOffset = EndOffset; } - transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, Foreground); + transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, _brushCache[Foreground]); } } } \ No newline at end of file
9
add a highlighter based on text segment collection.
10
.cs
TextMate/TextTransformation
mit
AvaloniaUI/AvaloniaEdit
10067293
<NME> TextTransformation.cs <BEF> using System; using Avalonia.Media; using AvaloniaEdit.Document; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { public TextTransformation(object tag, int startOffset, int endOffset) { Tag = tag; StartOffset = startOffset; EndOffset = endOffset; } public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); public object Tag { get; } } public class ForegroundTextTransformation : TextTransformation { public ForegroundTextTransformation(object tag, int startOffset, int endOffset, IBrush foreground) : base(tag, startOffset, endOffset) { Foreground = foreground; } public IBrush Foreground { get; set; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { } var formattedOffset = 0; var endOffset = line.EndOffset; if (StartOffset > line.Offset) { formattedOffset = StartOffset - line.Offset; } if (EndOffset < line.EndOffset) { endOffset = EndOffset; } endOffset = EndOffset; } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, Foreground); } } } catch(Exception ex) { ExceptionHandler?.Invoke(ex); } } AM.FontStyle GetFontStyle() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) return AM.FontStyle.Italic; return AM.FontStyle.Normal; } AM.FontWeight GetFontWeight() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) return AM.FontWeight.Bold; return AM.FontWeight.Regular; } bool IsUnderline() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) return true; return false; } } } <MSG> add a highlighter based on text segment collection. <DFF> @@ -1,34 +1,33 @@ using System; +using System.Collections.Generic; using Avalonia.Media; using AvaloniaEdit.Document; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { - public abstract class TextTransformation : TextSegment { - public TextTransformation(object tag, int startOffset, int endOffset) + public TextTransformation(int startOffset, int endOffset) { - Tag = tag; StartOffset = startOffset; EndOffset = endOffset; } public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); - - public object Tag { get; } } public class ForegroundTextTransformation : TextTransformation { - public ForegroundTextTransformation(object tag, int startOffset, int endOffset, IBrush foreground) : base(tag, - startOffset, endOffset) + private readonly Dictionary<int, IBrush> _brushCache; + + public ForegroundTextTransformation(Dictionary<int, IBrush> brushCache, int startOffset, int endOffset, int brushId) : base(startOffset, endOffset) { - Foreground = foreground; + _brushCache = brushCache; + Foreground = brushId; } - public IBrush Foreground { get; set; } + public int Foreground { get; set; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { @@ -50,7 +49,7 @@ namespace AvaloniaEdit.TextMate endOffset = EndOffset; } - transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, Foreground); + transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, _brushCache[Foreground]); } } } \ No newline at end of file
9
add a highlighter based on text segment collection.
10
.cs
TextMate/TextTransformation
mit
AvaloniaUI/AvaloniaEdit
10067294
<NME> TextTransformation.cs <BEF> using System; using Avalonia.Media; using AvaloniaEdit.Document; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { public TextTransformation(object tag, int startOffset, int endOffset) { Tag = tag; StartOffset = startOffset; EndOffset = endOffset; } public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); public object Tag { get; } } public class ForegroundTextTransformation : TextTransformation { public ForegroundTextTransformation(object tag, int startOffset, int endOffset, IBrush foreground) : base(tag, startOffset, endOffset) { Foreground = foreground; } public IBrush Foreground { get; set; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { } var formattedOffset = 0; var endOffset = line.EndOffset; if (StartOffset > line.Offset) { formattedOffset = StartOffset - line.Offset; } if (EndOffset < line.EndOffset) { endOffset = EndOffset; } endOffset = EndOffset; } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, Foreground); } } } catch(Exception ex) { ExceptionHandler?.Invoke(ex); } } AM.FontStyle GetFontStyle() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) return AM.FontStyle.Italic; return AM.FontStyle.Normal; } AM.FontWeight GetFontWeight() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) return AM.FontWeight.Bold; return AM.FontWeight.Regular; } bool IsUnderline() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) return true; return false; } } } <MSG> add a highlighter based on text segment collection. <DFF> @@ -1,34 +1,33 @@ using System; +using System.Collections.Generic; using Avalonia.Media; using AvaloniaEdit.Document; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { - public abstract class TextTransformation : TextSegment { - public TextTransformation(object tag, int startOffset, int endOffset) + public TextTransformation(int startOffset, int endOffset) { - Tag = tag; StartOffset = startOffset; EndOffset = endOffset; } public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); - - public object Tag { get; } } public class ForegroundTextTransformation : TextTransformation { - public ForegroundTextTransformation(object tag, int startOffset, int endOffset, IBrush foreground) : base(tag, - startOffset, endOffset) + private readonly Dictionary<int, IBrush> _brushCache; + + public ForegroundTextTransformation(Dictionary<int, IBrush> brushCache, int startOffset, int endOffset, int brushId) : base(startOffset, endOffset) { - Foreground = foreground; + _brushCache = brushCache; + Foreground = brushId; } - public IBrush Foreground { get; set; } + public int Foreground { get; set; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { @@ -50,7 +49,7 @@ namespace AvaloniaEdit.TextMate endOffset = EndOffset; } - transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, Foreground); + transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, _brushCache[Foreground]); } } } \ No newline at end of file
9
add a highlighter based on text segment collection.
10
.cs
TextMate/TextTransformation
mit
AvaloniaUI/AvaloniaEdit
10067295
<NME> TextTransformation.cs <BEF> using System; using Avalonia.Media; using AvaloniaEdit.Document; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { public TextTransformation(object tag, int startOffset, int endOffset) { Tag = tag; StartOffset = startOffset; EndOffset = endOffset; } public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); public object Tag { get; } } public class ForegroundTextTransformation : TextTransformation { public ForegroundTextTransformation(object tag, int startOffset, int endOffset, IBrush foreground) : base(tag, startOffset, endOffset) { Foreground = foreground; } public IBrush Foreground { get; set; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { } var formattedOffset = 0; var endOffset = line.EndOffset; if (StartOffset > line.Offset) { formattedOffset = StartOffset - line.Offset; } if (EndOffset < line.EndOffset) { endOffset = EndOffset; } endOffset = EndOffset; } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, Foreground); } } } catch(Exception ex) { ExceptionHandler?.Invoke(ex); } } AM.FontStyle GetFontStyle() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) return AM.FontStyle.Italic; return AM.FontStyle.Normal; } AM.FontWeight GetFontWeight() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) return AM.FontWeight.Bold; return AM.FontWeight.Regular; } bool IsUnderline() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) return true; return false; } } } <MSG> add a highlighter based on text segment collection. <DFF> @@ -1,34 +1,33 @@ using System; +using System.Collections.Generic; using Avalonia.Media; using AvaloniaEdit.Document; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { - public abstract class TextTransformation : TextSegment { - public TextTransformation(object tag, int startOffset, int endOffset) + public TextTransformation(int startOffset, int endOffset) { - Tag = tag; StartOffset = startOffset; EndOffset = endOffset; } public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); - - public object Tag { get; } } public class ForegroundTextTransformation : TextTransformation { - public ForegroundTextTransformation(object tag, int startOffset, int endOffset, IBrush foreground) : base(tag, - startOffset, endOffset) + private readonly Dictionary<int, IBrush> _brushCache; + + public ForegroundTextTransformation(Dictionary<int, IBrush> brushCache, int startOffset, int endOffset, int brushId) : base(startOffset, endOffset) { - Foreground = foreground; + _brushCache = brushCache; + Foreground = brushId; } - public IBrush Foreground { get; set; } + public int Foreground { get; set; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { @@ -50,7 +49,7 @@ namespace AvaloniaEdit.TextMate endOffset = EndOffset; } - transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, Foreground); + transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, _brushCache[Foreground]); } } } \ No newline at end of file
9
add a highlighter based on text segment collection.
10
.cs
TextMate/TextTransformation
mit
AvaloniaUI/AvaloniaEdit
10067296
<NME> TextTransformation.cs <BEF> using System; using Avalonia.Media; using AvaloniaEdit.Document; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { public TextTransformation(object tag, int startOffset, int endOffset) { Tag = tag; StartOffset = startOffset; EndOffset = endOffset; } public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); public object Tag { get; } } public class ForegroundTextTransformation : TextTransformation { public ForegroundTextTransformation(object tag, int startOffset, int endOffset, IBrush foreground) : base(tag, startOffset, endOffset) { Foreground = foreground; } public IBrush Foreground { get; set; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { } var formattedOffset = 0; var endOffset = line.EndOffset; if (StartOffset > line.Offset) { formattedOffset = StartOffset - line.Offset; } if (EndOffset < line.EndOffset) { endOffset = EndOffset; } endOffset = EndOffset; } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, Foreground); } } } catch(Exception ex) { ExceptionHandler?.Invoke(ex); } } AM.FontStyle GetFontStyle() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) return AM.FontStyle.Italic; return AM.FontStyle.Normal; } AM.FontWeight GetFontWeight() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) return AM.FontWeight.Bold; return AM.FontWeight.Regular; } bool IsUnderline() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) return true; return false; } } } <MSG> add a highlighter based on text segment collection. <DFF> @@ -1,34 +1,33 @@ using System; +using System.Collections.Generic; using Avalonia.Media; using AvaloniaEdit.Document; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { - public abstract class TextTransformation : TextSegment { - public TextTransformation(object tag, int startOffset, int endOffset) + public TextTransformation(int startOffset, int endOffset) { - Tag = tag; StartOffset = startOffset; EndOffset = endOffset; } public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); - - public object Tag { get; } } public class ForegroundTextTransformation : TextTransformation { - public ForegroundTextTransformation(object tag, int startOffset, int endOffset, IBrush foreground) : base(tag, - startOffset, endOffset) + private readonly Dictionary<int, IBrush> _brushCache; + + public ForegroundTextTransformation(Dictionary<int, IBrush> brushCache, int startOffset, int endOffset, int brushId) : base(startOffset, endOffset) { - Foreground = foreground; + _brushCache = brushCache; + Foreground = brushId; } - public IBrush Foreground { get; set; } + public int Foreground { get; set; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { @@ -50,7 +49,7 @@ namespace AvaloniaEdit.TextMate endOffset = EndOffset; } - transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, Foreground); + transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, _brushCache[Foreground]); } } } \ No newline at end of file
9
add a highlighter based on text segment collection.
10
.cs
TextMate/TextTransformation
mit
AvaloniaUI/AvaloniaEdit
10067297
<NME> TextTransformation.cs <BEF> using System; using Avalonia.Media; using AvaloniaEdit.Document; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { public TextTransformation(object tag, int startOffset, int endOffset) { Tag = tag; StartOffset = startOffset; EndOffset = endOffset; } public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); public object Tag { get; } } public class ForegroundTextTransformation : TextTransformation { public ForegroundTextTransformation(object tag, int startOffset, int endOffset, IBrush foreground) : base(tag, startOffset, endOffset) { Foreground = foreground; } public IBrush Foreground { get; set; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { } var formattedOffset = 0; var endOffset = line.EndOffset; if (StartOffset > line.Offset) { formattedOffset = StartOffset - line.Offset; } if (EndOffset < line.EndOffset) { endOffset = EndOffset; } endOffset = EndOffset; } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, Foreground); } } } catch(Exception ex) { ExceptionHandler?.Invoke(ex); } } AM.FontStyle GetFontStyle() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) return AM.FontStyle.Italic; return AM.FontStyle.Normal; } AM.FontWeight GetFontWeight() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) return AM.FontWeight.Bold; return AM.FontWeight.Regular; } bool IsUnderline() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) return true; return false; } } } <MSG> add a highlighter based on text segment collection. <DFF> @@ -1,34 +1,33 @@ using System; +using System.Collections.Generic; using Avalonia.Media; using AvaloniaEdit.Document; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { - public abstract class TextTransformation : TextSegment { - public TextTransformation(object tag, int startOffset, int endOffset) + public TextTransformation(int startOffset, int endOffset) { - Tag = tag; StartOffset = startOffset; EndOffset = endOffset; } public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); - - public object Tag { get; } } public class ForegroundTextTransformation : TextTransformation { - public ForegroundTextTransformation(object tag, int startOffset, int endOffset, IBrush foreground) : base(tag, - startOffset, endOffset) + private readonly Dictionary<int, IBrush> _brushCache; + + public ForegroundTextTransformation(Dictionary<int, IBrush> brushCache, int startOffset, int endOffset, int brushId) : base(startOffset, endOffset) { - Foreground = foreground; + _brushCache = brushCache; + Foreground = brushId; } - public IBrush Foreground { get; set; } + public int Foreground { get; set; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { @@ -50,7 +49,7 @@ namespace AvaloniaEdit.TextMate endOffset = EndOffset; } - transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, Foreground); + transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, _brushCache[Foreground]); } } } \ No newline at end of file
9
add a highlighter based on text segment collection.
10
.cs
TextMate/TextTransformation
mit
AvaloniaUI/AvaloniaEdit
10067298
<NME> TextTransformation.cs <BEF> using System; using Avalonia.Media; using AvaloniaEdit.Document; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { public TextTransformation(object tag, int startOffset, int endOffset) { Tag = tag; StartOffset = startOffset; EndOffset = endOffset; } public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); public object Tag { get; } } public class ForegroundTextTransformation : TextTransformation { public ForegroundTextTransformation(object tag, int startOffset, int endOffset, IBrush foreground) : base(tag, startOffset, endOffset) { Foreground = foreground; } public IBrush Foreground { get; set; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { } var formattedOffset = 0; var endOffset = line.EndOffset; if (StartOffset > line.Offset) { formattedOffset = StartOffset - line.Offset; } if (EndOffset < line.EndOffset) { endOffset = EndOffset; } endOffset = EndOffset; } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, Foreground); } } } catch(Exception ex) { ExceptionHandler?.Invoke(ex); } } AM.FontStyle GetFontStyle() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) return AM.FontStyle.Italic; return AM.FontStyle.Normal; } AM.FontWeight GetFontWeight() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) return AM.FontWeight.Bold; return AM.FontWeight.Regular; } bool IsUnderline() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) return true; return false; } } } <MSG> add a highlighter based on text segment collection. <DFF> @@ -1,34 +1,33 @@ using System; +using System.Collections.Generic; using Avalonia.Media; using AvaloniaEdit.Document; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { - public abstract class TextTransformation : TextSegment { - public TextTransformation(object tag, int startOffset, int endOffset) + public TextTransformation(int startOffset, int endOffset) { - Tag = tag; StartOffset = startOffset; EndOffset = endOffset; } public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); - - public object Tag { get; } } public class ForegroundTextTransformation : TextTransformation { - public ForegroundTextTransformation(object tag, int startOffset, int endOffset, IBrush foreground) : base(tag, - startOffset, endOffset) + private readonly Dictionary<int, IBrush> _brushCache; + + public ForegroundTextTransformation(Dictionary<int, IBrush> brushCache, int startOffset, int endOffset, int brushId) : base(startOffset, endOffset) { - Foreground = foreground; + _brushCache = brushCache; + Foreground = brushId; } - public IBrush Foreground { get; set; } + public int Foreground { get; set; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { @@ -50,7 +49,7 @@ namespace AvaloniaEdit.TextMate endOffset = EndOffset; } - transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, Foreground); + transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, _brushCache[Foreground]); } } } \ No newline at end of file
9
add a highlighter based on text segment collection.
10
.cs
TextMate/TextTransformation
mit
AvaloniaUI/AvaloniaEdit
10067299
<NME> TextTransformation.cs <BEF> using System; using Avalonia.Media; using AvaloniaEdit.Document; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { public TextTransformation(object tag, int startOffset, int endOffset) { Tag = tag; StartOffset = startOffset; EndOffset = endOffset; } public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); public object Tag { get; } } public class ForegroundTextTransformation : TextTransformation { public ForegroundTextTransformation(object tag, int startOffset, int endOffset, IBrush foreground) : base(tag, startOffset, endOffset) { Foreground = foreground; } public IBrush Foreground { get; set; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { } var formattedOffset = 0; var endOffset = line.EndOffset; if (StartOffset > line.Offset) { formattedOffset = StartOffset - line.Offset; } if (EndOffset < line.EndOffset) { endOffset = EndOffset; } endOffset = EndOffset; } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, Foreground); } } } catch(Exception ex) { ExceptionHandler?.Invoke(ex); } } AM.FontStyle GetFontStyle() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) return AM.FontStyle.Italic; return AM.FontStyle.Normal; } AM.FontWeight GetFontWeight() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) return AM.FontWeight.Bold; return AM.FontWeight.Regular; } bool IsUnderline() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) return true; return false; } } } <MSG> add a highlighter based on text segment collection. <DFF> @@ -1,34 +1,33 @@ using System; +using System.Collections.Generic; using Avalonia.Media; using AvaloniaEdit.Document; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { - public abstract class TextTransformation : TextSegment { - public TextTransformation(object tag, int startOffset, int endOffset) + public TextTransformation(int startOffset, int endOffset) { - Tag = tag; StartOffset = startOffset; EndOffset = endOffset; } public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); - - public object Tag { get; } } public class ForegroundTextTransformation : TextTransformation { - public ForegroundTextTransformation(object tag, int startOffset, int endOffset, IBrush foreground) : base(tag, - startOffset, endOffset) + private readonly Dictionary<int, IBrush> _brushCache; + + public ForegroundTextTransformation(Dictionary<int, IBrush> brushCache, int startOffset, int endOffset, int brushId) : base(startOffset, endOffset) { - Foreground = foreground; + _brushCache = brushCache; + Foreground = brushId; } - public IBrush Foreground { get; set; } + public int Foreground { get; set; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { @@ -50,7 +49,7 @@ namespace AvaloniaEdit.TextMate endOffset = EndOffset; } - transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, Foreground); + transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, _brushCache[Foreground]); } } } \ No newline at end of file
9
add a highlighter based on text segment collection.
10
.cs
TextMate/TextTransformation
mit
AvaloniaUI/AvaloniaEdit
10067300
<NME> TextTransformation.cs <BEF> using System; using Avalonia.Media; using AvaloniaEdit.Document; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { public TextTransformation(object tag, int startOffset, int endOffset) { Tag = tag; StartOffset = startOffset; EndOffset = endOffset; } public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); public object Tag { get; } } public class ForegroundTextTransformation : TextTransformation { public ForegroundTextTransformation(object tag, int startOffset, int endOffset, IBrush foreground) : base(tag, startOffset, endOffset) { Foreground = foreground; } public IBrush Foreground { get; set; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { } var formattedOffset = 0; var endOffset = line.EndOffset; if (StartOffset > line.Offset) { formattedOffset = StartOffset - line.Offset; } if (EndOffset < line.EndOffset) { endOffset = EndOffset; } endOffset = EndOffset; } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, Foreground); } } } catch(Exception ex) { ExceptionHandler?.Invoke(ex); } } AM.FontStyle GetFontStyle() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) return AM.FontStyle.Italic; return AM.FontStyle.Normal; } AM.FontWeight GetFontWeight() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) return AM.FontWeight.Bold; return AM.FontWeight.Regular; } bool IsUnderline() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) return true; return false; } } } <MSG> add a highlighter based on text segment collection. <DFF> @@ -1,34 +1,33 @@ using System; +using System.Collections.Generic; using Avalonia.Media; using AvaloniaEdit.Document; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { - public abstract class TextTransformation : TextSegment { - public TextTransformation(object tag, int startOffset, int endOffset) + public TextTransformation(int startOffset, int endOffset) { - Tag = tag; StartOffset = startOffset; EndOffset = endOffset; } public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); - - public object Tag { get; } } public class ForegroundTextTransformation : TextTransformation { - public ForegroundTextTransformation(object tag, int startOffset, int endOffset, IBrush foreground) : base(tag, - startOffset, endOffset) + private readonly Dictionary<int, IBrush> _brushCache; + + public ForegroundTextTransformation(Dictionary<int, IBrush> brushCache, int startOffset, int endOffset, int brushId) : base(startOffset, endOffset) { - Foreground = foreground; + _brushCache = brushCache; + Foreground = brushId; } - public IBrush Foreground { get; set; } + public int Foreground { get; set; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { @@ -50,7 +49,7 @@ namespace AvaloniaEdit.TextMate endOffset = EndOffset; } - transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, Foreground); + transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, _brushCache[Foreground]); } } } \ No newline at end of file
9
add a highlighter based on text segment collection.
10
.cs
TextMate/TextTransformation
mit
AvaloniaUI/AvaloniaEdit
10067301
<NME> TextTransformation.cs <BEF> using System; using Avalonia.Media; using AvaloniaEdit.Document; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { public TextTransformation(object tag, int startOffset, int endOffset) { Tag = tag; StartOffset = startOffset; EndOffset = endOffset; } public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); public object Tag { get; } } public class ForegroundTextTransformation : TextTransformation { public ForegroundTextTransformation(object tag, int startOffset, int endOffset, IBrush foreground) : base(tag, startOffset, endOffset) { Foreground = foreground; } public IBrush Foreground { get; set; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { } var formattedOffset = 0; var endOffset = line.EndOffset; if (StartOffset > line.Offset) { formattedOffset = StartOffset - line.Offset; } if (EndOffset < line.EndOffset) { endOffset = EndOffset; } endOffset = EndOffset; } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, Foreground); } } } catch(Exception ex) { ExceptionHandler?.Invoke(ex); } } AM.FontStyle GetFontStyle() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) return AM.FontStyle.Italic; return AM.FontStyle.Normal; } AM.FontWeight GetFontWeight() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) return AM.FontWeight.Bold; return AM.FontWeight.Regular; } bool IsUnderline() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) return true; return false; } } } <MSG> add a highlighter based on text segment collection. <DFF> @@ -1,34 +1,33 @@ using System; +using System.Collections.Generic; using Avalonia.Media; using AvaloniaEdit.Document; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { - public abstract class TextTransformation : TextSegment { - public TextTransformation(object tag, int startOffset, int endOffset) + public TextTransformation(int startOffset, int endOffset) { - Tag = tag; StartOffset = startOffset; EndOffset = endOffset; } public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); - - public object Tag { get; } } public class ForegroundTextTransformation : TextTransformation { - public ForegroundTextTransformation(object tag, int startOffset, int endOffset, IBrush foreground) : base(tag, - startOffset, endOffset) + private readonly Dictionary<int, IBrush> _brushCache; + + public ForegroundTextTransformation(Dictionary<int, IBrush> brushCache, int startOffset, int endOffset, int brushId) : base(startOffset, endOffset) { - Foreground = foreground; + _brushCache = brushCache; + Foreground = brushId; } - public IBrush Foreground { get; set; } + public int Foreground { get; set; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { @@ -50,7 +49,7 @@ namespace AvaloniaEdit.TextMate endOffset = EndOffset; } - transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, Foreground); + transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, _brushCache[Foreground]); } } } \ No newline at end of file
9
add a highlighter based on text segment collection.
10
.cs
TextMate/TextTransformation
mit
AvaloniaUI/AvaloniaEdit
10067302
<NME> fruitmachine.js <BEF> /*jslint browser:true, node:true*/ /** * FruitMachine * * Renders layouts/modules from a basic layout definition. * If views require custom interactions devs can extend * the basic functionality. * * @version 0.3.3 * @copyright The Financial Times Limited [All Rights Reserved] * @author Wilson Page <[email protected]> */ 'use strict'; /** * Module Dependencies */ var mod = require('./module'); var define = require('./define'); var utils = require('utils'); var events = require('evt'); /** * Creates a fruitmachine * * Options: * * - `Model` A model constructor to use (must have `.toJSON()`) * * @param {Object} options */ module.exports = function(options) { /** * Shortcut method for * creating lazy views. * * @param {Object} options * @return {Module} */ function fm(options) { var Module = fm.modules[options.module]; if (Module) { return new Module(options); } throw new Error("Unable to find module '" + options.module + "'"); } fm.create = module.exports; fm.Model = options.Model; fm.Events = events; fm.Module = mod(fm); fm.define = define(fm); fm.util = utils; fm.modules = {}; fm.config = { templateIterator: 'children', templateInstance: 'child' }; // Mixin events and return return events(fm); }; // classes in under module type. FruitMachine.Views = {}; /** * Util */ // the key. if (key && value) { this._data[key] = value; this.trigger('datachange'); return this; } if ('object' === typeof key) { util.extend(this._data, key); this.trigger('datachange'); return this; } }, /** * Returns an array of children * that match the query. * * @param {String} query * @return {Array} */ children: function(query) { return this._childHash[query]; }, /** // duplicate event bindings and shizzle. if (this.isSetup) this.teardown({ shallow: true }); // Trigger the beforesetup event so that // FruitMachine plugins can hook into them FruitMachine.trigger('beforesetup', this); <MSG> Detailed datachange:<prop> events and improved View#children() method <DFF> @@ -74,6 +74,11 @@ // classes in under module type. FruitMachine.Views = {}; + function error() { + if (!console) return; + console.error.apply(console, arguments); + } + /** * Util */ @@ -613,7 +618,8 @@ // the key. if (key && value) { this._data[key] = value; - this.trigger('datachange'); + this.trigger('datachange', key, value); + this.trigger('datachange:' + key, value); return this; } @@ -622,6 +628,7 @@ if ('object' === typeof key) { util.extend(this._data, key); this.trigger('datachange'); + for (var prop in key) this.trigger('datachange:' + key, key[prop]); return this; } }, @@ -643,14 +650,16 @@ /** * Returns an array of children - * that match the query. + * that match the query. If no + * query is passed, all children + * are returned. * - * @param {String} query + * @param {String} [query] * @return {Array} */ children: function(query) { - return this._childHash[query]; + return query ? this._childHash[query] : this._children; }, /** @@ -704,6 +713,17 @@ // duplicate event bindings and shizzle. if (this.isSetup) this.teardown({ shallow: true }); + // If a view doesn't have an element + // we will not proceed to setup. + // + // A view may not have an element + // for the following reason + // - The {{{fm_classes}}} and {{{fm_attrs}}} hooks + // may not be present on the template. + // - A child view's html hasn't been printed + // into the parent view's template. + if (!this.el) return error("FruitMachine - No view.el found for view: '%s'", this.id()); + // Trigger the beforesetup event so that // FruitMachine plugins can hook into them FruitMachine.trigger('beforesetup', this);
24
Detailed datachange:<prop> events and improved View#children() method
4
.js
js
mit
ftlabs/fruitmachine
10067303
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors> <Version>0.10.10</Version> </PropertyGroup> <ItemGroup> <EmbeddedResource Include="**\*.xshd;**\*.resx;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> <AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> </ItemGroup> <ItemGroup> <None Remove="Search\Assets\CaseSensitive.png" /> <None Remove="Search\Assets\CompleteWord.png" /> <None Remove="Search\Assets\FindNext.png" /> <None Remove="Search\Assets\FindPrevious.png" /> <None Remove="Search\Assets\RegularExpression.png" /> <None Remove="Search\Assets\ReplaceAll.png" /> <None Remove="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="Search\Assets\CaseSensitive.png" /> <EmbeddedResource Include="Search\Assets\CompleteWord.png" /> <EmbeddedResource Include="Search\Assets\FindNext.png" /> <EmbeddedResource Include="Search\Assets\FindPrevious.png" /> <EmbeddedResource Include="Search\Assets\RegularExpression.png" /> <EmbeddedResource Include="Search\Assets\ReplaceAll.png" /> <EmbeddedResource Include="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="System.Collections.Immutable" Version="1.6.0" /> </ItemGroup> <ItemGroup> <Compile Update="SR.Designer.cs"> <DesignTime>True</DesignTime> <AutoGen>True</AutoGen> <DependentUpon>SR.resx</DependentUpon> </Compile> </ItemGroup> <ItemGroup> <EmbeddedResource Update="SR.resx"> <Generator>PublicResXFileCodeGenerator</Generator> <LastGenOutput>SR.Designer.cs</LastGenOutput> </EmbeddedResource> </ItemGroup> <Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences"> <ItemGroup> <ReferencePath Condition="'%(FileName)' == 'Splat'"> <Aliases>SystemDrawing</Aliases> </ReferencePath> </ItemGroup> </Target> </Project> <MSG> Merge pull request #184 from AvaloniaUI/drop-build.cake Drop build.cake <DFF> @@ -3,7 +3,7 @@ <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors> - <Version>0.10.10</Version> + <Version>$(AvaloniaVersion)</Version> </PropertyGroup> <ItemGroup>
1
Merge pull request #184 from AvaloniaUI/drop-build.cake
1
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10067304
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors> <Version>0.10.10</Version> </PropertyGroup> <ItemGroup> <EmbeddedResource Include="**\*.xshd;**\*.resx;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> <AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> </ItemGroup> <ItemGroup> <None Remove="Search\Assets\CaseSensitive.png" /> <None Remove="Search\Assets\CompleteWord.png" /> <None Remove="Search\Assets\FindNext.png" /> <None Remove="Search\Assets\FindPrevious.png" /> <None Remove="Search\Assets\RegularExpression.png" /> <None Remove="Search\Assets\ReplaceAll.png" /> <None Remove="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="Search\Assets\CaseSensitive.png" /> <EmbeddedResource Include="Search\Assets\CompleteWord.png" /> <EmbeddedResource Include="Search\Assets\FindNext.png" /> <EmbeddedResource Include="Search\Assets\FindPrevious.png" /> <EmbeddedResource Include="Search\Assets\RegularExpression.png" /> <EmbeddedResource Include="Search\Assets\ReplaceAll.png" /> <EmbeddedResource Include="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="System.Collections.Immutable" Version="1.6.0" /> </ItemGroup> <ItemGroup> <Compile Update="SR.Designer.cs"> <DesignTime>True</DesignTime> <AutoGen>True</AutoGen> <DependentUpon>SR.resx</DependentUpon> </Compile> </ItemGroup> <ItemGroup> <EmbeddedResource Update="SR.resx"> <Generator>PublicResXFileCodeGenerator</Generator> <LastGenOutput>SR.Designer.cs</LastGenOutput> </EmbeddedResource> </ItemGroup> <Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences"> <ItemGroup> <ReferencePath Condition="'%(FileName)' == 'Splat'"> <Aliases>SystemDrawing</Aliases> </ReferencePath> </ItemGroup> </Target> </Project> <MSG> Merge pull request #184 from AvaloniaUI/drop-build.cake Drop build.cake <DFF> @@ -3,7 +3,7 @@ <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors> - <Version>0.10.10</Version> + <Version>$(AvaloniaVersion)</Version> </PropertyGroup> <ItemGroup>
1
Merge pull request #184 from AvaloniaUI/drop-build.cake
1
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10067305
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors> <Version>0.10.10</Version> </PropertyGroup> <ItemGroup> <EmbeddedResource Include="**\*.xshd;**\*.resx;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> <AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> </ItemGroup> <ItemGroup> <None Remove="Search\Assets\CaseSensitive.png" /> <None Remove="Search\Assets\CompleteWord.png" /> <None Remove="Search\Assets\FindNext.png" /> <None Remove="Search\Assets\FindPrevious.png" /> <None Remove="Search\Assets\RegularExpression.png" /> <None Remove="Search\Assets\ReplaceAll.png" /> <None Remove="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="Search\Assets\CaseSensitive.png" /> <EmbeddedResource Include="Search\Assets\CompleteWord.png" /> <EmbeddedResource Include="Search\Assets\FindNext.png" /> <EmbeddedResource Include="Search\Assets\FindPrevious.png" /> <EmbeddedResource Include="Search\Assets\RegularExpression.png" /> <EmbeddedResource Include="Search\Assets\ReplaceAll.png" /> <EmbeddedResource Include="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="System.Collections.Immutable" Version="1.6.0" /> </ItemGroup> <ItemGroup> <Compile Update="SR.Designer.cs"> <DesignTime>True</DesignTime> <AutoGen>True</AutoGen> <DependentUpon>SR.resx</DependentUpon> </Compile> </ItemGroup> <ItemGroup> <EmbeddedResource Update="SR.resx"> <Generator>PublicResXFileCodeGenerator</Generator> <LastGenOutput>SR.Designer.cs</LastGenOutput> </EmbeddedResource> </ItemGroup> <Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences"> <ItemGroup> <ReferencePath Condition="'%(FileName)' == 'Splat'"> <Aliases>SystemDrawing</Aliases> </ReferencePath> </ItemGroup> </Target> </Project> <MSG> Merge pull request #184 from AvaloniaUI/drop-build.cake Drop build.cake <DFF> @@ -3,7 +3,7 @@ <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors> - <Version>0.10.10</Version> + <Version>$(AvaloniaVersion)</Version> </PropertyGroup> <ItemGroup>
1
Merge pull request #184 from AvaloniaUI/drop-build.cake
1
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10067306
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors> <Version>0.10.10</Version> </PropertyGroup> <ItemGroup> <EmbeddedResource Include="**\*.xshd;**\*.resx;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> <AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> </ItemGroup> <ItemGroup> <None Remove="Search\Assets\CaseSensitive.png" /> <None Remove="Search\Assets\CompleteWord.png" /> <None Remove="Search\Assets\FindNext.png" /> <None Remove="Search\Assets\FindPrevious.png" /> <None Remove="Search\Assets\RegularExpression.png" /> <None Remove="Search\Assets\ReplaceAll.png" /> <None Remove="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="Search\Assets\CaseSensitive.png" /> <EmbeddedResource Include="Search\Assets\CompleteWord.png" /> <EmbeddedResource Include="Search\Assets\FindNext.png" /> <EmbeddedResource Include="Search\Assets\FindPrevious.png" /> <EmbeddedResource Include="Search\Assets\RegularExpression.png" /> <EmbeddedResource Include="Search\Assets\ReplaceAll.png" /> <EmbeddedResource Include="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="System.Collections.Immutable" Version="1.6.0" /> </ItemGroup> <ItemGroup> <Compile Update="SR.Designer.cs"> <DesignTime>True</DesignTime> <AutoGen>True</AutoGen> <DependentUpon>SR.resx</DependentUpon> </Compile> </ItemGroup> <ItemGroup> <EmbeddedResource Update="SR.resx"> <Generator>PublicResXFileCodeGenerator</Generator> <LastGenOutput>SR.Designer.cs</LastGenOutput> </EmbeddedResource> </ItemGroup> <Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences"> <ItemGroup> <ReferencePath Condition="'%(FileName)' == 'Splat'"> <Aliases>SystemDrawing</Aliases> </ReferencePath> </ItemGroup> </Target> </Project> <MSG> Merge pull request #184 from AvaloniaUI/drop-build.cake Drop build.cake <DFF> @@ -3,7 +3,7 @@ <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors> - <Version>0.10.10</Version> + <Version>$(AvaloniaVersion)</Version> </PropertyGroup> <ItemGroup>
1
Merge pull request #184 from AvaloniaUI/drop-build.cake
1
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10067307
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors> <Version>0.10.10</Version> </PropertyGroup> <ItemGroup> <EmbeddedResource Include="**\*.xshd;**\*.resx;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> <AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> </ItemGroup> <ItemGroup> <None Remove="Search\Assets\CaseSensitive.png" /> <None Remove="Search\Assets\CompleteWord.png" /> <None Remove="Search\Assets\FindNext.png" /> <None Remove="Search\Assets\FindPrevious.png" /> <None Remove="Search\Assets\RegularExpression.png" /> <None Remove="Search\Assets\ReplaceAll.png" /> <None Remove="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="Search\Assets\CaseSensitive.png" /> <EmbeddedResource Include="Search\Assets\CompleteWord.png" /> <EmbeddedResource Include="Search\Assets\FindNext.png" /> <EmbeddedResource Include="Search\Assets\FindPrevious.png" /> <EmbeddedResource Include="Search\Assets\RegularExpression.png" /> <EmbeddedResource Include="Search\Assets\ReplaceAll.png" /> <EmbeddedResource Include="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="System.Collections.Immutable" Version="1.6.0" /> </ItemGroup> <ItemGroup> <Compile Update="SR.Designer.cs"> <DesignTime>True</DesignTime> <AutoGen>True</AutoGen> <DependentUpon>SR.resx</DependentUpon> </Compile> </ItemGroup> <ItemGroup> <EmbeddedResource Update="SR.resx"> <Generator>PublicResXFileCodeGenerator</Generator> <LastGenOutput>SR.Designer.cs</LastGenOutput> </EmbeddedResource> </ItemGroup> <Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences"> <ItemGroup> <ReferencePath Condition="'%(FileName)' == 'Splat'"> <Aliases>SystemDrawing</Aliases> </ReferencePath> </ItemGroup> </Target> </Project> <MSG> Merge pull request #184 from AvaloniaUI/drop-build.cake Drop build.cake <DFF> @@ -3,7 +3,7 @@ <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors> - <Version>0.10.10</Version> + <Version>$(AvaloniaVersion)</Version> </PropertyGroup> <ItemGroup>
1
Merge pull request #184 from AvaloniaUI/drop-build.cake
1
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10067308
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors> <Version>0.10.10</Version> </PropertyGroup> <ItemGroup> <EmbeddedResource Include="**\*.xshd;**\*.resx;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> <AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> </ItemGroup> <ItemGroup> <None Remove="Search\Assets\CaseSensitive.png" /> <None Remove="Search\Assets\CompleteWord.png" /> <None Remove="Search\Assets\FindNext.png" /> <None Remove="Search\Assets\FindPrevious.png" /> <None Remove="Search\Assets\RegularExpression.png" /> <None Remove="Search\Assets\ReplaceAll.png" /> <None Remove="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="Search\Assets\CaseSensitive.png" /> <EmbeddedResource Include="Search\Assets\CompleteWord.png" /> <EmbeddedResource Include="Search\Assets\FindNext.png" /> <EmbeddedResource Include="Search\Assets\FindPrevious.png" /> <EmbeddedResource Include="Search\Assets\RegularExpression.png" /> <EmbeddedResource Include="Search\Assets\ReplaceAll.png" /> <EmbeddedResource Include="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="System.Collections.Immutable" Version="1.6.0" /> </ItemGroup> <ItemGroup> <Compile Update="SR.Designer.cs"> <DesignTime>True</DesignTime> <AutoGen>True</AutoGen> <DependentUpon>SR.resx</DependentUpon> </Compile> </ItemGroup> <ItemGroup> <EmbeddedResource Update="SR.resx"> <Generator>PublicResXFileCodeGenerator</Generator> <LastGenOutput>SR.Designer.cs</LastGenOutput> </EmbeddedResource> </ItemGroup> <Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences"> <ItemGroup> <ReferencePath Condition="'%(FileName)' == 'Splat'"> <Aliases>SystemDrawing</Aliases> </ReferencePath> </ItemGroup> </Target> </Project> <MSG> Merge pull request #184 from AvaloniaUI/drop-build.cake Drop build.cake <DFF> @@ -3,7 +3,7 @@ <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors> - <Version>0.10.10</Version> + <Version>$(AvaloniaVersion)</Version> </PropertyGroup> <ItemGroup>
1
Merge pull request #184 from AvaloniaUI/drop-build.cake
1
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10067309
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors> <Version>0.10.10</Version> </PropertyGroup> <ItemGroup> <EmbeddedResource Include="**\*.xshd;**\*.resx;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> <AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> </ItemGroup> <ItemGroup> <None Remove="Search\Assets\CaseSensitive.png" /> <None Remove="Search\Assets\CompleteWord.png" /> <None Remove="Search\Assets\FindNext.png" /> <None Remove="Search\Assets\FindPrevious.png" /> <None Remove="Search\Assets\RegularExpression.png" /> <None Remove="Search\Assets\ReplaceAll.png" /> <None Remove="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="Search\Assets\CaseSensitive.png" /> <EmbeddedResource Include="Search\Assets\CompleteWord.png" /> <EmbeddedResource Include="Search\Assets\FindNext.png" /> <EmbeddedResource Include="Search\Assets\FindPrevious.png" /> <EmbeddedResource Include="Search\Assets\RegularExpression.png" /> <EmbeddedResource Include="Search\Assets\ReplaceAll.png" /> <EmbeddedResource Include="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="System.Collections.Immutable" Version="1.6.0" /> </ItemGroup> <ItemGroup> <Compile Update="SR.Designer.cs"> <DesignTime>True</DesignTime> <AutoGen>True</AutoGen> <DependentUpon>SR.resx</DependentUpon> </Compile> </ItemGroup> <ItemGroup> <EmbeddedResource Update="SR.resx"> <Generator>PublicResXFileCodeGenerator</Generator> <LastGenOutput>SR.Designer.cs</LastGenOutput> </EmbeddedResource> </ItemGroup> <Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences"> <ItemGroup> <ReferencePath Condition="'%(FileName)' == 'Splat'"> <Aliases>SystemDrawing</Aliases> </ReferencePath> </ItemGroup> </Target> </Project> <MSG> Merge pull request #184 from AvaloniaUI/drop-build.cake Drop build.cake <DFF> @@ -3,7 +3,7 @@ <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors> - <Version>0.10.10</Version> + <Version>$(AvaloniaVersion)</Version> </PropertyGroup> <ItemGroup>
1
Merge pull request #184 from AvaloniaUI/drop-build.cake
1
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10067310
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors> <Version>0.10.10</Version> </PropertyGroup> <ItemGroup> <EmbeddedResource Include="**\*.xshd;**\*.resx;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> <AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> </ItemGroup> <ItemGroup> <None Remove="Search\Assets\CaseSensitive.png" /> <None Remove="Search\Assets\CompleteWord.png" /> <None Remove="Search\Assets\FindNext.png" /> <None Remove="Search\Assets\FindPrevious.png" /> <None Remove="Search\Assets\RegularExpression.png" /> <None Remove="Search\Assets\ReplaceAll.png" /> <None Remove="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="Search\Assets\CaseSensitive.png" /> <EmbeddedResource Include="Search\Assets\CompleteWord.png" /> <EmbeddedResource Include="Search\Assets\FindNext.png" /> <EmbeddedResource Include="Search\Assets\FindPrevious.png" /> <EmbeddedResource Include="Search\Assets\RegularExpression.png" /> <EmbeddedResource Include="Search\Assets\ReplaceAll.png" /> <EmbeddedResource Include="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="System.Collections.Immutable" Version="1.6.0" /> </ItemGroup> <ItemGroup> <Compile Update="SR.Designer.cs"> <DesignTime>True</DesignTime> <AutoGen>True</AutoGen> <DependentUpon>SR.resx</DependentUpon> </Compile> </ItemGroup> <ItemGroup> <EmbeddedResource Update="SR.resx"> <Generator>PublicResXFileCodeGenerator</Generator> <LastGenOutput>SR.Designer.cs</LastGenOutput> </EmbeddedResource> </ItemGroup> <Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences"> <ItemGroup> <ReferencePath Condition="'%(FileName)' == 'Splat'"> <Aliases>SystemDrawing</Aliases> </ReferencePath> </ItemGroup> </Target> </Project> <MSG> Merge pull request #184 from AvaloniaUI/drop-build.cake Drop build.cake <DFF> @@ -3,7 +3,7 @@ <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors> - <Version>0.10.10</Version> + <Version>$(AvaloniaVersion)</Version> </PropertyGroup> <ItemGroup>
1
Merge pull request #184 from AvaloniaUI/drop-build.cake
1
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10067311
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors> <Version>0.10.10</Version> </PropertyGroup> <ItemGroup> <EmbeddedResource Include="**\*.xshd;**\*.resx;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> <AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> </ItemGroup> <ItemGroup> <None Remove="Search\Assets\CaseSensitive.png" /> <None Remove="Search\Assets\CompleteWord.png" /> <None Remove="Search\Assets\FindNext.png" /> <None Remove="Search\Assets\FindPrevious.png" /> <None Remove="Search\Assets\RegularExpression.png" /> <None Remove="Search\Assets\ReplaceAll.png" /> <None Remove="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="Search\Assets\CaseSensitive.png" /> <EmbeddedResource Include="Search\Assets\CompleteWord.png" /> <EmbeddedResource Include="Search\Assets\FindNext.png" /> <EmbeddedResource Include="Search\Assets\FindPrevious.png" /> <EmbeddedResource Include="Search\Assets\RegularExpression.png" /> <EmbeddedResource Include="Search\Assets\ReplaceAll.png" /> <EmbeddedResource Include="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="System.Collections.Immutable" Version="1.6.0" /> </ItemGroup> <ItemGroup> <Compile Update="SR.Designer.cs"> <DesignTime>True</DesignTime> <AutoGen>True</AutoGen> <DependentUpon>SR.resx</DependentUpon> </Compile> </ItemGroup> <ItemGroup> <EmbeddedResource Update="SR.resx"> <Generator>PublicResXFileCodeGenerator</Generator> <LastGenOutput>SR.Designer.cs</LastGenOutput> </EmbeddedResource> </ItemGroup> <Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences"> <ItemGroup> <ReferencePath Condition="'%(FileName)' == 'Splat'"> <Aliases>SystemDrawing</Aliases> </ReferencePath> </ItemGroup> </Target> </Project> <MSG> Merge pull request #184 from AvaloniaUI/drop-build.cake Drop build.cake <DFF> @@ -3,7 +3,7 @@ <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors> - <Version>0.10.10</Version> + <Version>$(AvaloniaVersion)</Version> </PropertyGroup> <ItemGroup>
1
Merge pull request #184 from AvaloniaUI/drop-build.cake
1
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10067312
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors> <Version>0.10.10</Version> </PropertyGroup> <ItemGroup> <EmbeddedResource Include="**\*.xshd;**\*.resx;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> <AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> </ItemGroup> <ItemGroup> <None Remove="Search\Assets\CaseSensitive.png" /> <None Remove="Search\Assets\CompleteWord.png" /> <None Remove="Search\Assets\FindNext.png" /> <None Remove="Search\Assets\FindPrevious.png" /> <None Remove="Search\Assets\RegularExpression.png" /> <None Remove="Search\Assets\ReplaceAll.png" /> <None Remove="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="Search\Assets\CaseSensitive.png" /> <EmbeddedResource Include="Search\Assets\CompleteWord.png" /> <EmbeddedResource Include="Search\Assets\FindNext.png" /> <EmbeddedResource Include="Search\Assets\FindPrevious.png" /> <EmbeddedResource Include="Search\Assets\RegularExpression.png" /> <EmbeddedResource Include="Search\Assets\ReplaceAll.png" /> <EmbeddedResource Include="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="System.Collections.Immutable" Version="1.6.0" /> </ItemGroup> <ItemGroup> <Compile Update="SR.Designer.cs"> <DesignTime>True</DesignTime> <AutoGen>True</AutoGen> <DependentUpon>SR.resx</DependentUpon> </Compile> </ItemGroup> <ItemGroup> <EmbeddedResource Update="SR.resx"> <Generator>PublicResXFileCodeGenerator</Generator> <LastGenOutput>SR.Designer.cs</LastGenOutput> </EmbeddedResource> </ItemGroup> <Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences"> <ItemGroup> <ReferencePath Condition="'%(FileName)' == 'Splat'"> <Aliases>SystemDrawing</Aliases> </ReferencePath> </ItemGroup> </Target> </Project> <MSG> Merge pull request #184 from AvaloniaUI/drop-build.cake Drop build.cake <DFF> @@ -3,7 +3,7 @@ <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors> - <Version>0.10.10</Version> + <Version>$(AvaloniaVersion)</Version> </PropertyGroup> <ItemGroup>
1
Merge pull request #184 from AvaloniaUI/drop-build.cake
1
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10067313
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors> <Version>0.10.10</Version> </PropertyGroup> <ItemGroup> <EmbeddedResource Include="**\*.xshd;**\*.resx;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> <AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> </ItemGroup> <ItemGroup> <None Remove="Search\Assets\CaseSensitive.png" /> <None Remove="Search\Assets\CompleteWord.png" /> <None Remove="Search\Assets\FindNext.png" /> <None Remove="Search\Assets\FindPrevious.png" /> <None Remove="Search\Assets\RegularExpression.png" /> <None Remove="Search\Assets\ReplaceAll.png" /> <None Remove="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="Search\Assets\CaseSensitive.png" /> <EmbeddedResource Include="Search\Assets\CompleteWord.png" /> <EmbeddedResource Include="Search\Assets\FindNext.png" /> <EmbeddedResource Include="Search\Assets\FindPrevious.png" /> <EmbeddedResource Include="Search\Assets\RegularExpression.png" /> <EmbeddedResource Include="Search\Assets\ReplaceAll.png" /> <EmbeddedResource Include="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="System.Collections.Immutable" Version="1.6.0" /> </ItemGroup> <ItemGroup> <Compile Update="SR.Designer.cs"> <DesignTime>True</DesignTime> <AutoGen>True</AutoGen> <DependentUpon>SR.resx</DependentUpon> </Compile> </ItemGroup> <ItemGroup> <EmbeddedResource Update="SR.resx"> <Generator>PublicResXFileCodeGenerator</Generator> <LastGenOutput>SR.Designer.cs</LastGenOutput> </EmbeddedResource> </ItemGroup> <Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences"> <ItemGroup> <ReferencePath Condition="'%(FileName)' == 'Splat'"> <Aliases>SystemDrawing</Aliases> </ReferencePath> </ItemGroup> </Target> </Project> <MSG> Merge pull request #184 from AvaloniaUI/drop-build.cake Drop build.cake <DFF> @@ -3,7 +3,7 @@ <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors> - <Version>0.10.10</Version> + <Version>$(AvaloniaVersion)</Version> </PropertyGroup> <ItemGroup>
1
Merge pull request #184 from AvaloniaUI/drop-build.cake
1
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10067314
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors> <Version>0.10.10</Version> </PropertyGroup> <ItemGroup> <EmbeddedResource Include="**\*.xshd;**\*.resx;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> <AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> </ItemGroup> <ItemGroup> <None Remove="Search\Assets\CaseSensitive.png" /> <None Remove="Search\Assets\CompleteWord.png" /> <None Remove="Search\Assets\FindNext.png" /> <None Remove="Search\Assets\FindPrevious.png" /> <None Remove="Search\Assets\RegularExpression.png" /> <None Remove="Search\Assets\ReplaceAll.png" /> <None Remove="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="Search\Assets\CaseSensitive.png" /> <EmbeddedResource Include="Search\Assets\CompleteWord.png" /> <EmbeddedResource Include="Search\Assets\FindNext.png" /> <EmbeddedResource Include="Search\Assets\FindPrevious.png" /> <EmbeddedResource Include="Search\Assets\RegularExpression.png" /> <EmbeddedResource Include="Search\Assets\ReplaceAll.png" /> <EmbeddedResource Include="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="System.Collections.Immutable" Version="1.6.0" /> </ItemGroup> <ItemGroup> <Compile Update="SR.Designer.cs"> <DesignTime>True</DesignTime> <AutoGen>True</AutoGen> <DependentUpon>SR.resx</DependentUpon> </Compile> </ItemGroup> <ItemGroup> <EmbeddedResource Update="SR.resx"> <Generator>PublicResXFileCodeGenerator</Generator> <LastGenOutput>SR.Designer.cs</LastGenOutput> </EmbeddedResource> </ItemGroup> <Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences"> <ItemGroup> <ReferencePath Condition="'%(FileName)' == 'Splat'"> <Aliases>SystemDrawing</Aliases> </ReferencePath> </ItemGroup> </Target> </Project> <MSG> Merge pull request #184 from AvaloniaUI/drop-build.cake Drop build.cake <DFF> @@ -3,7 +3,7 @@ <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors> - <Version>0.10.10</Version> + <Version>$(AvaloniaVersion)</Version> </PropertyGroup> <ItemGroup>
1
Merge pull request #184 from AvaloniaUI/drop-build.cake
1
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10067315
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors> <Version>0.10.10</Version> </PropertyGroup> <ItemGroup> <EmbeddedResource Include="**\*.xshd;**\*.resx;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> <AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> </ItemGroup> <ItemGroup> <None Remove="Search\Assets\CaseSensitive.png" /> <None Remove="Search\Assets\CompleteWord.png" /> <None Remove="Search\Assets\FindNext.png" /> <None Remove="Search\Assets\FindPrevious.png" /> <None Remove="Search\Assets\RegularExpression.png" /> <None Remove="Search\Assets\ReplaceAll.png" /> <None Remove="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="Search\Assets\CaseSensitive.png" /> <EmbeddedResource Include="Search\Assets\CompleteWord.png" /> <EmbeddedResource Include="Search\Assets\FindNext.png" /> <EmbeddedResource Include="Search\Assets\FindPrevious.png" /> <EmbeddedResource Include="Search\Assets\RegularExpression.png" /> <EmbeddedResource Include="Search\Assets\ReplaceAll.png" /> <EmbeddedResource Include="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="System.Collections.Immutable" Version="1.6.0" /> </ItemGroup> <ItemGroup> <Compile Update="SR.Designer.cs"> <DesignTime>True</DesignTime> <AutoGen>True</AutoGen> <DependentUpon>SR.resx</DependentUpon> </Compile> </ItemGroup> <ItemGroup> <EmbeddedResource Update="SR.resx"> <Generator>PublicResXFileCodeGenerator</Generator> <LastGenOutput>SR.Designer.cs</LastGenOutput> </EmbeddedResource> </ItemGroup> <Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences"> <ItemGroup> <ReferencePath Condition="'%(FileName)' == 'Splat'"> <Aliases>SystemDrawing</Aliases> </ReferencePath> </ItemGroup> </Target> </Project> <MSG> Merge pull request #184 from AvaloniaUI/drop-build.cake Drop build.cake <DFF> @@ -3,7 +3,7 @@ <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors> - <Version>0.10.10</Version> + <Version>$(AvaloniaVersion)</Version> </PropertyGroup> <ItemGroup>
1
Merge pull request #184 from AvaloniaUI/drop-build.cake
1
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10067316
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors> <Version>0.10.10</Version> </PropertyGroup> <ItemGroup> <EmbeddedResource Include="**\*.xshd;**\*.resx;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> <AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> </ItemGroup> <ItemGroup> <None Remove="Search\Assets\CaseSensitive.png" /> <None Remove="Search\Assets\CompleteWord.png" /> <None Remove="Search\Assets\FindNext.png" /> <None Remove="Search\Assets\FindPrevious.png" /> <None Remove="Search\Assets\RegularExpression.png" /> <None Remove="Search\Assets\ReplaceAll.png" /> <None Remove="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="Search\Assets\CaseSensitive.png" /> <EmbeddedResource Include="Search\Assets\CompleteWord.png" /> <EmbeddedResource Include="Search\Assets\FindNext.png" /> <EmbeddedResource Include="Search\Assets\FindPrevious.png" /> <EmbeddedResource Include="Search\Assets\RegularExpression.png" /> <EmbeddedResource Include="Search\Assets\ReplaceAll.png" /> <EmbeddedResource Include="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="System.Collections.Immutable" Version="1.6.0" /> </ItemGroup> <ItemGroup> <Compile Update="SR.Designer.cs"> <DesignTime>True</DesignTime> <AutoGen>True</AutoGen> <DependentUpon>SR.resx</DependentUpon> </Compile> </ItemGroup> <ItemGroup> <EmbeddedResource Update="SR.resx"> <Generator>PublicResXFileCodeGenerator</Generator> <LastGenOutput>SR.Designer.cs</LastGenOutput> </EmbeddedResource> </ItemGroup> <Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences"> <ItemGroup> <ReferencePath Condition="'%(FileName)' == 'Splat'"> <Aliases>SystemDrawing</Aliases> </ReferencePath> </ItemGroup> </Target> </Project> <MSG> Merge pull request #184 from AvaloniaUI/drop-build.cake Drop build.cake <DFF> @@ -3,7 +3,7 @@ <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors> - <Version>0.10.10</Version> + <Version>$(AvaloniaVersion)</Version> </PropertyGroup> <ItemGroup>
1
Merge pull request #184 from AvaloniaUI/drop-build.cake
1
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10067317
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors> <Version>0.10.10</Version> </PropertyGroup> <ItemGroup> <EmbeddedResource Include="**\*.xshd;**\*.resx;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> <AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> </ItemGroup> <ItemGroup> <None Remove="Search\Assets\CaseSensitive.png" /> <None Remove="Search\Assets\CompleteWord.png" /> <None Remove="Search\Assets\FindNext.png" /> <None Remove="Search\Assets\FindPrevious.png" /> <None Remove="Search\Assets\RegularExpression.png" /> <None Remove="Search\Assets\ReplaceAll.png" /> <None Remove="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="Search\Assets\CaseSensitive.png" /> <EmbeddedResource Include="Search\Assets\CompleteWord.png" /> <EmbeddedResource Include="Search\Assets\FindNext.png" /> <EmbeddedResource Include="Search\Assets\FindPrevious.png" /> <EmbeddedResource Include="Search\Assets\RegularExpression.png" /> <EmbeddedResource Include="Search\Assets\ReplaceAll.png" /> <EmbeddedResource Include="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="System.Collections.Immutable" Version="1.6.0" /> </ItemGroup> <ItemGroup> <Compile Update="SR.Designer.cs"> <DesignTime>True</DesignTime> <AutoGen>True</AutoGen> <DependentUpon>SR.resx</DependentUpon> </Compile> </ItemGroup> <ItemGroup> <EmbeddedResource Update="SR.resx"> <Generator>PublicResXFileCodeGenerator</Generator> <LastGenOutput>SR.Designer.cs</LastGenOutput> </EmbeddedResource> </ItemGroup> <Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences"> <ItemGroup> <ReferencePath Condition="'%(FileName)' == 'Splat'"> <Aliases>SystemDrawing</Aliases> </ReferencePath> </ItemGroup> </Target> </Project> <MSG> Merge pull request #184 from AvaloniaUI/drop-build.cake Drop build.cake <DFF> @@ -3,7 +3,7 @@ <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors> - <Version>0.10.10</Version> + <Version>$(AvaloniaVersion)</Version> </PropertyGroup> <ItemGroup>
1
Merge pull request #184 from AvaloniaUI/drop-build.cake
1
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10067318
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.9.0-preview5</AvaloniaVersion> </PropertyGroup> </Project> <VersionSuffix>beta</VersionSuffix> </PropertyGroup> </Project> <MSG> update to avalonia preview 7 <DFF> @@ -2,6 +2,6 @@ <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> - <AvaloniaVersion>0.9.0-preview5</AvaloniaVersion> + <AvaloniaVersion>0.9.0-preview7</AvaloniaVersion> </PropertyGroup> </Project> \ No newline at end of file
1
update to avalonia preview 7
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10067319
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.9.0-preview5</AvaloniaVersion> </PropertyGroup> </Project> <VersionSuffix>beta</VersionSuffix> </PropertyGroup> </Project> <MSG> update to avalonia preview 7 <DFF> @@ -2,6 +2,6 @@ <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> - <AvaloniaVersion>0.9.0-preview5</AvaloniaVersion> + <AvaloniaVersion>0.9.0-preview7</AvaloniaVersion> </PropertyGroup> </Project> \ No newline at end of file
1
update to avalonia preview 7
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10067320
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.9.0-preview5</AvaloniaVersion> </PropertyGroup> </Project> <VersionSuffix>beta</VersionSuffix> </PropertyGroup> </Project> <MSG> update to avalonia preview 7 <DFF> @@ -2,6 +2,6 @@ <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> - <AvaloniaVersion>0.9.0-preview5</AvaloniaVersion> + <AvaloniaVersion>0.9.0-preview7</AvaloniaVersion> </PropertyGroup> </Project> \ No newline at end of file
1
update to avalonia preview 7
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10067321
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.9.0-preview5</AvaloniaVersion> </PropertyGroup> </Project> <VersionSuffix>beta</VersionSuffix> </PropertyGroup> </Project> <MSG> update to avalonia preview 7 <DFF> @@ -2,6 +2,6 @@ <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> - <AvaloniaVersion>0.9.0-preview5</AvaloniaVersion> + <AvaloniaVersion>0.9.0-preview7</AvaloniaVersion> </PropertyGroup> </Project> \ No newline at end of file
1
update to avalonia preview 7
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10067322
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.9.0-preview5</AvaloniaVersion> </PropertyGroup> </Project> <VersionSuffix>beta</VersionSuffix> </PropertyGroup> </Project> <MSG> update to avalonia preview 7 <DFF> @@ -2,6 +2,6 @@ <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> - <AvaloniaVersion>0.9.0-preview5</AvaloniaVersion> + <AvaloniaVersion>0.9.0-preview7</AvaloniaVersion> </PropertyGroup> </Project> \ No newline at end of file
1
update to avalonia preview 7
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10067323
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.9.0-preview5</AvaloniaVersion> </PropertyGroup> </Project> <VersionSuffix>beta</VersionSuffix> </PropertyGroup> </Project> <MSG> update to avalonia preview 7 <DFF> @@ -2,6 +2,6 @@ <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> - <AvaloniaVersion>0.9.0-preview5</AvaloniaVersion> + <AvaloniaVersion>0.9.0-preview7</AvaloniaVersion> </PropertyGroup> </Project> \ No newline at end of file
1
update to avalonia preview 7
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10067324
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.9.0-preview5</AvaloniaVersion> </PropertyGroup> </Project> <VersionSuffix>beta</VersionSuffix> </PropertyGroup> </Project> <MSG> update to avalonia preview 7 <DFF> @@ -2,6 +2,6 @@ <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> - <AvaloniaVersion>0.9.0-preview5</AvaloniaVersion> + <AvaloniaVersion>0.9.0-preview7</AvaloniaVersion> </PropertyGroup> </Project> \ No newline at end of file
1
update to avalonia preview 7
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10067325
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.9.0-preview5</AvaloniaVersion> </PropertyGroup> </Project> <VersionSuffix>beta</VersionSuffix> </PropertyGroup> </Project> <MSG> update to avalonia preview 7 <DFF> @@ -2,6 +2,6 @@ <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> - <AvaloniaVersion>0.9.0-preview5</AvaloniaVersion> + <AvaloniaVersion>0.9.0-preview7</AvaloniaVersion> </PropertyGroup> </Project> \ No newline at end of file
1
update to avalonia preview 7
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10067326
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.9.0-preview5</AvaloniaVersion> </PropertyGroup> </Project> <VersionSuffix>beta</VersionSuffix> </PropertyGroup> </Project> <MSG> update to avalonia preview 7 <DFF> @@ -2,6 +2,6 @@ <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> - <AvaloniaVersion>0.9.0-preview5</AvaloniaVersion> + <AvaloniaVersion>0.9.0-preview7</AvaloniaVersion> </PropertyGroup> </Project> \ No newline at end of file
1
update to avalonia preview 7
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10067327
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.9.0-preview5</AvaloniaVersion> </PropertyGroup> </Project> <VersionSuffix>beta</VersionSuffix> </PropertyGroup> </Project> <MSG> update to avalonia preview 7 <DFF> @@ -2,6 +2,6 @@ <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> - <AvaloniaVersion>0.9.0-preview5</AvaloniaVersion> + <AvaloniaVersion>0.9.0-preview7</AvaloniaVersion> </PropertyGroup> </Project> \ No newline at end of file
1
update to avalonia preview 7
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10067328
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.9.0-preview5</AvaloniaVersion> </PropertyGroup> </Project> <VersionSuffix>beta</VersionSuffix> </PropertyGroup> </Project> <MSG> update to avalonia preview 7 <DFF> @@ -2,6 +2,6 @@ <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> - <AvaloniaVersion>0.9.0-preview5</AvaloniaVersion> + <AvaloniaVersion>0.9.0-preview7</AvaloniaVersion> </PropertyGroup> </Project> \ No newline at end of file
1
update to avalonia preview 7
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10067329
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.9.0-preview5</AvaloniaVersion> </PropertyGroup> </Project> <VersionSuffix>beta</VersionSuffix> </PropertyGroup> </Project> <MSG> update to avalonia preview 7 <DFF> @@ -2,6 +2,6 @@ <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> - <AvaloniaVersion>0.9.0-preview5</AvaloniaVersion> + <AvaloniaVersion>0.9.0-preview7</AvaloniaVersion> </PropertyGroup> </Project> \ No newline at end of file
1
update to avalonia preview 7
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10067330
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.9.0-preview5</AvaloniaVersion> </PropertyGroup> </Project> <VersionSuffix>beta</VersionSuffix> </PropertyGroup> </Project> <MSG> update to avalonia preview 7 <DFF> @@ -2,6 +2,6 @@ <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> - <AvaloniaVersion>0.9.0-preview5</AvaloniaVersion> + <AvaloniaVersion>0.9.0-preview7</AvaloniaVersion> </PropertyGroup> </Project> \ No newline at end of file
1
update to avalonia preview 7
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10067331
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.9.0-preview5</AvaloniaVersion> </PropertyGroup> </Project> <VersionSuffix>beta</VersionSuffix> </PropertyGroup> </Project> <MSG> update to avalonia preview 7 <DFF> @@ -2,6 +2,6 @@ <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> - <AvaloniaVersion>0.9.0-preview5</AvaloniaVersion> + <AvaloniaVersion>0.9.0-preview7</AvaloniaVersion> </PropertyGroup> </Project> \ No newline at end of file
1
update to avalonia preview 7
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10067332
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.9.0-preview5</AvaloniaVersion> </PropertyGroup> </Project> <VersionSuffix>beta</VersionSuffix> </PropertyGroup> </Project> <MSG> update to avalonia preview 7 <DFF> @@ -2,6 +2,6 @@ <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> - <AvaloniaVersion>0.9.0-preview5</AvaloniaVersion> + <AvaloniaVersion>0.9.0-preview7</AvaloniaVersion> </PropertyGroup> </Project> \ No newline at end of file
1
update to avalonia preview 7
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10067333
<NME> .travis.yml <BEF> script: - "npm test" language: node_js node_js: - "0.12" sudo: false <MSG> Bump travis node version to match what many packages require <DFF> @@ -4,6 +4,6 @@ script: language: node_js node_js: - - "0.12" + - "6" sudo: false
1
Bump travis node version to match what many packages require
1
.yml
travis
mit
ftlabs/fruitmachine
10067334
<NME> README.md <BEF> # FruitMachine [![Build Status](https://api.travis-ci.com/ftlabs/fruitmachine.svg)](https://travis-ci.com/ftlabs/fruitmachine) [![Coverage Status](https://coveralls.io/repos/ftlabs/fruitmachine/badge.png)](https://coveralls.io/r/ftlabs/fruitmachine) A lightweight component layout engine for client and server. ### View(); <p>View constructor</p> ### create(); <p>Creates a new FruitMachine view using the options passed.</p> ### View#trigger(); <p>Proxies the standard Event.trigger method so that we can add bubble functionality.</p> ### View#id(); <p>Returns a decendent module by id, or if called with no arguments, returns this view's id.</p> ### View#child(); <p>Returns the first child view that matches the query.</p> ### View#children(); <p>Allows three ways to return a view's children and direct children, depending on arguments passed.</p> ### View#each(); <p>Calls the passed function for each of the view's children.</p> ### View#remove(); <p>Removes the View's element from the DOM.</p> ### View#empty(); <p>Destroys all children.</p> ### View#closestElement(); <p>Returns the closest root view element, walking up the chain until it finds one.</p> ### View#getElement(); <p>Returns the View's root element.</p> ### View#setElement(); <p>Sets a root element on a view. If the view already has a root element, it is replaced.</p> ### View#purgeElementCaches(); <p>Recursively purges the element cache.</p> ### View#data(); <p>A single method for getting and setting view data.</p> ### View#inDOM(); <p>Detects whether a view is in the DOM (useful for debugging).</p> ### View#toNode(); <p>Templates the whole view and turns it into a real node.</p> ### View#inject(); <p>Empties the destination element and appends the view into it.</p> ### View#appendTo(); <p>Appends the view element into the destination element.</p> ### View#toJSON(); <p>Returns a JSON represention of a FruitMachine View. This can be generated serverside and passed into new FruitMachine(json) to inflate serverside rendered views.</p> ### Model#get(); <p>Gets a value by key</p> ### module(); <p>Creates and registers a FruitMachine view constructor.</p> ### clear(); <p>Removes a module from the module store.</p> ### helper(); <p>Registers a helper</p> ### clear(); <p>Clears one or all registered helpers.</p> ### templates(); <p>Registers templates, or overwrites the <code>getTemplate</code> method with a custom template getter function.</p> ### getTemplate(); <p>The default get template method if FruitMachine.template is passed a function, this gets overwritten by that.</p> ### clear(); <p>Clear reference to a module's template, or clear all template references and resets the template getter method.</p> ### FruitMachine(); <p>The main library namespace doubling as a convenient alias for creating new views.</p> ## License <MSG> Added discription.body and test using option <DFF> @@ -5,115 +5,246 @@ Assembles dynamic views on the client and server. ### View(); -<p>View constructor</p> +View constructor + + ### create(); -<p>Creates a new FruitMachine view using the options passed.</p> +Creates a new FruitMachine view +using the options passed. + +If a module parameter is passed +we attempt to find a registered +module of that name to intantiate, +else we use a default view instance. ### View#trigger(); -<p>Proxies the standard Event.trigger method so that we can add bubble functionality.</p> +Proxies the standard Event.trigger +method so that we can add bubble +functionality. + +Options: + + - `propagate` States whether the event + should bubble through parent views. ### View#id(); -<p>Returns a decendent module by id, or if called with no arguments, returns this view's id.</p> +Returns a decendent module +by id, or if called with no +arguments, returns this view's id. + + ### View#child(); -<p>Returns the first child view that matches the query.</p> +Returns the first child +view that matches the query. + +Example: + + var child = view.child(<id>); + var child = view.child(<module>); ### View#children(); -<p>Allows three ways to return a view's children and direct children, depending on arguments passed.</p> +Allows three ways to return +a view's children and direct +children, depending on arguments +passed. + +Example: + + // Return all direct children + view.children(); + + // Return all children that match query. + view.children('orange'); ### View#each(); -<p>Calls the passed function for each of the view's children.</p> +Calls the passed function +for each of the view's +children. + + ### View#remove(); -<p>Removes the View's element from the DOM.</p> +Removes the View's element +from the DOM. + + ### View#empty(); -<p>Destroys all children.</p> +Destroys all children. + + ### View#closestElement(); -<p>Returns the closest root view element, walking up the chain until it finds one.</p> +Returns the closest root view +element, walking up the chain +until it finds one. + + ### View#getElement(); -<p>Returns the View's root element.</p> +Returns the View's root element. + +If a cache is present it is used, +else we search the DOM, else we +find the closest element and +perform a querySelector using +the view._fmid. ### View#setElement(); -<p>Sets a root element on a view. If the view already has a root element, it is replaced.</p> +Sets a root element on a view. +If the view already has a root +element, it is replaced. + +IMPORTANT: All descendent root +element caches are purged so that +the new correct elements are retrieved +next time View#getElement is called. ### View#purgeElementCaches(); -<p>Recursively purges the element cache.</p> +Recursively purges the +element cache. + + ### View#data(); -<p>A single method for getting and setting view data.</p> +A single method for getting +and setting view data. + +Example: + + // Getters + var all = view.data(); + var one = view.data('myKey'); + + // Setters + view.data('myKey', 'my value'); + view.data({ + myKey: 'my value', + anotherKey: 10 + }); ### View#inDOM(); -<p>Detects whether a view is in the DOM (useful for debugging).</p> +Detects whether a view is in +the DOM (useful for debugging). + + ### View#toNode(); -<p>Templates the whole view and turns it into a real node.</p> +Templates the whole view and turns +it into a real node. + + ### View#inject(); -<p>Empties the destination element and appends the view into it.</p> +Empties the destination element +and appends the view into it. + + ### View#appendTo(); -<p>Appends the view element into the destination element.</p> +Appends the view element into +the destination element. + + ### View#toJSON(); -<p>Returns a JSON represention of a FruitMachine View. This can be generated serverside and passed into new FruitMachine(json) to inflate serverside rendered views.</p> +Returns a JSON represention of +a FruitMachine View. This can +be generated serverside and +passed into new FruitMachine(json) +to inflate serverside rendered +views. + + ### Model#get(); -<p>Gets a value by key</p> +Gets a value by key + +If no key is given, the +whole model is returned. ### module(); -<p>Creates and registers a FruitMachine view constructor.</p> +Creates and registers a +FruitMachine view constructor. + + ### clear(); -<p>Removes a module from the module store.</p> +Removes a module +from the module store. + +If no module key is passed +the entire store is cleared. ### helper(); -<p>Registers a helper</p> +Registers a helper + + ### clear(); -<p>Clears one or all registered helpers.</p> +Clears one or all +registered helpers. + + ### templates(); -<p>Registers templates, or overwrites the <code>getTemplate</code> method with a custom template getter function.</p> +Registers templates, or overwrites +the `getTemplate` method with a +custom template getter function. + + ### getTemplate(); -<p>The default get template method if FruitMachine.template is passed a function, this gets overwritten by that.</p> +The default get template method +if FruitMachine.template is passed +a function, this gets overwritten +by that. + + ### clear(); -<p>Clear reference to a module's template, or clear all template references and resets the template getter method.</p> +Clear reference to a module's +template, or clear all template +references and resets the template +getter method. + + ### FruitMachine(); -<p>The main library namespace doubling as a convenient alias for creating new views.</p> +The main library namespace doubling +as a convenient alias for creating +new views. + + ## License
159
Added discription.body and test using option
28
.md
md
mit
ftlabs/fruitmachine
10067335
<NME> TextEditor.cs <BEF> // 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 Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent { #region Constructors static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) protected TextEditor(TextArea textArea, TextDocument document) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => 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) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently used by the text editor. /// </summary> public TextEditorOptions Options { get => 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) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var 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. CaretOffset = 0; document.UndoStack.ClearAll(); } } #endregion #region TextArea / ScrollViewer properties protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea { get; } /// <summary> /// Gets the scroll viewer used by the text editor. #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { if (_colorizer != null) { TextArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } /// <summary> /// Gets the text area. _colorizer = CreateColorizer(newValue); if (_colorizer != null) { TextArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <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; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private 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(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <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 => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <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 => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var 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 StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, 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() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <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() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <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() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <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 (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created 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() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. { get { var textArea = TextArea; // 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); return string.Empty; } return false; } if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea?.Document != null) { var offset = SelectionStart; var length = SelectionLength; } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> { get { var textArea = TextArea; if (textArea != null) return textArea.Caret.Offset; return 0; } set { var textArea = TextArea; if (textArea != null && textArea.Caret.Offset != value) textArea.Caret.Offset = value; } } { get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } } { get { var textArea = TextArea; if (textArea != null) { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; return textArea.Selection.SurroundingSegment.Offset; } return 0; } set => Select(value, SelectionLength); } /// </summary> public bool CanDelete { get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } } { get { var textArea = TextArea; if (textArea != null && !textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; return 0; } set => Select(SelectionStart, value); } /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> 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); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> 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> 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) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { 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 (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <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> public Encoding Encoding { get => 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(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Minor cleanup #123 https://github.com/icsharpcode/AvalonEdit/pull/123 <DFF> @@ -77,7 +77,7 @@ namespace AvaloniaEdit protected TextEditor(TextArea textArea, TextDocument document) { - TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); + this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); @@ -263,7 +263,8 @@ namespace AvaloniaEdit #endregion #region TextArea / ScrollViewer properties - + private readonly TextArea textArea; + protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); @@ -276,7 +277,7 @@ namespace AvaloniaEdit /// <summary> /// Gets the text area. /// </summary> - public TextArea TextArea { get; } + public TextArea TextArea => textArea; /// <summary> /// Gets the scroll viewer used by the text editor. @@ -314,7 +315,7 @@ namespace AvaloniaEdit { if (_colorizer != null) { - TextArea.TextView.LineTransformers.Remove(_colorizer); + textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } @@ -323,7 +324,7 @@ namespace AvaloniaEdit _colorizer = CreateColorizer(newValue); if (_colorizer != null) { - TextArea.TextView.LineTransformers.Insert(0, _colorizer); + textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } @@ -799,10 +800,9 @@ namespace AvaloniaEdit { get { - var textArea = TextArea; // 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) + if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } @@ -811,7 +811,7 @@ namespace AvaloniaEdit if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; - if (textArea?.Document != null) + if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; @@ -829,16 +829,11 @@ namespace AvaloniaEdit { get { - var textArea = TextArea; - if (textArea != null) - return textArea.Caret.Offset; - return 0; + return textArea.Caret.Offset; } set { - var textArea = TextArea; - if (textArea != null && textArea.Caret.Offset != value) - textArea.Caret.Offset = value; + textArea.Caret.Offset = value; } } @@ -849,14 +844,10 @@ namespace AvaloniaEdit { get { - var textArea = TextArea; - if (textArea != null) - { - if (textArea.Selection.IsEmpty) - return textArea.Caret.Offset; + if (textArea.Selection.IsEmpty) + return textArea.Caret.Offset; + else return textArea.Selection.SurroundingSegment.Offset; - } - return 0; } set => Select(value, SelectionLength); } @@ -868,10 +859,10 @@ namespace AvaloniaEdit { get { - var textArea = TextArea; - if (textArea != null && !textArea.Selection.IsEmpty) + if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; - return 0; + else + return 0; } set => Select(SelectionStart, value); }
16
Minor cleanup #123
25
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10067336
<NME> TextEditor.cs <BEF> // 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 Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent { #region Constructors static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) protected TextEditor(TextArea textArea, TextDocument document) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => 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) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently used by the text editor. /// </summary> public TextEditorOptions Options { get => 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) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var 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. CaretOffset = 0; document.UndoStack.ClearAll(); } } #endregion #region TextArea / ScrollViewer properties protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea { get; } /// <summary> /// Gets the scroll viewer used by the text editor. #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { if (_colorizer != null) { TextArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } /// <summary> /// Gets the text area. _colorizer = CreateColorizer(newValue); if (_colorizer != null) { TextArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <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; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private 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(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <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 => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <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 => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var 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 StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, 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() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <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() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <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() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <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 (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created 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() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. { get { var textArea = TextArea; // 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); return string.Empty; } return false; } if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea?.Document != null) { var offset = SelectionStart; var length = SelectionLength; } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> { get { var textArea = TextArea; if (textArea != null) return textArea.Caret.Offset; return 0; } set { var textArea = TextArea; if (textArea != null && textArea.Caret.Offset != value) textArea.Caret.Offset = value; } } { get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } } { get { var textArea = TextArea; if (textArea != null) { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; return textArea.Selection.SurroundingSegment.Offset; } return 0; } set => Select(value, SelectionLength); } /// </summary> public bool CanDelete { get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } } { get { var textArea = TextArea; if (textArea != null && !textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; return 0; } set => Select(SelectionStart, value); } /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> 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); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> 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> 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) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { 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 (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <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> public Encoding Encoding { get => 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(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Minor cleanup #123 https://github.com/icsharpcode/AvalonEdit/pull/123 <DFF> @@ -77,7 +77,7 @@ namespace AvaloniaEdit protected TextEditor(TextArea textArea, TextDocument document) { - TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); + this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); @@ -263,7 +263,8 @@ namespace AvaloniaEdit #endregion #region TextArea / ScrollViewer properties - + private readonly TextArea textArea; + protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); @@ -276,7 +277,7 @@ namespace AvaloniaEdit /// <summary> /// Gets the text area. /// </summary> - public TextArea TextArea { get; } + public TextArea TextArea => textArea; /// <summary> /// Gets the scroll viewer used by the text editor. @@ -314,7 +315,7 @@ namespace AvaloniaEdit { if (_colorizer != null) { - TextArea.TextView.LineTransformers.Remove(_colorizer); + textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } @@ -323,7 +324,7 @@ namespace AvaloniaEdit _colorizer = CreateColorizer(newValue); if (_colorizer != null) { - TextArea.TextView.LineTransformers.Insert(0, _colorizer); + textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } @@ -799,10 +800,9 @@ namespace AvaloniaEdit { get { - var textArea = TextArea; // 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) + if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } @@ -811,7 +811,7 @@ namespace AvaloniaEdit if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; - if (textArea?.Document != null) + if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; @@ -829,16 +829,11 @@ namespace AvaloniaEdit { get { - var textArea = TextArea; - if (textArea != null) - return textArea.Caret.Offset; - return 0; + return textArea.Caret.Offset; } set { - var textArea = TextArea; - if (textArea != null && textArea.Caret.Offset != value) - textArea.Caret.Offset = value; + textArea.Caret.Offset = value; } } @@ -849,14 +844,10 @@ namespace AvaloniaEdit { get { - var textArea = TextArea; - if (textArea != null) - { - if (textArea.Selection.IsEmpty) - return textArea.Caret.Offset; + if (textArea.Selection.IsEmpty) + return textArea.Caret.Offset; + else return textArea.Selection.SurroundingSegment.Offset; - } - return 0; } set => Select(value, SelectionLength); } @@ -868,10 +859,10 @@ namespace AvaloniaEdit { get { - var textArea = TextArea; - if (textArea != null && !textArea.Selection.IsEmpty) + if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; - return 0; + else + return 0; } set => Select(SelectionStart, value); }
16
Minor cleanup #123
25
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10067337
<NME> TextEditor.cs <BEF> // 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 Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent { #region Constructors static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) protected TextEditor(TextArea textArea, TextDocument document) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => 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) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently used by the text editor. /// </summary> public TextEditorOptions Options { get => 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) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var 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. CaretOffset = 0; document.UndoStack.ClearAll(); } } #endregion #region TextArea / ScrollViewer properties protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea { get; } /// <summary> /// Gets the scroll viewer used by the text editor. #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { if (_colorizer != null) { TextArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } /// <summary> /// Gets the text area. _colorizer = CreateColorizer(newValue); if (_colorizer != null) { TextArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <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; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private 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(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <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 => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <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 => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var 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 StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, 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() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <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() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <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() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <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 (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created 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() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. { get { var textArea = TextArea; // 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); return string.Empty; } return false; } if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea?.Document != null) { var offset = SelectionStart; var length = SelectionLength; } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> { get { var textArea = TextArea; if (textArea != null) return textArea.Caret.Offset; return 0; } set { var textArea = TextArea; if (textArea != null && textArea.Caret.Offset != value) textArea.Caret.Offset = value; } } { get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } } { get { var textArea = TextArea; if (textArea != null) { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; return textArea.Selection.SurroundingSegment.Offset; } return 0; } set => Select(value, SelectionLength); } /// </summary> public bool CanDelete { get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } } { get { var textArea = TextArea; if (textArea != null && !textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; return 0; } set => Select(SelectionStart, value); } /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> 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); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> 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> 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) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { 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 (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <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> public Encoding Encoding { get => 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(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Minor cleanup #123 https://github.com/icsharpcode/AvalonEdit/pull/123 <DFF> @@ -77,7 +77,7 @@ namespace AvaloniaEdit protected TextEditor(TextArea textArea, TextDocument document) { - TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); + this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); @@ -263,7 +263,8 @@ namespace AvaloniaEdit #endregion #region TextArea / ScrollViewer properties - + private readonly TextArea textArea; + protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); @@ -276,7 +277,7 @@ namespace AvaloniaEdit /// <summary> /// Gets the text area. /// </summary> - public TextArea TextArea { get; } + public TextArea TextArea => textArea; /// <summary> /// Gets the scroll viewer used by the text editor. @@ -314,7 +315,7 @@ namespace AvaloniaEdit { if (_colorizer != null) { - TextArea.TextView.LineTransformers.Remove(_colorizer); + textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } @@ -323,7 +324,7 @@ namespace AvaloniaEdit _colorizer = CreateColorizer(newValue); if (_colorizer != null) { - TextArea.TextView.LineTransformers.Insert(0, _colorizer); + textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } @@ -799,10 +800,9 @@ namespace AvaloniaEdit { get { - var textArea = TextArea; // 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) + if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } @@ -811,7 +811,7 @@ namespace AvaloniaEdit if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; - if (textArea?.Document != null) + if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; @@ -829,16 +829,11 @@ namespace AvaloniaEdit { get { - var textArea = TextArea; - if (textArea != null) - return textArea.Caret.Offset; - return 0; + return textArea.Caret.Offset; } set { - var textArea = TextArea; - if (textArea != null && textArea.Caret.Offset != value) - textArea.Caret.Offset = value; + textArea.Caret.Offset = value; } } @@ -849,14 +844,10 @@ namespace AvaloniaEdit { get { - var textArea = TextArea; - if (textArea != null) - { - if (textArea.Selection.IsEmpty) - return textArea.Caret.Offset; + if (textArea.Selection.IsEmpty) + return textArea.Caret.Offset; + else return textArea.Selection.SurroundingSegment.Offset; - } - return 0; } set => Select(value, SelectionLength); } @@ -868,10 +859,10 @@ namespace AvaloniaEdit { get { - var textArea = TextArea; - if (textArea != null && !textArea.Selection.IsEmpty) + if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; - return 0; + else + return 0; } set => Select(SelectionStart, value); }
16
Minor cleanup #123
25
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10067338
<NME> TextEditor.cs <BEF> // 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 Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent { #region Constructors static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) protected TextEditor(TextArea textArea, TextDocument document) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => 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) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently used by the text editor. /// </summary> public TextEditorOptions Options { get => 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) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var 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. CaretOffset = 0; document.UndoStack.ClearAll(); } } #endregion #region TextArea / ScrollViewer properties protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea { get; } /// <summary> /// Gets the scroll viewer used by the text editor. #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { if (_colorizer != null) { TextArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } /// <summary> /// Gets the text area. _colorizer = CreateColorizer(newValue); if (_colorizer != null) { TextArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <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; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private 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(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <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 => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <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 => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var 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 StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, 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() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <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() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <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() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <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 (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created 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() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. { get { var textArea = TextArea; // 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); return string.Empty; } return false; } if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea?.Document != null) { var offset = SelectionStart; var length = SelectionLength; } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> { get { var textArea = TextArea; if (textArea != null) return textArea.Caret.Offset; return 0; } set { var textArea = TextArea; if (textArea != null && textArea.Caret.Offset != value) textArea.Caret.Offset = value; } } { get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } } { get { var textArea = TextArea; if (textArea != null) { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; return textArea.Selection.SurroundingSegment.Offset; } return 0; } set => Select(value, SelectionLength); } /// </summary> public bool CanDelete { get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } } { get { var textArea = TextArea; if (textArea != null && !textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; return 0; } set => Select(SelectionStart, value); } /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> 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); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> 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> 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) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { 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 (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <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> public Encoding Encoding { get => 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(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Minor cleanup #123 https://github.com/icsharpcode/AvalonEdit/pull/123 <DFF> @@ -77,7 +77,7 @@ namespace AvaloniaEdit protected TextEditor(TextArea textArea, TextDocument document) { - TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); + this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); @@ -263,7 +263,8 @@ namespace AvaloniaEdit #endregion #region TextArea / ScrollViewer properties - + private readonly TextArea textArea; + protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); @@ -276,7 +277,7 @@ namespace AvaloniaEdit /// <summary> /// Gets the text area. /// </summary> - public TextArea TextArea { get; } + public TextArea TextArea => textArea; /// <summary> /// Gets the scroll viewer used by the text editor. @@ -314,7 +315,7 @@ namespace AvaloniaEdit { if (_colorizer != null) { - TextArea.TextView.LineTransformers.Remove(_colorizer); + textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } @@ -323,7 +324,7 @@ namespace AvaloniaEdit _colorizer = CreateColorizer(newValue); if (_colorizer != null) { - TextArea.TextView.LineTransformers.Insert(0, _colorizer); + textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } @@ -799,10 +800,9 @@ namespace AvaloniaEdit { get { - var textArea = TextArea; // 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) + if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } @@ -811,7 +811,7 @@ namespace AvaloniaEdit if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; - if (textArea?.Document != null) + if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; @@ -829,16 +829,11 @@ namespace AvaloniaEdit { get { - var textArea = TextArea; - if (textArea != null) - return textArea.Caret.Offset; - return 0; + return textArea.Caret.Offset; } set { - var textArea = TextArea; - if (textArea != null && textArea.Caret.Offset != value) - textArea.Caret.Offset = value; + textArea.Caret.Offset = value; } } @@ -849,14 +844,10 @@ namespace AvaloniaEdit { get { - var textArea = TextArea; - if (textArea != null) - { - if (textArea.Selection.IsEmpty) - return textArea.Caret.Offset; + if (textArea.Selection.IsEmpty) + return textArea.Caret.Offset; + else return textArea.Selection.SurroundingSegment.Offset; - } - return 0; } set => Select(value, SelectionLength); } @@ -868,10 +859,10 @@ namespace AvaloniaEdit { get { - var textArea = TextArea; - if (textArea != null && !textArea.Selection.IsEmpty) + if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; - return 0; + else + return 0; } set => Select(SelectionStart, value); }
16
Minor cleanup #123
25
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10067339
<NME> TextEditor.cs <BEF> // 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 Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent { #region Constructors static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) protected TextEditor(TextArea textArea, TextDocument document) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => 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) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently used by the text editor. /// </summary> public TextEditorOptions Options { get => 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) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var 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. CaretOffset = 0; document.UndoStack.ClearAll(); } } #endregion #region TextArea / ScrollViewer properties protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea { get; } /// <summary> /// Gets the scroll viewer used by the text editor. #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { if (_colorizer != null) { TextArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } /// <summary> /// Gets the text area. _colorizer = CreateColorizer(newValue); if (_colorizer != null) { TextArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <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; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private 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(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <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 => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <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 => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var 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 StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, 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() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <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() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <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() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <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 (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created 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() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. { get { var textArea = TextArea; // 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); return string.Empty; } return false; } if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea?.Document != null) { var offset = SelectionStart; var length = SelectionLength; } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> { get { var textArea = TextArea; if (textArea != null) return textArea.Caret.Offset; return 0; } set { var textArea = TextArea; if (textArea != null && textArea.Caret.Offset != value) textArea.Caret.Offset = value; } } { get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } } { get { var textArea = TextArea; if (textArea != null) { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; return textArea.Selection.SurroundingSegment.Offset; } return 0; } set => Select(value, SelectionLength); } /// </summary> public bool CanDelete { get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } } { get { var textArea = TextArea; if (textArea != null && !textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; return 0; } set => Select(SelectionStart, value); } /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> 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); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> 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> 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) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { 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 (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <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> public Encoding Encoding { get => 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(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Minor cleanup #123 https://github.com/icsharpcode/AvalonEdit/pull/123 <DFF> @@ -77,7 +77,7 @@ namespace AvaloniaEdit protected TextEditor(TextArea textArea, TextDocument document) { - TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); + this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); @@ -263,7 +263,8 @@ namespace AvaloniaEdit #endregion #region TextArea / ScrollViewer properties - + private readonly TextArea textArea; + protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); @@ -276,7 +277,7 @@ namespace AvaloniaEdit /// <summary> /// Gets the text area. /// </summary> - public TextArea TextArea { get; } + public TextArea TextArea => textArea; /// <summary> /// Gets the scroll viewer used by the text editor. @@ -314,7 +315,7 @@ namespace AvaloniaEdit { if (_colorizer != null) { - TextArea.TextView.LineTransformers.Remove(_colorizer); + textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } @@ -323,7 +324,7 @@ namespace AvaloniaEdit _colorizer = CreateColorizer(newValue); if (_colorizer != null) { - TextArea.TextView.LineTransformers.Insert(0, _colorizer); + textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } @@ -799,10 +800,9 @@ namespace AvaloniaEdit { get { - var textArea = TextArea; // 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) + if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } @@ -811,7 +811,7 @@ namespace AvaloniaEdit if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; - if (textArea?.Document != null) + if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; @@ -829,16 +829,11 @@ namespace AvaloniaEdit { get { - var textArea = TextArea; - if (textArea != null) - return textArea.Caret.Offset; - return 0; + return textArea.Caret.Offset; } set { - var textArea = TextArea; - if (textArea != null && textArea.Caret.Offset != value) - textArea.Caret.Offset = value; + textArea.Caret.Offset = value; } } @@ -849,14 +844,10 @@ namespace AvaloniaEdit { get { - var textArea = TextArea; - if (textArea != null) - { - if (textArea.Selection.IsEmpty) - return textArea.Caret.Offset; + if (textArea.Selection.IsEmpty) + return textArea.Caret.Offset; + else return textArea.Selection.SurroundingSegment.Offset; - } - return 0; } set => Select(value, SelectionLength); } @@ -868,10 +859,10 @@ namespace AvaloniaEdit { get { - var textArea = TextArea; - if (textArea != null && !textArea.Selection.IsEmpty) + if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; - return 0; + else + return 0; } set => Select(SelectionStart, value); }
16
Minor cleanup #123
25
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10067340
<NME> TextEditor.cs <BEF> // 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 Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent { #region Constructors static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) protected TextEditor(TextArea textArea, TextDocument document) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => 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) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently used by the text editor. /// </summary> public TextEditorOptions Options { get => 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) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var 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. CaretOffset = 0; document.UndoStack.ClearAll(); } } #endregion #region TextArea / ScrollViewer properties protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea { get; } /// <summary> /// Gets the scroll viewer used by the text editor. #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { if (_colorizer != null) { TextArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } /// <summary> /// Gets the text area. _colorizer = CreateColorizer(newValue); if (_colorizer != null) { TextArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <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; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private 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(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <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 => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <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 => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var 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 StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, 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() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <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() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <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() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <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 (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created 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() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. { get { var textArea = TextArea; // 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); return string.Empty; } return false; } if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea?.Document != null) { var offset = SelectionStart; var length = SelectionLength; } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> { get { var textArea = TextArea; if (textArea != null) return textArea.Caret.Offset; return 0; } set { var textArea = TextArea; if (textArea != null && textArea.Caret.Offset != value) textArea.Caret.Offset = value; } } { get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } } { get { var textArea = TextArea; if (textArea != null) { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; return textArea.Selection.SurroundingSegment.Offset; } return 0; } set => Select(value, SelectionLength); } /// </summary> public bool CanDelete { get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } } { get { var textArea = TextArea; if (textArea != null && !textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; return 0; } set => Select(SelectionStart, value); } /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> 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); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> 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> 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) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { 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 (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <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> public Encoding Encoding { get => 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(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Minor cleanup #123 https://github.com/icsharpcode/AvalonEdit/pull/123 <DFF> @@ -77,7 +77,7 @@ namespace AvaloniaEdit protected TextEditor(TextArea textArea, TextDocument document) { - TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); + this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); @@ -263,7 +263,8 @@ namespace AvaloniaEdit #endregion #region TextArea / ScrollViewer properties - + private readonly TextArea textArea; + protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); @@ -276,7 +277,7 @@ namespace AvaloniaEdit /// <summary> /// Gets the text area. /// </summary> - public TextArea TextArea { get; } + public TextArea TextArea => textArea; /// <summary> /// Gets the scroll viewer used by the text editor. @@ -314,7 +315,7 @@ namespace AvaloniaEdit { if (_colorizer != null) { - TextArea.TextView.LineTransformers.Remove(_colorizer); + textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } @@ -323,7 +324,7 @@ namespace AvaloniaEdit _colorizer = CreateColorizer(newValue); if (_colorizer != null) { - TextArea.TextView.LineTransformers.Insert(0, _colorizer); + textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } @@ -799,10 +800,9 @@ namespace AvaloniaEdit { get { - var textArea = TextArea; // 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) + if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } @@ -811,7 +811,7 @@ namespace AvaloniaEdit if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; - if (textArea?.Document != null) + if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; @@ -829,16 +829,11 @@ namespace AvaloniaEdit { get { - var textArea = TextArea; - if (textArea != null) - return textArea.Caret.Offset; - return 0; + return textArea.Caret.Offset; } set { - var textArea = TextArea; - if (textArea != null && textArea.Caret.Offset != value) - textArea.Caret.Offset = value; + textArea.Caret.Offset = value; } } @@ -849,14 +844,10 @@ namespace AvaloniaEdit { get { - var textArea = TextArea; - if (textArea != null) - { - if (textArea.Selection.IsEmpty) - return textArea.Caret.Offset; + if (textArea.Selection.IsEmpty) + return textArea.Caret.Offset; + else return textArea.Selection.SurroundingSegment.Offset; - } - return 0; } set => Select(value, SelectionLength); } @@ -868,10 +859,10 @@ namespace AvaloniaEdit { get { - var textArea = TextArea; - if (textArea != null && !textArea.Selection.IsEmpty) + if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; - return 0; + else + return 0; } set => Select(SelectionStart, value); }
16
Minor cleanup #123
25
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10067341
<NME> TextEditor.cs <BEF> // 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 Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent { #region Constructors static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) protected TextEditor(TextArea textArea, TextDocument document) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => 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) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently used by the text editor. /// </summary> public TextEditorOptions Options { get => 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) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var 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. CaretOffset = 0; document.UndoStack.ClearAll(); } } #endregion #region TextArea / ScrollViewer properties protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea { get; } /// <summary> /// Gets the scroll viewer used by the text editor. #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { if (_colorizer != null) { TextArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } /// <summary> /// Gets the text area. _colorizer = CreateColorizer(newValue); if (_colorizer != null) { TextArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <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; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private 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(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <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 => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <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 => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var 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 StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, 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() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <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() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <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() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <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 (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created 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() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. { get { var textArea = TextArea; // 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); return string.Empty; } return false; } if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea?.Document != null) { var offset = SelectionStart; var length = SelectionLength; } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> { get { var textArea = TextArea; if (textArea != null) return textArea.Caret.Offset; return 0; } set { var textArea = TextArea; if (textArea != null && textArea.Caret.Offset != value) textArea.Caret.Offset = value; } } { get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } } { get { var textArea = TextArea; if (textArea != null) { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; return textArea.Selection.SurroundingSegment.Offset; } return 0; } set => Select(value, SelectionLength); } /// </summary> public bool CanDelete { get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } } { get { var textArea = TextArea; if (textArea != null && !textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; return 0; } set => Select(SelectionStart, value); } /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> 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); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> 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> 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) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { 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 (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <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> public Encoding Encoding { get => 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(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Minor cleanup #123 https://github.com/icsharpcode/AvalonEdit/pull/123 <DFF> @@ -77,7 +77,7 @@ namespace AvaloniaEdit protected TextEditor(TextArea textArea, TextDocument document) { - TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); + this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); @@ -263,7 +263,8 @@ namespace AvaloniaEdit #endregion #region TextArea / ScrollViewer properties - + private readonly TextArea textArea; + protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); @@ -276,7 +277,7 @@ namespace AvaloniaEdit /// <summary> /// Gets the text area. /// </summary> - public TextArea TextArea { get; } + public TextArea TextArea => textArea; /// <summary> /// Gets the scroll viewer used by the text editor. @@ -314,7 +315,7 @@ namespace AvaloniaEdit { if (_colorizer != null) { - TextArea.TextView.LineTransformers.Remove(_colorizer); + textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } @@ -323,7 +324,7 @@ namespace AvaloniaEdit _colorizer = CreateColorizer(newValue); if (_colorizer != null) { - TextArea.TextView.LineTransformers.Insert(0, _colorizer); + textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } @@ -799,10 +800,9 @@ namespace AvaloniaEdit { get { - var textArea = TextArea; // 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) + if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } @@ -811,7 +811,7 @@ namespace AvaloniaEdit if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; - if (textArea?.Document != null) + if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; @@ -829,16 +829,11 @@ namespace AvaloniaEdit { get { - var textArea = TextArea; - if (textArea != null) - return textArea.Caret.Offset; - return 0; + return textArea.Caret.Offset; } set { - var textArea = TextArea; - if (textArea != null && textArea.Caret.Offset != value) - textArea.Caret.Offset = value; + textArea.Caret.Offset = value; } } @@ -849,14 +844,10 @@ namespace AvaloniaEdit { get { - var textArea = TextArea; - if (textArea != null) - { - if (textArea.Selection.IsEmpty) - return textArea.Caret.Offset; + if (textArea.Selection.IsEmpty) + return textArea.Caret.Offset; + else return textArea.Selection.SurroundingSegment.Offset; - } - return 0; } set => Select(value, SelectionLength); } @@ -868,10 +859,10 @@ namespace AvaloniaEdit { get { - var textArea = TextArea; - if (textArea != null && !textArea.Selection.IsEmpty) + if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; - return 0; + else + return 0; } set => Select(SelectionStart, value); }
16
Minor cleanup #123
25
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10067342
<NME> TextEditor.cs <BEF> // 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 Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent { #region Constructors static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) protected TextEditor(TextArea textArea, TextDocument document) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => 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) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently used by the text editor. /// </summary> public TextEditorOptions Options { get => 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) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var 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. CaretOffset = 0; document.UndoStack.ClearAll(); } } #endregion #region TextArea / ScrollViewer properties protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea { get; } /// <summary> /// Gets the scroll viewer used by the text editor. #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { if (_colorizer != null) { TextArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } /// <summary> /// Gets the text area. _colorizer = CreateColorizer(newValue); if (_colorizer != null) { TextArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <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; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private 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(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <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 => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <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 => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var 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 StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, 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() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <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() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <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() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <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 (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created 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() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. { get { var textArea = TextArea; // 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); return string.Empty; } return false; } if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea?.Document != null) { var offset = SelectionStart; var length = SelectionLength; } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> { get { var textArea = TextArea; if (textArea != null) return textArea.Caret.Offset; return 0; } set { var textArea = TextArea; if (textArea != null && textArea.Caret.Offset != value) textArea.Caret.Offset = value; } } { get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } } { get { var textArea = TextArea; if (textArea != null) { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; return textArea.Selection.SurroundingSegment.Offset; } return 0; } set => Select(value, SelectionLength); } /// </summary> public bool CanDelete { get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } } { get { var textArea = TextArea; if (textArea != null && !textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; return 0; } set => Select(SelectionStart, value); } /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> 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); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> 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> 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) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { 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 (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <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> public Encoding Encoding { get => 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(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Minor cleanup #123 https://github.com/icsharpcode/AvalonEdit/pull/123 <DFF> @@ -77,7 +77,7 @@ namespace AvaloniaEdit protected TextEditor(TextArea textArea, TextDocument document) { - TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); + this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); @@ -263,7 +263,8 @@ namespace AvaloniaEdit #endregion #region TextArea / ScrollViewer properties - + private readonly TextArea textArea; + protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); @@ -276,7 +277,7 @@ namespace AvaloniaEdit /// <summary> /// Gets the text area. /// </summary> - public TextArea TextArea { get; } + public TextArea TextArea => textArea; /// <summary> /// Gets the scroll viewer used by the text editor. @@ -314,7 +315,7 @@ namespace AvaloniaEdit { if (_colorizer != null) { - TextArea.TextView.LineTransformers.Remove(_colorizer); + textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } @@ -323,7 +324,7 @@ namespace AvaloniaEdit _colorizer = CreateColorizer(newValue); if (_colorizer != null) { - TextArea.TextView.LineTransformers.Insert(0, _colorizer); + textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } @@ -799,10 +800,9 @@ namespace AvaloniaEdit { get { - var textArea = TextArea; // 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) + if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } @@ -811,7 +811,7 @@ namespace AvaloniaEdit if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; - if (textArea?.Document != null) + if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; @@ -829,16 +829,11 @@ namespace AvaloniaEdit { get { - var textArea = TextArea; - if (textArea != null) - return textArea.Caret.Offset; - return 0; + return textArea.Caret.Offset; } set { - var textArea = TextArea; - if (textArea != null && textArea.Caret.Offset != value) - textArea.Caret.Offset = value; + textArea.Caret.Offset = value; } } @@ -849,14 +844,10 @@ namespace AvaloniaEdit { get { - var textArea = TextArea; - if (textArea != null) - { - if (textArea.Selection.IsEmpty) - return textArea.Caret.Offset; + if (textArea.Selection.IsEmpty) + return textArea.Caret.Offset; + else return textArea.Selection.SurroundingSegment.Offset; - } - return 0; } set => Select(value, SelectionLength); } @@ -868,10 +859,10 @@ namespace AvaloniaEdit { get { - var textArea = TextArea; - if (textArea != null && !textArea.Selection.IsEmpty) + if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; - return 0; + else + return 0; } set => Select(SelectionStart, value); }
16
Minor cleanup #123
25
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10067343
<NME> TextEditor.cs <BEF> // 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 Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent { #region Constructors static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) protected TextEditor(TextArea textArea, TextDocument document) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => 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) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently used by the text editor. /// </summary> public TextEditorOptions Options { get => 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) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var 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. CaretOffset = 0; document.UndoStack.ClearAll(); } } #endregion #region TextArea / ScrollViewer properties protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea { get; } /// <summary> /// Gets the scroll viewer used by the text editor. #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { if (_colorizer != null) { TextArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } /// <summary> /// Gets the text area. _colorizer = CreateColorizer(newValue); if (_colorizer != null) { TextArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <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; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private 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(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <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 => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <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 => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var 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 StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, 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() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <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() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <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() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <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 (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created 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() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. { get { var textArea = TextArea; // 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); return string.Empty; } return false; } if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea?.Document != null) { var offset = SelectionStart; var length = SelectionLength; } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> { get { var textArea = TextArea; if (textArea != null) return textArea.Caret.Offset; return 0; } set { var textArea = TextArea; if (textArea != null && textArea.Caret.Offset != value) textArea.Caret.Offset = value; } } { get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } } { get { var textArea = TextArea; if (textArea != null) { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; return textArea.Selection.SurroundingSegment.Offset; } return 0; } set => Select(value, SelectionLength); } /// </summary> public bool CanDelete { get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } } { get { var textArea = TextArea; if (textArea != null && !textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; return 0; } set => Select(SelectionStart, value); } /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> 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); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> 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> 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) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { 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 (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <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> public Encoding Encoding { get => 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(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Minor cleanup #123 https://github.com/icsharpcode/AvalonEdit/pull/123 <DFF> @@ -77,7 +77,7 @@ namespace AvaloniaEdit protected TextEditor(TextArea textArea, TextDocument document) { - TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); + this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); @@ -263,7 +263,8 @@ namespace AvaloniaEdit #endregion #region TextArea / ScrollViewer properties - + private readonly TextArea textArea; + protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); @@ -276,7 +277,7 @@ namespace AvaloniaEdit /// <summary> /// Gets the text area. /// </summary> - public TextArea TextArea { get; } + public TextArea TextArea => textArea; /// <summary> /// Gets the scroll viewer used by the text editor. @@ -314,7 +315,7 @@ namespace AvaloniaEdit { if (_colorizer != null) { - TextArea.TextView.LineTransformers.Remove(_colorizer); + textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } @@ -323,7 +324,7 @@ namespace AvaloniaEdit _colorizer = CreateColorizer(newValue); if (_colorizer != null) { - TextArea.TextView.LineTransformers.Insert(0, _colorizer); + textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } @@ -799,10 +800,9 @@ namespace AvaloniaEdit { get { - var textArea = TextArea; // 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) + if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } @@ -811,7 +811,7 @@ namespace AvaloniaEdit if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; - if (textArea?.Document != null) + if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; @@ -829,16 +829,11 @@ namespace AvaloniaEdit { get { - var textArea = TextArea; - if (textArea != null) - return textArea.Caret.Offset; - return 0; + return textArea.Caret.Offset; } set { - var textArea = TextArea; - if (textArea != null && textArea.Caret.Offset != value) - textArea.Caret.Offset = value; + textArea.Caret.Offset = value; } } @@ -849,14 +844,10 @@ namespace AvaloniaEdit { get { - var textArea = TextArea; - if (textArea != null) - { - if (textArea.Selection.IsEmpty) - return textArea.Caret.Offset; + if (textArea.Selection.IsEmpty) + return textArea.Caret.Offset; + else return textArea.Selection.SurroundingSegment.Offset; - } - return 0; } set => Select(value, SelectionLength); } @@ -868,10 +859,10 @@ namespace AvaloniaEdit { get { - var textArea = TextArea; - if (textArea != null && !textArea.Selection.IsEmpty) + if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; - return 0; + else + return 0; } set => Select(SelectionStart, value); }
16
Minor cleanup #123
25
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10067344
<NME> TextEditor.cs <BEF> // 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 Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent { #region Constructors static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) protected TextEditor(TextArea textArea, TextDocument document) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => 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) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently used by the text editor. /// </summary> public TextEditorOptions Options { get => 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) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var 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. CaretOffset = 0; document.UndoStack.ClearAll(); } } #endregion #region TextArea / ScrollViewer properties protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea { get; } /// <summary> /// Gets the scroll viewer used by the text editor. #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { if (_colorizer != null) { TextArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } /// <summary> /// Gets the text area. _colorizer = CreateColorizer(newValue); if (_colorizer != null) { TextArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <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; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private 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(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <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 => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <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 => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var 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 StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, 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() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <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() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <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() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <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 (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created 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() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. { get { var textArea = TextArea; // 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); return string.Empty; } return false; } if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea?.Document != null) { var offset = SelectionStart; var length = SelectionLength; } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> { get { var textArea = TextArea; if (textArea != null) return textArea.Caret.Offset; return 0; } set { var textArea = TextArea; if (textArea != null && textArea.Caret.Offset != value) textArea.Caret.Offset = value; } } { get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } } { get { var textArea = TextArea; if (textArea != null) { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; return textArea.Selection.SurroundingSegment.Offset; } return 0; } set => Select(value, SelectionLength); } /// </summary> public bool CanDelete { get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } } { get { var textArea = TextArea; if (textArea != null && !textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; return 0; } set => Select(SelectionStart, value); } /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> 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); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> 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> 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) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { 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 (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <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> public Encoding Encoding { get => 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(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Minor cleanup #123 https://github.com/icsharpcode/AvalonEdit/pull/123 <DFF> @@ -77,7 +77,7 @@ namespace AvaloniaEdit protected TextEditor(TextArea textArea, TextDocument document) { - TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); + this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); @@ -263,7 +263,8 @@ namespace AvaloniaEdit #endregion #region TextArea / ScrollViewer properties - + private readonly TextArea textArea; + protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); @@ -276,7 +277,7 @@ namespace AvaloniaEdit /// <summary> /// Gets the text area. /// </summary> - public TextArea TextArea { get; } + public TextArea TextArea => textArea; /// <summary> /// Gets the scroll viewer used by the text editor. @@ -314,7 +315,7 @@ namespace AvaloniaEdit { if (_colorizer != null) { - TextArea.TextView.LineTransformers.Remove(_colorizer); + textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } @@ -323,7 +324,7 @@ namespace AvaloniaEdit _colorizer = CreateColorizer(newValue); if (_colorizer != null) { - TextArea.TextView.LineTransformers.Insert(0, _colorizer); + textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } @@ -799,10 +800,9 @@ namespace AvaloniaEdit { get { - var textArea = TextArea; // 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) + if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } @@ -811,7 +811,7 @@ namespace AvaloniaEdit if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; - if (textArea?.Document != null) + if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; @@ -829,16 +829,11 @@ namespace AvaloniaEdit { get { - var textArea = TextArea; - if (textArea != null) - return textArea.Caret.Offset; - return 0; + return textArea.Caret.Offset; } set { - var textArea = TextArea; - if (textArea != null && textArea.Caret.Offset != value) - textArea.Caret.Offset = value; + textArea.Caret.Offset = value; } } @@ -849,14 +844,10 @@ namespace AvaloniaEdit { get { - var textArea = TextArea; - if (textArea != null) - { - if (textArea.Selection.IsEmpty) - return textArea.Caret.Offset; + if (textArea.Selection.IsEmpty) + return textArea.Caret.Offset; + else return textArea.Selection.SurroundingSegment.Offset; - } - return 0; } set => Select(value, SelectionLength); } @@ -868,10 +859,10 @@ namespace AvaloniaEdit { get { - var textArea = TextArea; - if (textArea != null && !textArea.Selection.IsEmpty) + if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; - return 0; + else + return 0; } set => Select(SelectionStart, value); }
16
Minor cleanup #123
25
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10067345
<NME> TextEditor.cs <BEF> // 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 Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent { #region Constructors static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) protected TextEditor(TextArea textArea, TextDocument document) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => 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) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently used by the text editor. /// </summary> public TextEditorOptions Options { get => 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) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var 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. CaretOffset = 0; document.UndoStack.ClearAll(); } } #endregion #region TextArea / ScrollViewer properties protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea { get; } /// <summary> /// Gets the scroll viewer used by the text editor. #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { if (_colorizer != null) { TextArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } /// <summary> /// Gets the text area. _colorizer = CreateColorizer(newValue); if (_colorizer != null) { TextArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <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; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private 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(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <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 => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <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 => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var 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 StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, 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() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <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() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <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() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <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 (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created 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() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. { get { var textArea = TextArea; // 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); return string.Empty; } return false; } if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea?.Document != null) { var offset = SelectionStart; var length = SelectionLength; } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> { get { var textArea = TextArea; if (textArea != null) return textArea.Caret.Offset; return 0; } set { var textArea = TextArea; if (textArea != null && textArea.Caret.Offset != value) textArea.Caret.Offset = value; } } { get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } } { get { var textArea = TextArea; if (textArea != null) { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; return textArea.Selection.SurroundingSegment.Offset; } return 0; } set => Select(value, SelectionLength); } /// </summary> public bool CanDelete { get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } } { get { var textArea = TextArea; if (textArea != null && !textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; return 0; } set => Select(SelectionStart, value); } /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> 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); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> 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> 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) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { 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 (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <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> public Encoding Encoding { get => 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(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Minor cleanup #123 https://github.com/icsharpcode/AvalonEdit/pull/123 <DFF> @@ -77,7 +77,7 @@ namespace AvaloniaEdit protected TextEditor(TextArea textArea, TextDocument document) { - TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); + this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); @@ -263,7 +263,8 @@ namespace AvaloniaEdit #endregion #region TextArea / ScrollViewer properties - + private readonly TextArea textArea; + protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); @@ -276,7 +277,7 @@ namespace AvaloniaEdit /// <summary> /// Gets the text area. /// </summary> - public TextArea TextArea { get; } + public TextArea TextArea => textArea; /// <summary> /// Gets the scroll viewer used by the text editor. @@ -314,7 +315,7 @@ namespace AvaloniaEdit { if (_colorizer != null) { - TextArea.TextView.LineTransformers.Remove(_colorizer); + textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } @@ -323,7 +324,7 @@ namespace AvaloniaEdit _colorizer = CreateColorizer(newValue); if (_colorizer != null) { - TextArea.TextView.LineTransformers.Insert(0, _colorizer); + textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } @@ -799,10 +800,9 @@ namespace AvaloniaEdit { get { - var textArea = TextArea; // 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) + if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } @@ -811,7 +811,7 @@ namespace AvaloniaEdit if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; - if (textArea?.Document != null) + if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; @@ -829,16 +829,11 @@ namespace AvaloniaEdit { get { - var textArea = TextArea; - if (textArea != null) - return textArea.Caret.Offset; - return 0; + return textArea.Caret.Offset; } set { - var textArea = TextArea; - if (textArea != null && textArea.Caret.Offset != value) - textArea.Caret.Offset = value; + textArea.Caret.Offset = value; } } @@ -849,14 +844,10 @@ namespace AvaloniaEdit { get { - var textArea = TextArea; - if (textArea != null) - { - if (textArea.Selection.IsEmpty) - return textArea.Caret.Offset; + if (textArea.Selection.IsEmpty) + return textArea.Caret.Offset; + else return textArea.Selection.SurroundingSegment.Offset; - } - return 0; } set => Select(value, SelectionLength); } @@ -868,10 +859,10 @@ namespace AvaloniaEdit { get { - var textArea = TextArea; - if (textArea != null && !textArea.Selection.IsEmpty) + if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; - return 0; + else + return 0; } set => Select(SelectionStart, value); }
16
Minor cleanup #123
25
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10067346
<NME> TextEditor.cs <BEF> // 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 Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent { #region Constructors static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) protected TextEditor(TextArea textArea, TextDocument document) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => 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) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently used by the text editor. /// </summary> public TextEditorOptions Options { get => 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) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var 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. CaretOffset = 0; document.UndoStack.ClearAll(); } } #endregion #region TextArea / ScrollViewer properties protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea { get; } /// <summary> /// Gets the scroll viewer used by the text editor. #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { if (_colorizer != null) { TextArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } /// <summary> /// Gets the text area. _colorizer = CreateColorizer(newValue); if (_colorizer != null) { TextArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <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; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private 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(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <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 => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <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 => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var 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 StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, 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() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <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() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <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() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <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 (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created 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() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. { get { var textArea = TextArea; // 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); return string.Empty; } return false; } if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea?.Document != null) { var offset = SelectionStart; var length = SelectionLength; } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> { get { var textArea = TextArea; if (textArea != null) return textArea.Caret.Offset; return 0; } set { var textArea = TextArea; if (textArea != null && textArea.Caret.Offset != value) textArea.Caret.Offset = value; } } { get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } } { get { var textArea = TextArea; if (textArea != null) { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; return textArea.Selection.SurroundingSegment.Offset; } return 0; } set => Select(value, SelectionLength); } /// </summary> public bool CanDelete { get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } } { get { var textArea = TextArea; if (textArea != null && !textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; return 0; } set => Select(SelectionStart, value); } /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> 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); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> 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> 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) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { 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 (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <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> public Encoding Encoding { get => 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(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Minor cleanup #123 https://github.com/icsharpcode/AvalonEdit/pull/123 <DFF> @@ -77,7 +77,7 @@ namespace AvaloniaEdit protected TextEditor(TextArea textArea, TextDocument document) { - TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); + this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); @@ -263,7 +263,8 @@ namespace AvaloniaEdit #endregion #region TextArea / ScrollViewer properties - + private readonly TextArea textArea; + protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); @@ -276,7 +277,7 @@ namespace AvaloniaEdit /// <summary> /// Gets the text area. /// </summary> - public TextArea TextArea { get; } + public TextArea TextArea => textArea; /// <summary> /// Gets the scroll viewer used by the text editor. @@ -314,7 +315,7 @@ namespace AvaloniaEdit { if (_colorizer != null) { - TextArea.TextView.LineTransformers.Remove(_colorizer); + textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } @@ -323,7 +324,7 @@ namespace AvaloniaEdit _colorizer = CreateColorizer(newValue); if (_colorizer != null) { - TextArea.TextView.LineTransformers.Insert(0, _colorizer); + textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } @@ -799,10 +800,9 @@ namespace AvaloniaEdit { get { - var textArea = TextArea; // 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) + if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } @@ -811,7 +811,7 @@ namespace AvaloniaEdit if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; - if (textArea?.Document != null) + if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; @@ -829,16 +829,11 @@ namespace AvaloniaEdit { get { - var textArea = TextArea; - if (textArea != null) - return textArea.Caret.Offset; - return 0; + return textArea.Caret.Offset; } set { - var textArea = TextArea; - if (textArea != null && textArea.Caret.Offset != value) - textArea.Caret.Offset = value; + textArea.Caret.Offset = value; } } @@ -849,14 +844,10 @@ namespace AvaloniaEdit { get { - var textArea = TextArea; - if (textArea != null) - { - if (textArea.Selection.IsEmpty) - return textArea.Caret.Offset; + if (textArea.Selection.IsEmpty) + return textArea.Caret.Offset; + else return textArea.Selection.SurroundingSegment.Offset; - } - return 0; } set => Select(value, SelectionLength); } @@ -868,10 +859,10 @@ namespace AvaloniaEdit { get { - var textArea = TextArea; - if (textArea != null && !textArea.Selection.IsEmpty) + if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; - return 0; + else + return 0; } set => Select(SelectionStart, value); }
16
Minor cleanup #123
25
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10067347
<NME> TextEditor.cs <BEF> // 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 Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent { #region Constructors static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) protected TextEditor(TextArea textArea, TextDocument document) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => 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) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently used by the text editor. /// </summary> public TextEditorOptions Options { get => 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) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var 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. CaretOffset = 0; document.UndoStack.ClearAll(); } } #endregion #region TextArea / ScrollViewer properties protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea { get; } /// <summary> /// Gets the scroll viewer used by the text editor. #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { if (_colorizer != null) { TextArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } /// <summary> /// Gets the text area. _colorizer = CreateColorizer(newValue); if (_colorizer != null) { TextArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <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; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private 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(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <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 => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <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 => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var 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 StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, 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() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <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() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <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() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <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 (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created 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() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. { get { var textArea = TextArea; // 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); return string.Empty; } return false; } if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea?.Document != null) { var offset = SelectionStart; var length = SelectionLength; } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> { get { var textArea = TextArea; if (textArea != null) return textArea.Caret.Offset; return 0; } set { var textArea = TextArea; if (textArea != null && textArea.Caret.Offset != value) textArea.Caret.Offset = value; } } { get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } } { get { var textArea = TextArea; if (textArea != null) { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; return textArea.Selection.SurroundingSegment.Offset; } return 0; } set => Select(value, SelectionLength); } /// </summary> public bool CanDelete { get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } } { get { var textArea = TextArea; if (textArea != null && !textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; return 0; } set => Select(SelectionStart, value); } /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> 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); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> 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> 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) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { 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 (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <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> public Encoding Encoding { get => 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(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Minor cleanup #123 https://github.com/icsharpcode/AvalonEdit/pull/123 <DFF> @@ -77,7 +77,7 @@ namespace AvaloniaEdit protected TextEditor(TextArea textArea, TextDocument document) { - TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); + this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); @@ -263,7 +263,8 @@ namespace AvaloniaEdit #endregion #region TextArea / ScrollViewer properties - + private readonly TextArea textArea; + protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); @@ -276,7 +277,7 @@ namespace AvaloniaEdit /// <summary> /// Gets the text area. /// </summary> - public TextArea TextArea { get; } + public TextArea TextArea => textArea; /// <summary> /// Gets the scroll viewer used by the text editor. @@ -314,7 +315,7 @@ namespace AvaloniaEdit { if (_colorizer != null) { - TextArea.TextView.LineTransformers.Remove(_colorizer); + textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } @@ -323,7 +324,7 @@ namespace AvaloniaEdit _colorizer = CreateColorizer(newValue); if (_colorizer != null) { - TextArea.TextView.LineTransformers.Insert(0, _colorizer); + textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } @@ -799,10 +800,9 @@ namespace AvaloniaEdit { get { - var textArea = TextArea; // 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) + if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } @@ -811,7 +811,7 @@ namespace AvaloniaEdit if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; - if (textArea?.Document != null) + if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; @@ -829,16 +829,11 @@ namespace AvaloniaEdit { get { - var textArea = TextArea; - if (textArea != null) - return textArea.Caret.Offset; - return 0; + return textArea.Caret.Offset; } set { - var textArea = TextArea; - if (textArea != null && textArea.Caret.Offset != value) - textArea.Caret.Offset = value; + textArea.Caret.Offset = value; } } @@ -849,14 +844,10 @@ namespace AvaloniaEdit { get { - var textArea = TextArea; - if (textArea != null) - { - if (textArea.Selection.IsEmpty) - return textArea.Caret.Offset; + if (textArea.Selection.IsEmpty) + return textArea.Caret.Offset; + else return textArea.Selection.SurroundingSegment.Offset; - } - return 0; } set => Select(value, SelectionLength); } @@ -868,10 +859,10 @@ namespace AvaloniaEdit { get { - var textArea = TextArea; - if (textArea != null && !textArea.Selection.IsEmpty) + if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; - return 0; + else + return 0; } set => Select(SelectionStart, value); }
16
Minor cleanup #123
25
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10067348
<NME> TextEditor.cs <BEF> // 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 Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent { #region Constructors static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) protected TextEditor(TextArea textArea, TextDocument document) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => 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) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently used by the text editor. /// </summary> public TextEditorOptions Options { get => 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) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var 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. CaretOffset = 0; document.UndoStack.ClearAll(); } } #endregion #region TextArea / ScrollViewer properties protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea { get; } /// <summary> /// Gets the scroll viewer used by the text editor. #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { if (_colorizer != null) { TextArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } /// <summary> /// Gets the text area. _colorizer = CreateColorizer(newValue); if (_colorizer != null) { TextArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <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; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private 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(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <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 => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <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 => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var 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 StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, 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() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <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() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <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() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <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 (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created 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() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. { get { var textArea = TextArea; // 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); return string.Empty; } return false; } if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea?.Document != null) { var offset = SelectionStart; var length = SelectionLength; } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> { get { var textArea = TextArea; if (textArea != null) return textArea.Caret.Offset; return 0; } set { var textArea = TextArea; if (textArea != null && textArea.Caret.Offset != value) textArea.Caret.Offset = value; } } { get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } } { get { var textArea = TextArea; if (textArea != null) { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; return textArea.Selection.SurroundingSegment.Offset; } return 0; } set => Select(value, SelectionLength); } /// </summary> public bool CanDelete { get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } } { get { var textArea = TextArea; if (textArea != null && !textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; return 0; } set => Select(SelectionStart, value); } /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> 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); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> 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> 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) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { 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 (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <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> public Encoding Encoding { get => 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(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Minor cleanup #123 https://github.com/icsharpcode/AvalonEdit/pull/123 <DFF> @@ -77,7 +77,7 @@ namespace AvaloniaEdit protected TextEditor(TextArea textArea, TextDocument document) { - TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); + this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); @@ -263,7 +263,8 @@ namespace AvaloniaEdit #endregion #region TextArea / ScrollViewer properties - + private readonly TextArea textArea; + protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); @@ -276,7 +277,7 @@ namespace AvaloniaEdit /// <summary> /// Gets the text area. /// </summary> - public TextArea TextArea { get; } + public TextArea TextArea => textArea; /// <summary> /// Gets the scroll viewer used by the text editor. @@ -314,7 +315,7 @@ namespace AvaloniaEdit { if (_colorizer != null) { - TextArea.TextView.LineTransformers.Remove(_colorizer); + textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } @@ -323,7 +324,7 @@ namespace AvaloniaEdit _colorizer = CreateColorizer(newValue); if (_colorizer != null) { - TextArea.TextView.LineTransformers.Insert(0, _colorizer); + textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } @@ -799,10 +800,9 @@ namespace AvaloniaEdit { get { - var textArea = TextArea; // 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) + if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } @@ -811,7 +811,7 @@ namespace AvaloniaEdit if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; - if (textArea?.Document != null) + if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; @@ -829,16 +829,11 @@ namespace AvaloniaEdit { get { - var textArea = TextArea; - if (textArea != null) - return textArea.Caret.Offset; - return 0; + return textArea.Caret.Offset; } set { - var textArea = TextArea; - if (textArea != null && textArea.Caret.Offset != value) - textArea.Caret.Offset = value; + textArea.Caret.Offset = value; } } @@ -849,14 +844,10 @@ namespace AvaloniaEdit { get { - var textArea = TextArea; - if (textArea != null) - { - if (textArea.Selection.IsEmpty) - return textArea.Caret.Offset; + if (textArea.Selection.IsEmpty) + return textArea.Caret.Offset; + else return textArea.Selection.SurroundingSegment.Offset; - } - return 0; } set => Select(value, SelectionLength); } @@ -868,10 +859,10 @@ namespace AvaloniaEdit { get { - var textArea = TextArea; - if (textArea != null && !textArea.Selection.IsEmpty) + if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; - return 0; + else + return 0; } set => Select(SelectionStart, value); }
16
Minor cleanup #123
25
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10067349
<NME> TextEditor.cs <BEF> // 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 Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent { #region Constructors static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) protected TextEditor(TextArea textArea, TextDocument document) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => 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) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently used by the text editor. /// </summary> public TextEditorOptions Options { get => 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) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var 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. CaretOffset = 0; document.UndoStack.ClearAll(); } } #endregion #region TextArea / ScrollViewer properties protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea { get; } /// <summary> /// Gets the scroll viewer used by the text editor. #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { if (_colorizer != null) { TextArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } /// <summary> /// Gets the text area. _colorizer = CreateColorizer(newValue); if (_colorizer != null) { TextArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <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; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private 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(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <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 => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <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 => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var 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 StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, 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() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <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() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <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() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <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 (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created 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() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. { get { var textArea = TextArea; // 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); return string.Empty; } return false; } if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea?.Document != null) { var offset = SelectionStart; var length = SelectionLength; } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> { get { var textArea = TextArea; if (textArea != null) return textArea.Caret.Offset; return 0; } set { var textArea = TextArea; if (textArea != null && textArea.Caret.Offset != value) textArea.Caret.Offset = value; } } { get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } } { get { var textArea = TextArea; if (textArea != null) { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; return textArea.Selection.SurroundingSegment.Offset; } return 0; } set => Select(value, SelectionLength); } /// </summary> public bool CanDelete { get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } } { get { var textArea = TextArea; if (textArea != null && !textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; return 0; } set => Select(SelectionStart, value); } /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> 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); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> 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> 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) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { 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 (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <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> public Encoding Encoding { get => 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(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Minor cleanup #123 https://github.com/icsharpcode/AvalonEdit/pull/123 <DFF> @@ -77,7 +77,7 @@ namespace AvaloniaEdit protected TextEditor(TextArea textArea, TextDocument document) { - TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); + this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); @@ -263,7 +263,8 @@ namespace AvaloniaEdit #endregion #region TextArea / ScrollViewer properties - + private readonly TextArea textArea; + protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); @@ -276,7 +277,7 @@ namespace AvaloniaEdit /// <summary> /// Gets the text area. /// </summary> - public TextArea TextArea { get; } + public TextArea TextArea => textArea; /// <summary> /// Gets the scroll viewer used by the text editor. @@ -314,7 +315,7 @@ namespace AvaloniaEdit { if (_colorizer != null) { - TextArea.TextView.LineTransformers.Remove(_colorizer); + textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } @@ -323,7 +324,7 @@ namespace AvaloniaEdit _colorizer = CreateColorizer(newValue); if (_colorizer != null) { - TextArea.TextView.LineTransformers.Insert(0, _colorizer); + textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } @@ -799,10 +800,9 @@ namespace AvaloniaEdit { get { - var textArea = TextArea; // 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) + if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } @@ -811,7 +811,7 @@ namespace AvaloniaEdit if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; - if (textArea?.Document != null) + if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; @@ -829,16 +829,11 @@ namespace AvaloniaEdit { get { - var textArea = TextArea; - if (textArea != null) - return textArea.Caret.Offset; - return 0; + return textArea.Caret.Offset; } set { - var textArea = TextArea; - if (textArea != null && textArea.Caret.Offset != value) - textArea.Caret.Offset = value; + textArea.Caret.Offset = value; } } @@ -849,14 +844,10 @@ namespace AvaloniaEdit { get { - var textArea = TextArea; - if (textArea != null) - { - if (textArea.Selection.IsEmpty) - return textArea.Caret.Offset; + if (textArea.Selection.IsEmpty) + return textArea.Caret.Offset; + else return textArea.Selection.SurroundingSegment.Offset; - } - return 0; } set => Select(value, SelectionLength); } @@ -868,10 +859,10 @@ namespace AvaloniaEdit { get { - var textArea = TextArea; - if (textArea != null && !textArea.Selection.IsEmpty) + if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; - return 0; + else + return 0; } set => Select(SelectionStart, value); }
16
Minor cleanup #123
25
.cs
cs
mit
AvaloniaUI/AvaloniaEdit