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
|
---|---|---|---|---|---|---|---|---|
10057650 | <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;
using System.Threading.Tasks;
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()
{
// TODO ApplicationCommands.Delete gets called, but never editing commands.Delete (since porting to avalonia.)
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.CharRight), CanDelete);
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.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);
//textArea.RaiseEvent(copyingEventArgs);
//if (copyingEventArgs.CommandCancelled)
// return false;
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void CanPaste(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset);
args.Handled = true;
}
}
private static async void OnPaste(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
textArea.Document.BeginUpdate();
string text = null;
try
{
text = await Application.Current.Clipboard.GetTextAsync();
}
catch (Exception)
{
textArea.Document.EndUpdate();
return;
}
if (text == null)
return;
text = GetTextToPaste(text, textArea);
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> Merge remote-tracking branch 'AvaloniaUI/master' into as-mods
<DFF> @@ -61,9 +61,7 @@ namespace AvaloniaEdit.Editing
}
static EditingCommandHandler()
- {
- // TODO ApplicationCommands.Delete gets called, but never editing commands.Delete (since porting to avalonia.)
- AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.CharRight), CanDelete);
+ {
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
| 1 | Merge remote-tracking branch 'AvaloniaUI/master' into as-mods | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057651 | <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;
using System.Threading.Tasks;
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()
{
// TODO ApplicationCommands.Delete gets called, but never editing commands.Delete (since porting to avalonia.)
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.CharRight), CanDelete);
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.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);
//textArea.RaiseEvent(copyingEventArgs);
//if (copyingEventArgs.CommandCancelled)
// return false;
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void CanPaste(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset);
args.Handled = true;
}
}
private static async void OnPaste(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
textArea.Document.BeginUpdate();
string text = null;
try
{
text = await Application.Current.Clipboard.GetTextAsync();
}
catch (Exception)
{
textArea.Document.EndUpdate();
return;
}
if (text == null)
return;
text = GetTextToPaste(text, textArea);
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> Merge remote-tracking branch 'AvaloniaUI/master' into as-mods
<DFF> @@ -61,9 +61,7 @@ namespace AvaloniaEdit.Editing
}
static EditingCommandHandler()
- {
- // TODO ApplicationCommands.Delete gets called, but never editing commands.Delete (since porting to avalonia.)
- AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.CharRight), CanDelete);
+ {
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
| 1 | Merge remote-tracking branch 'AvaloniaUI/master' into as-mods | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057652 | <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;
using System.Threading.Tasks;
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()
{
// TODO ApplicationCommands.Delete gets called, but never editing commands.Delete (since porting to avalonia.)
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.CharRight), CanDelete);
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.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);
//textArea.RaiseEvent(copyingEventArgs);
//if (copyingEventArgs.CommandCancelled)
// return false;
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void CanPaste(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset);
args.Handled = true;
}
}
private static async void OnPaste(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
textArea.Document.BeginUpdate();
string text = null;
try
{
text = await Application.Current.Clipboard.GetTextAsync();
}
catch (Exception)
{
textArea.Document.EndUpdate();
return;
}
if (text == null)
return;
text = GetTextToPaste(text, textArea);
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> Merge remote-tracking branch 'AvaloniaUI/master' into as-mods
<DFF> @@ -61,9 +61,7 @@ namespace AvaloniaEdit.Editing
}
static EditingCommandHandler()
- {
- // TODO ApplicationCommands.Delete gets called, but never editing commands.Delete (since porting to avalonia.)
- AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.CharRight), CanDelete);
+ {
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
| 1 | Merge remote-tracking branch 'AvaloniaUI/master' into as-mods | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057653 | <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;
using System.Threading.Tasks;
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()
{
// TODO ApplicationCommands.Delete gets called, but never editing commands.Delete (since porting to avalonia.)
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.CharRight), CanDelete);
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.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);
//textArea.RaiseEvent(copyingEventArgs);
//if (copyingEventArgs.CommandCancelled)
// return false;
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void CanPaste(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset);
args.Handled = true;
}
}
private static async void OnPaste(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
textArea.Document.BeginUpdate();
string text = null;
try
{
text = await Application.Current.Clipboard.GetTextAsync();
}
catch (Exception)
{
textArea.Document.EndUpdate();
return;
}
if (text == null)
return;
text = GetTextToPaste(text, textArea);
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> Merge remote-tracking branch 'AvaloniaUI/master' into as-mods
<DFF> @@ -61,9 +61,7 @@ namespace AvaloniaEdit.Editing
}
static EditingCommandHandler()
- {
- // TODO ApplicationCommands.Delete gets called, but never editing commands.Delete (since porting to avalonia.)
- AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.CharRight), CanDelete);
+ {
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
| 1 | Merge remote-tracking branch 'AvaloniaUI/master' into as-mods | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057654 | <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;
using System.Threading.Tasks;
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()
{
// TODO ApplicationCommands.Delete gets called, but never editing commands.Delete (since porting to avalonia.)
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.CharRight), CanDelete);
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.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);
//textArea.RaiseEvent(copyingEventArgs);
//if (copyingEventArgs.CommandCancelled)
// return false;
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void CanPaste(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset);
args.Handled = true;
}
}
private static async void OnPaste(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
textArea.Document.BeginUpdate();
string text = null;
try
{
text = await Application.Current.Clipboard.GetTextAsync();
}
catch (Exception)
{
textArea.Document.EndUpdate();
return;
}
if (text == null)
return;
text = GetTextToPaste(text, textArea);
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> Merge remote-tracking branch 'AvaloniaUI/master' into as-mods
<DFF> @@ -61,9 +61,7 @@ namespace AvaloniaEdit.Editing
}
static EditingCommandHandler()
- {
- // TODO ApplicationCommands.Delete gets called, but never editing commands.Delete (since porting to avalonia.)
- AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.CharRight), CanDelete);
+ {
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
| 1 | Merge remote-tracking branch 'AvaloniaUI/master' into as-mods | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057655 | <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;
using System.Threading.Tasks;
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()
{
// TODO ApplicationCommands.Delete gets called, but never editing commands.Delete (since porting to avalonia.)
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.CharRight), CanDelete);
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.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);
//textArea.RaiseEvent(copyingEventArgs);
//if (copyingEventArgs.CommandCancelled)
// return false;
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void CanPaste(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset);
args.Handled = true;
}
}
private static async void OnPaste(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
textArea.Document.BeginUpdate();
string text = null;
try
{
text = await Application.Current.Clipboard.GetTextAsync();
}
catch (Exception)
{
textArea.Document.EndUpdate();
return;
}
if (text == null)
return;
text = GetTextToPaste(text, textArea);
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> Merge remote-tracking branch 'AvaloniaUI/master' into as-mods
<DFF> @@ -61,9 +61,7 @@ namespace AvaloniaEdit.Editing
}
static EditingCommandHandler()
- {
- // TODO ApplicationCommands.Delete gets called, but never editing commands.Delete (since porting to avalonia.)
- AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.CharRight), CanDelete);
+ {
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
| 1 | Merge remote-tracking branch 'AvaloniaUI/master' into as-mods | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057656 | <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;
using System.Threading.Tasks;
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()
{
// TODO ApplicationCommands.Delete gets called, but never editing commands.Delete (since porting to avalonia.)
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.CharRight), CanDelete);
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.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);
//textArea.RaiseEvent(copyingEventArgs);
//if (copyingEventArgs.CommandCancelled)
// return false;
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void CanPaste(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset);
args.Handled = true;
}
}
private static async void OnPaste(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
textArea.Document.BeginUpdate();
string text = null;
try
{
text = await Application.Current.Clipboard.GetTextAsync();
}
catch (Exception)
{
textArea.Document.EndUpdate();
return;
}
if (text == null)
return;
text = GetTextToPaste(text, textArea);
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> Merge remote-tracking branch 'AvaloniaUI/master' into as-mods
<DFF> @@ -61,9 +61,7 @@ namespace AvaloniaEdit.Editing
}
static EditingCommandHandler()
- {
- // TODO ApplicationCommands.Delete gets called, but never editing commands.Delete (since porting to avalonia.)
- AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.CharRight), CanDelete);
+ {
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
| 1 | Merge remote-tracking branch 'AvaloniaUI/master' into as-mods | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057657 | <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;
using System.Threading.Tasks;
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()
{
// TODO ApplicationCommands.Delete gets called, but never editing commands.Delete (since porting to avalonia.)
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.CharRight), CanDelete);
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.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);
//textArea.RaiseEvent(copyingEventArgs);
//if (copyingEventArgs.CommandCancelled)
// return false;
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void CanPaste(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset);
args.Handled = true;
}
}
private static async void OnPaste(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
textArea.Document.BeginUpdate();
string text = null;
try
{
text = await Application.Current.Clipboard.GetTextAsync();
}
catch (Exception)
{
textArea.Document.EndUpdate();
return;
}
if (text == null)
return;
text = GetTextToPaste(text, textArea);
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> Merge remote-tracking branch 'AvaloniaUI/master' into as-mods
<DFF> @@ -61,9 +61,7 @@ namespace AvaloniaEdit.Editing
}
static EditingCommandHandler()
- {
- // TODO ApplicationCommands.Delete gets called, but never editing commands.Delete (since porting to avalonia.)
- AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.CharRight), CanDelete);
+ {
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
| 1 | Merge remote-tracking branch 'AvaloniaUI/master' into as-mods | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057658 | <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;
using System.Threading.Tasks;
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()
{
// TODO ApplicationCommands.Delete gets called, but never editing commands.Delete (since porting to avalonia.)
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.CharRight), CanDelete);
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.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);
//textArea.RaiseEvent(copyingEventArgs);
//if (copyingEventArgs.CommandCancelled)
// return false;
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void CanPaste(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset);
args.Handled = true;
}
}
private static async void OnPaste(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
textArea.Document.BeginUpdate();
string text = null;
try
{
text = await Application.Current.Clipboard.GetTextAsync();
}
catch (Exception)
{
textArea.Document.EndUpdate();
return;
}
if (text == null)
return;
text = GetTextToPaste(text, textArea);
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> Merge remote-tracking branch 'AvaloniaUI/master' into as-mods
<DFF> @@ -61,9 +61,7 @@ namespace AvaloniaEdit.Editing
}
static EditingCommandHandler()
- {
- // TODO ApplicationCommands.Delete gets called, but never editing commands.Delete (since porting to avalonia.)
- AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.CharRight), CanDelete);
+ {
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
| 1 | Merge remote-tracking branch 'AvaloniaUI/master' into as-mods | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057659 | <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;
using System.Threading.Tasks;
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()
{
// TODO ApplicationCommands.Delete gets called, but never editing commands.Delete (since porting to avalonia.)
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.CharRight), CanDelete);
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.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);
//textArea.RaiseEvent(copyingEventArgs);
//if (copyingEventArgs.CommandCancelled)
// return false;
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void CanPaste(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset);
args.Handled = true;
}
}
private static async void OnPaste(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
textArea.Document.BeginUpdate();
string text = null;
try
{
text = await Application.Current.Clipboard.GetTextAsync();
}
catch (Exception)
{
textArea.Document.EndUpdate();
return;
}
if (text == null)
return;
text = GetTextToPaste(text, textArea);
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> Merge remote-tracking branch 'AvaloniaUI/master' into as-mods
<DFF> @@ -61,9 +61,7 @@ namespace AvaloniaEdit.Editing
}
static EditingCommandHandler()
- {
- // TODO ApplicationCommands.Delete gets called, but never editing commands.Delete (since porting to avalonia.)
- AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.CharRight), CanDelete);
+ {
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
| 1 | Merge remote-tracking branch 'AvaloniaUI/master' into as-mods | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057660 | <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;
using System.Threading.Tasks;
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()
{
// TODO ApplicationCommands.Delete gets called, but never editing commands.Delete (since porting to avalonia.)
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.CharRight), CanDelete);
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.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);
//textArea.RaiseEvent(copyingEventArgs);
//if (copyingEventArgs.CommandCancelled)
// return false;
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void CanPaste(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset);
args.Handled = true;
}
}
private static async void OnPaste(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
textArea.Document.BeginUpdate();
string text = null;
try
{
text = await Application.Current.Clipboard.GetTextAsync();
}
catch (Exception)
{
textArea.Document.EndUpdate();
return;
}
if (text == null)
return;
text = GetTextToPaste(text, textArea);
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> Merge remote-tracking branch 'AvaloniaUI/master' into as-mods
<DFF> @@ -61,9 +61,7 @@ namespace AvaloniaEdit.Editing
}
static EditingCommandHandler()
- {
- // TODO ApplicationCommands.Delete gets called, but never editing commands.Delete (since porting to avalonia.)
- AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.CharRight), CanDelete);
+ {
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
| 1 | Merge remote-tracking branch 'AvaloniaUI/master' into as-mods | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057661 | <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;
using System.Threading.Tasks;
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()
{
// TODO ApplicationCommands.Delete gets called, but never editing commands.Delete (since porting to avalonia.)
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.CharRight), CanDelete);
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.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);
//textArea.RaiseEvent(copyingEventArgs);
//if (copyingEventArgs.CommandCancelled)
// return false;
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void CanPaste(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset);
args.Handled = true;
}
}
private static async void OnPaste(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
textArea.Document.BeginUpdate();
string text = null;
try
{
text = await Application.Current.Clipboard.GetTextAsync();
}
catch (Exception)
{
textArea.Document.EndUpdate();
return;
}
if (text == null)
return;
text = GetTextToPaste(text, textArea);
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> Merge remote-tracking branch 'AvaloniaUI/master' into as-mods
<DFF> @@ -61,9 +61,7 @@ namespace AvaloniaEdit.Editing
}
static EditingCommandHandler()
- {
- // TODO ApplicationCommands.Delete gets called, but never editing commands.Delete (since porting to avalonia.)
- AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.CharRight), CanDelete);
+ {
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
| 1 | Merge remote-tracking branch 'AvaloniaUI/master' into as-mods | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057662 | <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;
using System.Threading.Tasks;
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()
{
// TODO ApplicationCommands.Delete gets called, but never editing commands.Delete (since porting to avalonia.)
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.CharRight), CanDelete);
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.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);
//textArea.RaiseEvent(copyingEventArgs);
//if (copyingEventArgs.CommandCancelled)
// return false;
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void CanPaste(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset);
args.Handled = true;
}
}
private static async void OnPaste(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
textArea.Document.BeginUpdate();
string text = null;
try
{
text = await Application.Current.Clipboard.GetTextAsync();
}
catch (Exception)
{
textArea.Document.EndUpdate();
return;
}
if (text == null)
return;
text = GetTextToPaste(text, textArea);
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> Merge remote-tracking branch 'AvaloniaUI/master' into as-mods
<DFF> @@ -61,9 +61,7 @@ namespace AvaloniaEdit.Editing
}
static EditingCommandHandler()
- {
- // TODO ApplicationCommands.Delete gets called, but never editing commands.Delete (since porting to avalonia.)
- AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.CharRight), CanDelete);
+ {
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
| 1 | Merge remote-tracking branch 'AvaloniaUI/master' into as-mods | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057663 | <NME> SnippetBoundElement.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 AvaloniaEdit.Document;
namespace AvaloniaEdit.Snippets
{
/// <summary>
/// An element that binds to a <see cref="SnippetReplaceableTextElement"/> and displays the same text.
/// </summary>
public class SnippetBoundElement : SnippetElement
{
/// <summary>
/// Gets/Sets the target element.
/// </summary>
public SnippetReplaceableTextElement TargetElement { get; set; }
/// <summary>
/// Converts the text before copying it.
/// </summary>
public virtual string ConvertText(string input)
{
return input;
}
/// <inheritdoc/>
public override void Insert(InsertionContext context)
{
if (TargetElement != null)
{
var start = context.Document.CreateAnchor(context.InsertionPosition);
start.MovementType = AnchorMovementType.BeforeInsertion;
start.SurviveDeletion = true;
var inputText = TargetElement.Text;
if (inputText != null)
{
context.InsertText(ConvertText(inputText));
}
var end = context.Document.CreateAnchor(context.InsertionPosition);
end.MovementType = AnchorMovementType.BeforeInsertion;
end.SurviveDeletion = true;
var segment = new AnchorSegment(start, end);
context.RegisterActiveElement(this, new BoundActiveElement(context, TargetElement, this, segment));
}
}
///// <inheritdoc/>
//public override Inline ToTextRun()
//{
// if (TargetElement != null) {
// string inputText = TargetElement.Text;
// if (inputText != null) {
// return new Italic(new Run(ConvertText(inputText)));
// }
// }
// return base.ToTextRun();
//}
}
internal sealed class BoundActiveElement : IActiveElement
{
private readonly InsertionContext _context;
private readonly SnippetReplaceableTextElement _targetSnippetElement;
private readonly SnippetBoundElement _boundElement;
internal IReplaceableActiveElement TargetElement;
private AnchorSegment _segment;
public BoundActiveElement(InsertionContext context, SnippetReplaceableTextElement targetSnippetElement, SnippetBoundElement boundElement, AnchorSegment segment)
{
_context = context;
_targetSnippetElement = targetSnippetElement;
_boundElement = boundElement;
_segment = segment;
}
public void OnInsertionCompleted()
{
TargetElement = _context.GetActiveElement(_targetSnippetElement) as IReplaceableActiveElement;
if (TargetElement != null)
{
TargetElement.TextChanged += targetElement_TextChanged;
}
}
private void targetElement_TextChanged(object sender, EventArgs e)
{
// Don't copy text if the segments overlap (we would get an endless loop).
// This can happen if the user deletes the text between the replaceable element and the bound element.
if (SimpleSegment.GetOverlap(_segment, TargetElement.Segment) == SimpleSegment.Invalid)
{
var offset = _segment.Offset;
var length = _segment.Length;
var text = _boundElement.ConvertText(TargetElement.Text);
if (length != text.Length || text != _context.Document.GetText(offset, length))
{
// Call replace only if we're actually changing something.
// Without this check, we would generate an empty undo group when the user pressed undo.
_context.Document.Replace(offset, length, text);
if (length == 0)
{
// replacing an empty anchor segment with text won't enlarge it, so we have to recreate it
_segment = new AnchorSegment(_context.Document, offset, text.Length);
}
}
}
}
public void Deactivate(SnippetEventArgs e)
{
}
public bool IsEditable => false;
public ISegment Segment => _segment;
}
}
<MSG> Merge pull request #40 from danwalmsley/snippet-returns-context
Snippet returns context
<DFF> @@ -123,6 +123,7 @@ namespace AvaloniaEdit.Snippets
public void Deactivate(SnippetEventArgs e)
{
+ TargetElement.TextChanged -= targetElement_TextChanged;
}
public bool IsEditable => false;
| 1 | Merge pull request #40 from danwalmsley/snippet-returns-context | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057664 | <NME> SnippetBoundElement.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 AvaloniaEdit.Document;
namespace AvaloniaEdit.Snippets
{
/// <summary>
/// An element that binds to a <see cref="SnippetReplaceableTextElement"/> and displays the same text.
/// </summary>
public class SnippetBoundElement : SnippetElement
{
/// <summary>
/// Gets/Sets the target element.
/// </summary>
public SnippetReplaceableTextElement TargetElement { get; set; }
/// <summary>
/// Converts the text before copying it.
/// </summary>
public virtual string ConvertText(string input)
{
return input;
}
/// <inheritdoc/>
public override void Insert(InsertionContext context)
{
if (TargetElement != null)
{
var start = context.Document.CreateAnchor(context.InsertionPosition);
start.MovementType = AnchorMovementType.BeforeInsertion;
start.SurviveDeletion = true;
var inputText = TargetElement.Text;
if (inputText != null)
{
context.InsertText(ConvertText(inputText));
}
var end = context.Document.CreateAnchor(context.InsertionPosition);
end.MovementType = AnchorMovementType.BeforeInsertion;
end.SurviveDeletion = true;
var segment = new AnchorSegment(start, end);
context.RegisterActiveElement(this, new BoundActiveElement(context, TargetElement, this, segment));
}
}
///// <inheritdoc/>
//public override Inline ToTextRun()
//{
// if (TargetElement != null) {
// string inputText = TargetElement.Text;
// if (inputText != null) {
// return new Italic(new Run(ConvertText(inputText)));
// }
// }
// return base.ToTextRun();
//}
}
internal sealed class BoundActiveElement : IActiveElement
{
private readonly InsertionContext _context;
private readonly SnippetReplaceableTextElement _targetSnippetElement;
private readonly SnippetBoundElement _boundElement;
internal IReplaceableActiveElement TargetElement;
private AnchorSegment _segment;
public BoundActiveElement(InsertionContext context, SnippetReplaceableTextElement targetSnippetElement, SnippetBoundElement boundElement, AnchorSegment segment)
{
_context = context;
_targetSnippetElement = targetSnippetElement;
_boundElement = boundElement;
_segment = segment;
}
public void OnInsertionCompleted()
{
TargetElement = _context.GetActiveElement(_targetSnippetElement) as IReplaceableActiveElement;
if (TargetElement != null)
{
TargetElement.TextChanged += targetElement_TextChanged;
}
}
private void targetElement_TextChanged(object sender, EventArgs e)
{
// Don't copy text if the segments overlap (we would get an endless loop).
// This can happen if the user deletes the text between the replaceable element and the bound element.
if (SimpleSegment.GetOverlap(_segment, TargetElement.Segment) == SimpleSegment.Invalid)
{
var offset = _segment.Offset;
var length = _segment.Length;
var text = _boundElement.ConvertText(TargetElement.Text);
if (length != text.Length || text != _context.Document.GetText(offset, length))
{
// Call replace only if we're actually changing something.
// Without this check, we would generate an empty undo group when the user pressed undo.
_context.Document.Replace(offset, length, text);
if (length == 0)
{
// replacing an empty anchor segment with text won't enlarge it, so we have to recreate it
_segment = new AnchorSegment(_context.Document, offset, text.Length);
}
}
}
}
public void Deactivate(SnippetEventArgs e)
{
}
public bool IsEditable => false;
public ISegment Segment => _segment;
}
}
<MSG> Merge pull request #40 from danwalmsley/snippet-returns-context
Snippet returns context
<DFF> @@ -123,6 +123,7 @@ namespace AvaloniaEdit.Snippets
public void Deactivate(SnippetEventArgs e)
{
+ TargetElement.TextChanged -= targetElement_TextChanged;
}
public bool IsEditable => false;
| 1 | Merge pull request #40 from danwalmsley/snippet-returns-context | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057665 | <NME> SnippetBoundElement.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 AvaloniaEdit.Document;
namespace AvaloniaEdit.Snippets
{
/// <summary>
/// An element that binds to a <see cref="SnippetReplaceableTextElement"/> and displays the same text.
/// </summary>
public class SnippetBoundElement : SnippetElement
{
/// <summary>
/// Gets/Sets the target element.
/// </summary>
public SnippetReplaceableTextElement TargetElement { get; set; }
/// <summary>
/// Converts the text before copying it.
/// </summary>
public virtual string ConvertText(string input)
{
return input;
}
/// <inheritdoc/>
public override void Insert(InsertionContext context)
{
if (TargetElement != null)
{
var start = context.Document.CreateAnchor(context.InsertionPosition);
start.MovementType = AnchorMovementType.BeforeInsertion;
start.SurviveDeletion = true;
var inputText = TargetElement.Text;
if (inputText != null)
{
context.InsertText(ConvertText(inputText));
}
var end = context.Document.CreateAnchor(context.InsertionPosition);
end.MovementType = AnchorMovementType.BeforeInsertion;
end.SurviveDeletion = true;
var segment = new AnchorSegment(start, end);
context.RegisterActiveElement(this, new BoundActiveElement(context, TargetElement, this, segment));
}
}
///// <inheritdoc/>
//public override Inline ToTextRun()
//{
// if (TargetElement != null) {
// string inputText = TargetElement.Text;
// if (inputText != null) {
// return new Italic(new Run(ConvertText(inputText)));
// }
// }
// return base.ToTextRun();
//}
}
internal sealed class BoundActiveElement : IActiveElement
{
private readonly InsertionContext _context;
private readonly SnippetReplaceableTextElement _targetSnippetElement;
private readonly SnippetBoundElement _boundElement;
internal IReplaceableActiveElement TargetElement;
private AnchorSegment _segment;
public BoundActiveElement(InsertionContext context, SnippetReplaceableTextElement targetSnippetElement, SnippetBoundElement boundElement, AnchorSegment segment)
{
_context = context;
_targetSnippetElement = targetSnippetElement;
_boundElement = boundElement;
_segment = segment;
}
public void OnInsertionCompleted()
{
TargetElement = _context.GetActiveElement(_targetSnippetElement) as IReplaceableActiveElement;
if (TargetElement != null)
{
TargetElement.TextChanged += targetElement_TextChanged;
}
}
private void targetElement_TextChanged(object sender, EventArgs e)
{
// Don't copy text if the segments overlap (we would get an endless loop).
// This can happen if the user deletes the text between the replaceable element and the bound element.
if (SimpleSegment.GetOverlap(_segment, TargetElement.Segment) == SimpleSegment.Invalid)
{
var offset = _segment.Offset;
var length = _segment.Length;
var text = _boundElement.ConvertText(TargetElement.Text);
if (length != text.Length || text != _context.Document.GetText(offset, length))
{
// Call replace only if we're actually changing something.
// Without this check, we would generate an empty undo group when the user pressed undo.
_context.Document.Replace(offset, length, text);
if (length == 0)
{
// replacing an empty anchor segment with text won't enlarge it, so we have to recreate it
_segment = new AnchorSegment(_context.Document, offset, text.Length);
}
}
}
}
public void Deactivate(SnippetEventArgs e)
{
}
public bool IsEditable => false;
public ISegment Segment => _segment;
}
}
<MSG> Merge pull request #40 from danwalmsley/snippet-returns-context
Snippet returns context
<DFF> @@ -123,6 +123,7 @@ namespace AvaloniaEdit.Snippets
public void Deactivate(SnippetEventArgs e)
{
+ TargetElement.TextChanged -= targetElement_TextChanged;
}
public bool IsEditable => false;
| 1 | Merge pull request #40 from danwalmsley/snippet-returns-context | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057666 | <NME> SnippetBoundElement.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 AvaloniaEdit.Document;
namespace AvaloniaEdit.Snippets
{
/// <summary>
/// An element that binds to a <see cref="SnippetReplaceableTextElement"/> and displays the same text.
/// </summary>
public class SnippetBoundElement : SnippetElement
{
/// <summary>
/// Gets/Sets the target element.
/// </summary>
public SnippetReplaceableTextElement TargetElement { get; set; }
/// <summary>
/// Converts the text before copying it.
/// </summary>
public virtual string ConvertText(string input)
{
return input;
}
/// <inheritdoc/>
public override void Insert(InsertionContext context)
{
if (TargetElement != null)
{
var start = context.Document.CreateAnchor(context.InsertionPosition);
start.MovementType = AnchorMovementType.BeforeInsertion;
start.SurviveDeletion = true;
var inputText = TargetElement.Text;
if (inputText != null)
{
context.InsertText(ConvertText(inputText));
}
var end = context.Document.CreateAnchor(context.InsertionPosition);
end.MovementType = AnchorMovementType.BeforeInsertion;
end.SurviveDeletion = true;
var segment = new AnchorSegment(start, end);
context.RegisterActiveElement(this, new BoundActiveElement(context, TargetElement, this, segment));
}
}
///// <inheritdoc/>
//public override Inline ToTextRun()
//{
// if (TargetElement != null) {
// string inputText = TargetElement.Text;
// if (inputText != null) {
// return new Italic(new Run(ConvertText(inputText)));
// }
// }
// return base.ToTextRun();
//}
}
internal sealed class BoundActiveElement : IActiveElement
{
private readonly InsertionContext _context;
private readonly SnippetReplaceableTextElement _targetSnippetElement;
private readonly SnippetBoundElement _boundElement;
internal IReplaceableActiveElement TargetElement;
private AnchorSegment _segment;
public BoundActiveElement(InsertionContext context, SnippetReplaceableTextElement targetSnippetElement, SnippetBoundElement boundElement, AnchorSegment segment)
{
_context = context;
_targetSnippetElement = targetSnippetElement;
_boundElement = boundElement;
_segment = segment;
}
public void OnInsertionCompleted()
{
TargetElement = _context.GetActiveElement(_targetSnippetElement) as IReplaceableActiveElement;
if (TargetElement != null)
{
TargetElement.TextChanged += targetElement_TextChanged;
}
}
private void targetElement_TextChanged(object sender, EventArgs e)
{
// Don't copy text if the segments overlap (we would get an endless loop).
// This can happen if the user deletes the text between the replaceable element and the bound element.
if (SimpleSegment.GetOverlap(_segment, TargetElement.Segment) == SimpleSegment.Invalid)
{
var offset = _segment.Offset;
var length = _segment.Length;
var text = _boundElement.ConvertText(TargetElement.Text);
if (length != text.Length || text != _context.Document.GetText(offset, length))
{
// Call replace only if we're actually changing something.
// Without this check, we would generate an empty undo group when the user pressed undo.
_context.Document.Replace(offset, length, text);
if (length == 0)
{
// replacing an empty anchor segment with text won't enlarge it, so we have to recreate it
_segment = new AnchorSegment(_context.Document, offset, text.Length);
}
}
}
}
public void Deactivate(SnippetEventArgs e)
{
}
public bool IsEditable => false;
public ISegment Segment => _segment;
}
}
<MSG> Merge pull request #40 from danwalmsley/snippet-returns-context
Snippet returns context
<DFF> @@ -123,6 +123,7 @@ namespace AvaloniaEdit.Snippets
public void Deactivate(SnippetEventArgs e)
{
+ TargetElement.TextChanged -= targetElement_TextChanged;
}
public bool IsEditable => false;
| 1 | Merge pull request #40 from danwalmsley/snippet-returns-context | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057667 | <NME> SnippetBoundElement.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 AvaloniaEdit.Document;
namespace AvaloniaEdit.Snippets
{
/// <summary>
/// An element that binds to a <see cref="SnippetReplaceableTextElement"/> and displays the same text.
/// </summary>
public class SnippetBoundElement : SnippetElement
{
/// <summary>
/// Gets/Sets the target element.
/// </summary>
public SnippetReplaceableTextElement TargetElement { get; set; }
/// <summary>
/// Converts the text before copying it.
/// </summary>
public virtual string ConvertText(string input)
{
return input;
}
/// <inheritdoc/>
public override void Insert(InsertionContext context)
{
if (TargetElement != null)
{
var start = context.Document.CreateAnchor(context.InsertionPosition);
start.MovementType = AnchorMovementType.BeforeInsertion;
start.SurviveDeletion = true;
var inputText = TargetElement.Text;
if (inputText != null)
{
context.InsertText(ConvertText(inputText));
}
var end = context.Document.CreateAnchor(context.InsertionPosition);
end.MovementType = AnchorMovementType.BeforeInsertion;
end.SurviveDeletion = true;
var segment = new AnchorSegment(start, end);
context.RegisterActiveElement(this, new BoundActiveElement(context, TargetElement, this, segment));
}
}
///// <inheritdoc/>
//public override Inline ToTextRun()
//{
// if (TargetElement != null) {
// string inputText = TargetElement.Text;
// if (inputText != null) {
// return new Italic(new Run(ConvertText(inputText)));
// }
// }
// return base.ToTextRun();
//}
}
internal sealed class BoundActiveElement : IActiveElement
{
private readonly InsertionContext _context;
private readonly SnippetReplaceableTextElement _targetSnippetElement;
private readonly SnippetBoundElement _boundElement;
internal IReplaceableActiveElement TargetElement;
private AnchorSegment _segment;
public BoundActiveElement(InsertionContext context, SnippetReplaceableTextElement targetSnippetElement, SnippetBoundElement boundElement, AnchorSegment segment)
{
_context = context;
_targetSnippetElement = targetSnippetElement;
_boundElement = boundElement;
_segment = segment;
}
public void OnInsertionCompleted()
{
TargetElement = _context.GetActiveElement(_targetSnippetElement) as IReplaceableActiveElement;
if (TargetElement != null)
{
TargetElement.TextChanged += targetElement_TextChanged;
}
}
private void targetElement_TextChanged(object sender, EventArgs e)
{
// Don't copy text if the segments overlap (we would get an endless loop).
// This can happen if the user deletes the text between the replaceable element and the bound element.
if (SimpleSegment.GetOverlap(_segment, TargetElement.Segment) == SimpleSegment.Invalid)
{
var offset = _segment.Offset;
var length = _segment.Length;
var text = _boundElement.ConvertText(TargetElement.Text);
if (length != text.Length || text != _context.Document.GetText(offset, length))
{
// Call replace only if we're actually changing something.
// Without this check, we would generate an empty undo group when the user pressed undo.
_context.Document.Replace(offset, length, text);
if (length == 0)
{
// replacing an empty anchor segment with text won't enlarge it, so we have to recreate it
_segment = new AnchorSegment(_context.Document, offset, text.Length);
}
}
}
}
public void Deactivate(SnippetEventArgs e)
{
}
public bool IsEditable => false;
public ISegment Segment => _segment;
}
}
<MSG> Merge pull request #40 from danwalmsley/snippet-returns-context
Snippet returns context
<DFF> @@ -123,6 +123,7 @@ namespace AvaloniaEdit.Snippets
public void Deactivate(SnippetEventArgs e)
{
+ TargetElement.TextChanged -= targetElement_TextChanged;
}
public bool IsEditable => false;
| 1 | Merge pull request #40 from danwalmsley/snippet-returns-context | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057668 | <NME> SnippetBoundElement.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 AvaloniaEdit.Document;
namespace AvaloniaEdit.Snippets
{
/// <summary>
/// An element that binds to a <see cref="SnippetReplaceableTextElement"/> and displays the same text.
/// </summary>
public class SnippetBoundElement : SnippetElement
{
/// <summary>
/// Gets/Sets the target element.
/// </summary>
public SnippetReplaceableTextElement TargetElement { get; set; }
/// <summary>
/// Converts the text before copying it.
/// </summary>
public virtual string ConvertText(string input)
{
return input;
}
/// <inheritdoc/>
public override void Insert(InsertionContext context)
{
if (TargetElement != null)
{
var start = context.Document.CreateAnchor(context.InsertionPosition);
start.MovementType = AnchorMovementType.BeforeInsertion;
start.SurviveDeletion = true;
var inputText = TargetElement.Text;
if (inputText != null)
{
context.InsertText(ConvertText(inputText));
}
var end = context.Document.CreateAnchor(context.InsertionPosition);
end.MovementType = AnchorMovementType.BeforeInsertion;
end.SurviveDeletion = true;
var segment = new AnchorSegment(start, end);
context.RegisterActiveElement(this, new BoundActiveElement(context, TargetElement, this, segment));
}
}
///// <inheritdoc/>
//public override Inline ToTextRun()
//{
// if (TargetElement != null) {
// string inputText = TargetElement.Text;
// if (inputText != null) {
// return new Italic(new Run(ConvertText(inputText)));
// }
// }
// return base.ToTextRun();
//}
}
internal sealed class BoundActiveElement : IActiveElement
{
private readonly InsertionContext _context;
private readonly SnippetReplaceableTextElement _targetSnippetElement;
private readonly SnippetBoundElement _boundElement;
internal IReplaceableActiveElement TargetElement;
private AnchorSegment _segment;
public BoundActiveElement(InsertionContext context, SnippetReplaceableTextElement targetSnippetElement, SnippetBoundElement boundElement, AnchorSegment segment)
{
_context = context;
_targetSnippetElement = targetSnippetElement;
_boundElement = boundElement;
_segment = segment;
}
public void OnInsertionCompleted()
{
TargetElement = _context.GetActiveElement(_targetSnippetElement) as IReplaceableActiveElement;
if (TargetElement != null)
{
TargetElement.TextChanged += targetElement_TextChanged;
}
}
private void targetElement_TextChanged(object sender, EventArgs e)
{
// Don't copy text if the segments overlap (we would get an endless loop).
// This can happen if the user deletes the text between the replaceable element and the bound element.
if (SimpleSegment.GetOverlap(_segment, TargetElement.Segment) == SimpleSegment.Invalid)
{
var offset = _segment.Offset;
var length = _segment.Length;
var text = _boundElement.ConvertText(TargetElement.Text);
if (length != text.Length || text != _context.Document.GetText(offset, length))
{
// Call replace only if we're actually changing something.
// Without this check, we would generate an empty undo group when the user pressed undo.
_context.Document.Replace(offset, length, text);
if (length == 0)
{
// replacing an empty anchor segment with text won't enlarge it, so we have to recreate it
_segment = new AnchorSegment(_context.Document, offset, text.Length);
}
}
}
}
public void Deactivate(SnippetEventArgs e)
{
}
public bool IsEditable => false;
public ISegment Segment => _segment;
}
}
<MSG> Merge pull request #40 from danwalmsley/snippet-returns-context
Snippet returns context
<DFF> @@ -123,6 +123,7 @@ namespace AvaloniaEdit.Snippets
public void Deactivate(SnippetEventArgs e)
{
+ TargetElement.TextChanged -= targetElement_TextChanged;
}
public bool IsEditable => false;
| 1 | Merge pull request #40 from danwalmsley/snippet-returns-context | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057669 | <NME> SnippetBoundElement.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 AvaloniaEdit.Document;
namespace AvaloniaEdit.Snippets
{
/// <summary>
/// An element that binds to a <see cref="SnippetReplaceableTextElement"/> and displays the same text.
/// </summary>
public class SnippetBoundElement : SnippetElement
{
/// <summary>
/// Gets/Sets the target element.
/// </summary>
public SnippetReplaceableTextElement TargetElement { get; set; }
/// <summary>
/// Converts the text before copying it.
/// </summary>
public virtual string ConvertText(string input)
{
return input;
}
/// <inheritdoc/>
public override void Insert(InsertionContext context)
{
if (TargetElement != null)
{
var start = context.Document.CreateAnchor(context.InsertionPosition);
start.MovementType = AnchorMovementType.BeforeInsertion;
start.SurviveDeletion = true;
var inputText = TargetElement.Text;
if (inputText != null)
{
context.InsertText(ConvertText(inputText));
}
var end = context.Document.CreateAnchor(context.InsertionPosition);
end.MovementType = AnchorMovementType.BeforeInsertion;
end.SurviveDeletion = true;
var segment = new AnchorSegment(start, end);
context.RegisterActiveElement(this, new BoundActiveElement(context, TargetElement, this, segment));
}
}
///// <inheritdoc/>
//public override Inline ToTextRun()
//{
// if (TargetElement != null) {
// string inputText = TargetElement.Text;
// if (inputText != null) {
// return new Italic(new Run(ConvertText(inputText)));
// }
// }
// return base.ToTextRun();
//}
}
internal sealed class BoundActiveElement : IActiveElement
{
private readonly InsertionContext _context;
private readonly SnippetReplaceableTextElement _targetSnippetElement;
private readonly SnippetBoundElement _boundElement;
internal IReplaceableActiveElement TargetElement;
private AnchorSegment _segment;
public BoundActiveElement(InsertionContext context, SnippetReplaceableTextElement targetSnippetElement, SnippetBoundElement boundElement, AnchorSegment segment)
{
_context = context;
_targetSnippetElement = targetSnippetElement;
_boundElement = boundElement;
_segment = segment;
}
public void OnInsertionCompleted()
{
TargetElement = _context.GetActiveElement(_targetSnippetElement) as IReplaceableActiveElement;
if (TargetElement != null)
{
TargetElement.TextChanged += targetElement_TextChanged;
}
}
private void targetElement_TextChanged(object sender, EventArgs e)
{
// Don't copy text if the segments overlap (we would get an endless loop).
// This can happen if the user deletes the text between the replaceable element and the bound element.
if (SimpleSegment.GetOverlap(_segment, TargetElement.Segment) == SimpleSegment.Invalid)
{
var offset = _segment.Offset;
var length = _segment.Length;
var text = _boundElement.ConvertText(TargetElement.Text);
if (length != text.Length || text != _context.Document.GetText(offset, length))
{
// Call replace only if we're actually changing something.
// Without this check, we would generate an empty undo group when the user pressed undo.
_context.Document.Replace(offset, length, text);
if (length == 0)
{
// replacing an empty anchor segment with text won't enlarge it, so we have to recreate it
_segment = new AnchorSegment(_context.Document, offset, text.Length);
}
}
}
}
public void Deactivate(SnippetEventArgs e)
{
}
public bool IsEditable => false;
public ISegment Segment => _segment;
}
}
<MSG> Merge pull request #40 from danwalmsley/snippet-returns-context
Snippet returns context
<DFF> @@ -123,6 +123,7 @@ namespace AvaloniaEdit.Snippets
public void Deactivate(SnippetEventArgs e)
{
+ TargetElement.TextChanged -= targetElement_TextChanged;
}
public bool IsEditable => false;
| 1 | Merge pull request #40 from danwalmsley/snippet-returns-context | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057670 | <NME> SnippetBoundElement.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 AvaloniaEdit.Document;
namespace AvaloniaEdit.Snippets
{
/// <summary>
/// An element that binds to a <see cref="SnippetReplaceableTextElement"/> and displays the same text.
/// </summary>
public class SnippetBoundElement : SnippetElement
{
/// <summary>
/// Gets/Sets the target element.
/// </summary>
public SnippetReplaceableTextElement TargetElement { get; set; }
/// <summary>
/// Converts the text before copying it.
/// </summary>
public virtual string ConvertText(string input)
{
return input;
}
/// <inheritdoc/>
public override void Insert(InsertionContext context)
{
if (TargetElement != null)
{
var start = context.Document.CreateAnchor(context.InsertionPosition);
start.MovementType = AnchorMovementType.BeforeInsertion;
start.SurviveDeletion = true;
var inputText = TargetElement.Text;
if (inputText != null)
{
context.InsertText(ConvertText(inputText));
}
var end = context.Document.CreateAnchor(context.InsertionPosition);
end.MovementType = AnchorMovementType.BeforeInsertion;
end.SurviveDeletion = true;
var segment = new AnchorSegment(start, end);
context.RegisterActiveElement(this, new BoundActiveElement(context, TargetElement, this, segment));
}
}
///// <inheritdoc/>
//public override Inline ToTextRun()
//{
// if (TargetElement != null) {
// string inputText = TargetElement.Text;
// if (inputText != null) {
// return new Italic(new Run(ConvertText(inputText)));
// }
// }
// return base.ToTextRun();
//}
}
internal sealed class BoundActiveElement : IActiveElement
{
private readonly InsertionContext _context;
private readonly SnippetReplaceableTextElement _targetSnippetElement;
private readonly SnippetBoundElement _boundElement;
internal IReplaceableActiveElement TargetElement;
private AnchorSegment _segment;
public BoundActiveElement(InsertionContext context, SnippetReplaceableTextElement targetSnippetElement, SnippetBoundElement boundElement, AnchorSegment segment)
{
_context = context;
_targetSnippetElement = targetSnippetElement;
_boundElement = boundElement;
_segment = segment;
}
public void OnInsertionCompleted()
{
TargetElement = _context.GetActiveElement(_targetSnippetElement) as IReplaceableActiveElement;
if (TargetElement != null)
{
TargetElement.TextChanged += targetElement_TextChanged;
}
}
private void targetElement_TextChanged(object sender, EventArgs e)
{
// Don't copy text if the segments overlap (we would get an endless loop).
// This can happen if the user deletes the text between the replaceable element and the bound element.
if (SimpleSegment.GetOverlap(_segment, TargetElement.Segment) == SimpleSegment.Invalid)
{
var offset = _segment.Offset;
var length = _segment.Length;
var text = _boundElement.ConvertText(TargetElement.Text);
if (length != text.Length || text != _context.Document.GetText(offset, length))
{
// Call replace only if we're actually changing something.
// Without this check, we would generate an empty undo group when the user pressed undo.
_context.Document.Replace(offset, length, text);
if (length == 0)
{
// replacing an empty anchor segment with text won't enlarge it, so we have to recreate it
_segment = new AnchorSegment(_context.Document, offset, text.Length);
}
}
}
}
public void Deactivate(SnippetEventArgs e)
{
}
public bool IsEditable => false;
public ISegment Segment => _segment;
}
}
<MSG> Merge pull request #40 from danwalmsley/snippet-returns-context
Snippet returns context
<DFF> @@ -123,6 +123,7 @@ namespace AvaloniaEdit.Snippets
public void Deactivate(SnippetEventArgs e)
{
+ TargetElement.TextChanged -= targetElement_TextChanged;
}
public bool IsEditable => false;
| 1 | Merge pull request #40 from danwalmsley/snippet-returns-context | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057671 | <NME> SnippetBoundElement.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 AvaloniaEdit.Document;
namespace AvaloniaEdit.Snippets
{
/// <summary>
/// An element that binds to a <see cref="SnippetReplaceableTextElement"/> and displays the same text.
/// </summary>
public class SnippetBoundElement : SnippetElement
{
/// <summary>
/// Gets/Sets the target element.
/// </summary>
public SnippetReplaceableTextElement TargetElement { get; set; }
/// <summary>
/// Converts the text before copying it.
/// </summary>
public virtual string ConvertText(string input)
{
return input;
}
/// <inheritdoc/>
public override void Insert(InsertionContext context)
{
if (TargetElement != null)
{
var start = context.Document.CreateAnchor(context.InsertionPosition);
start.MovementType = AnchorMovementType.BeforeInsertion;
start.SurviveDeletion = true;
var inputText = TargetElement.Text;
if (inputText != null)
{
context.InsertText(ConvertText(inputText));
}
var end = context.Document.CreateAnchor(context.InsertionPosition);
end.MovementType = AnchorMovementType.BeforeInsertion;
end.SurviveDeletion = true;
var segment = new AnchorSegment(start, end);
context.RegisterActiveElement(this, new BoundActiveElement(context, TargetElement, this, segment));
}
}
///// <inheritdoc/>
//public override Inline ToTextRun()
//{
// if (TargetElement != null) {
// string inputText = TargetElement.Text;
// if (inputText != null) {
// return new Italic(new Run(ConvertText(inputText)));
// }
// }
// return base.ToTextRun();
//}
}
internal sealed class BoundActiveElement : IActiveElement
{
private readonly InsertionContext _context;
private readonly SnippetReplaceableTextElement _targetSnippetElement;
private readonly SnippetBoundElement _boundElement;
internal IReplaceableActiveElement TargetElement;
private AnchorSegment _segment;
public BoundActiveElement(InsertionContext context, SnippetReplaceableTextElement targetSnippetElement, SnippetBoundElement boundElement, AnchorSegment segment)
{
_context = context;
_targetSnippetElement = targetSnippetElement;
_boundElement = boundElement;
_segment = segment;
}
public void OnInsertionCompleted()
{
TargetElement = _context.GetActiveElement(_targetSnippetElement) as IReplaceableActiveElement;
if (TargetElement != null)
{
TargetElement.TextChanged += targetElement_TextChanged;
}
}
private void targetElement_TextChanged(object sender, EventArgs e)
{
// Don't copy text if the segments overlap (we would get an endless loop).
// This can happen if the user deletes the text between the replaceable element and the bound element.
if (SimpleSegment.GetOverlap(_segment, TargetElement.Segment) == SimpleSegment.Invalid)
{
var offset = _segment.Offset;
var length = _segment.Length;
var text = _boundElement.ConvertText(TargetElement.Text);
if (length != text.Length || text != _context.Document.GetText(offset, length))
{
// Call replace only if we're actually changing something.
// Without this check, we would generate an empty undo group when the user pressed undo.
_context.Document.Replace(offset, length, text);
if (length == 0)
{
// replacing an empty anchor segment with text won't enlarge it, so we have to recreate it
_segment = new AnchorSegment(_context.Document, offset, text.Length);
}
}
}
}
public void Deactivate(SnippetEventArgs e)
{
}
public bool IsEditable => false;
public ISegment Segment => _segment;
}
}
<MSG> Merge pull request #40 from danwalmsley/snippet-returns-context
Snippet returns context
<DFF> @@ -123,6 +123,7 @@ namespace AvaloniaEdit.Snippets
public void Deactivate(SnippetEventArgs e)
{
+ TargetElement.TextChanged -= targetElement_TextChanged;
}
public bool IsEditable => false;
| 1 | Merge pull request #40 from danwalmsley/snippet-returns-context | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057672 | <NME> SnippetBoundElement.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 AvaloniaEdit.Document;
namespace AvaloniaEdit.Snippets
{
/// <summary>
/// An element that binds to a <see cref="SnippetReplaceableTextElement"/> and displays the same text.
/// </summary>
public class SnippetBoundElement : SnippetElement
{
/// <summary>
/// Gets/Sets the target element.
/// </summary>
public SnippetReplaceableTextElement TargetElement { get; set; }
/// <summary>
/// Converts the text before copying it.
/// </summary>
public virtual string ConvertText(string input)
{
return input;
}
/// <inheritdoc/>
public override void Insert(InsertionContext context)
{
if (TargetElement != null)
{
var start = context.Document.CreateAnchor(context.InsertionPosition);
start.MovementType = AnchorMovementType.BeforeInsertion;
start.SurviveDeletion = true;
var inputText = TargetElement.Text;
if (inputText != null)
{
context.InsertText(ConvertText(inputText));
}
var end = context.Document.CreateAnchor(context.InsertionPosition);
end.MovementType = AnchorMovementType.BeforeInsertion;
end.SurviveDeletion = true;
var segment = new AnchorSegment(start, end);
context.RegisterActiveElement(this, new BoundActiveElement(context, TargetElement, this, segment));
}
}
///// <inheritdoc/>
//public override Inline ToTextRun()
//{
// if (TargetElement != null) {
// string inputText = TargetElement.Text;
// if (inputText != null) {
// return new Italic(new Run(ConvertText(inputText)));
// }
// }
// return base.ToTextRun();
//}
}
internal sealed class BoundActiveElement : IActiveElement
{
private readonly InsertionContext _context;
private readonly SnippetReplaceableTextElement _targetSnippetElement;
private readonly SnippetBoundElement _boundElement;
internal IReplaceableActiveElement TargetElement;
private AnchorSegment _segment;
public BoundActiveElement(InsertionContext context, SnippetReplaceableTextElement targetSnippetElement, SnippetBoundElement boundElement, AnchorSegment segment)
{
_context = context;
_targetSnippetElement = targetSnippetElement;
_boundElement = boundElement;
_segment = segment;
}
public void OnInsertionCompleted()
{
TargetElement = _context.GetActiveElement(_targetSnippetElement) as IReplaceableActiveElement;
if (TargetElement != null)
{
TargetElement.TextChanged += targetElement_TextChanged;
}
}
private void targetElement_TextChanged(object sender, EventArgs e)
{
// Don't copy text if the segments overlap (we would get an endless loop).
// This can happen if the user deletes the text between the replaceable element and the bound element.
if (SimpleSegment.GetOverlap(_segment, TargetElement.Segment) == SimpleSegment.Invalid)
{
var offset = _segment.Offset;
var length = _segment.Length;
var text = _boundElement.ConvertText(TargetElement.Text);
if (length != text.Length || text != _context.Document.GetText(offset, length))
{
// Call replace only if we're actually changing something.
// Without this check, we would generate an empty undo group when the user pressed undo.
_context.Document.Replace(offset, length, text);
if (length == 0)
{
// replacing an empty anchor segment with text won't enlarge it, so we have to recreate it
_segment = new AnchorSegment(_context.Document, offset, text.Length);
}
}
}
}
public void Deactivate(SnippetEventArgs e)
{
}
public bool IsEditable => false;
public ISegment Segment => _segment;
}
}
<MSG> Merge pull request #40 from danwalmsley/snippet-returns-context
Snippet returns context
<DFF> @@ -123,6 +123,7 @@ namespace AvaloniaEdit.Snippets
public void Deactivate(SnippetEventArgs e)
{
+ TargetElement.TextChanged -= targetElement_TextChanged;
}
public bool IsEditable => false;
| 1 | Merge pull request #40 from danwalmsley/snippet-returns-context | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057673 | <NME> SnippetBoundElement.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 AvaloniaEdit.Document;
namespace AvaloniaEdit.Snippets
{
/// <summary>
/// An element that binds to a <see cref="SnippetReplaceableTextElement"/> and displays the same text.
/// </summary>
public class SnippetBoundElement : SnippetElement
{
/// <summary>
/// Gets/Sets the target element.
/// </summary>
public SnippetReplaceableTextElement TargetElement { get; set; }
/// <summary>
/// Converts the text before copying it.
/// </summary>
public virtual string ConvertText(string input)
{
return input;
}
/// <inheritdoc/>
public override void Insert(InsertionContext context)
{
if (TargetElement != null)
{
var start = context.Document.CreateAnchor(context.InsertionPosition);
start.MovementType = AnchorMovementType.BeforeInsertion;
start.SurviveDeletion = true;
var inputText = TargetElement.Text;
if (inputText != null)
{
context.InsertText(ConvertText(inputText));
}
var end = context.Document.CreateAnchor(context.InsertionPosition);
end.MovementType = AnchorMovementType.BeforeInsertion;
end.SurviveDeletion = true;
var segment = new AnchorSegment(start, end);
context.RegisterActiveElement(this, new BoundActiveElement(context, TargetElement, this, segment));
}
}
///// <inheritdoc/>
//public override Inline ToTextRun()
//{
// if (TargetElement != null) {
// string inputText = TargetElement.Text;
// if (inputText != null) {
// return new Italic(new Run(ConvertText(inputText)));
// }
// }
// return base.ToTextRun();
//}
}
internal sealed class BoundActiveElement : IActiveElement
{
private readonly InsertionContext _context;
private readonly SnippetReplaceableTextElement _targetSnippetElement;
private readonly SnippetBoundElement _boundElement;
internal IReplaceableActiveElement TargetElement;
private AnchorSegment _segment;
public BoundActiveElement(InsertionContext context, SnippetReplaceableTextElement targetSnippetElement, SnippetBoundElement boundElement, AnchorSegment segment)
{
_context = context;
_targetSnippetElement = targetSnippetElement;
_boundElement = boundElement;
_segment = segment;
}
public void OnInsertionCompleted()
{
TargetElement = _context.GetActiveElement(_targetSnippetElement) as IReplaceableActiveElement;
if (TargetElement != null)
{
TargetElement.TextChanged += targetElement_TextChanged;
}
}
private void targetElement_TextChanged(object sender, EventArgs e)
{
// Don't copy text if the segments overlap (we would get an endless loop).
// This can happen if the user deletes the text between the replaceable element and the bound element.
if (SimpleSegment.GetOverlap(_segment, TargetElement.Segment) == SimpleSegment.Invalid)
{
var offset = _segment.Offset;
var length = _segment.Length;
var text = _boundElement.ConvertText(TargetElement.Text);
if (length != text.Length || text != _context.Document.GetText(offset, length))
{
// Call replace only if we're actually changing something.
// Without this check, we would generate an empty undo group when the user pressed undo.
_context.Document.Replace(offset, length, text);
if (length == 0)
{
// replacing an empty anchor segment with text won't enlarge it, so we have to recreate it
_segment = new AnchorSegment(_context.Document, offset, text.Length);
}
}
}
}
public void Deactivate(SnippetEventArgs e)
{
}
public bool IsEditable => false;
public ISegment Segment => _segment;
}
}
<MSG> Merge pull request #40 from danwalmsley/snippet-returns-context
Snippet returns context
<DFF> @@ -123,6 +123,7 @@ namespace AvaloniaEdit.Snippets
public void Deactivate(SnippetEventArgs e)
{
+ TargetElement.TextChanged -= targetElement_TextChanged;
}
public bool IsEditable => false;
| 1 | Merge pull request #40 from danwalmsley/snippet-returns-context | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057674 | <NME> SnippetBoundElement.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 AvaloniaEdit.Document;
namespace AvaloniaEdit.Snippets
{
/// <summary>
/// An element that binds to a <see cref="SnippetReplaceableTextElement"/> and displays the same text.
/// </summary>
public class SnippetBoundElement : SnippetElement
{
/// <summary>
/// Gets/Sets the target element.
/// </summary>
public SnippetReplaceableTextElement TargetElement { get; set; }
/// <summary>
/// Converts the text before copying it.
/// </summary>
public virtual string ConvertText(string input)
{
return input;
}
/// <inheritdoc/>
public override void Insert(InsertionContext context)
{
if (TargetElement != null)
{
var start = context.Document.CreateAnchor(context.InsertionPosition);
start.MovementType = AnchorMovementType.BeforeInsertion;
start.SurviveDeletion = true;
var inputText = TargetElement.Text;
if (inputText != null)
{
context.InsertText(ConvertText(inputText));
}
var end = context.Document.CreateAnchor(context.InsertionPosition);
end.MovementType = AnchorMovementType.BeforeInsertion;
end.SurviveDeletion = true;
var segment = new AnchorSegment(start, end);
context.RegisterActiveElement(this, new BoundActiveElement(context, TargetElement, this, segment));
}
}
///// <inheritdoc/>
//public override Inline ToTextRun()
//{
// if (TargetElement != null) {
// string inputText = TargetElement.Text;
// if (inputText != null) {
// return new Italic(new Run(ConvertText(inputText)));
// }
// }
// return base.ToTextRun();
//}
}
internal sealed class BoundActiveElement : IActiveElement
{
private readonly InsertionContext _context;
private readonly SnippetReplaceableTextElement _targetSnippetElement;
private readonly SnippetBoundElement _boundElement;
internal IReplaceableActiveElement TargetElement;
private AnchorSegment _segment;
public BoundActiveElement(InsertionContext context, SnippetReplaceableTextElement targetSnippetElement, SnippetBoundElement boundElement, AnchorSegment segment)
{
_context = context;
_targetSnippetElement = targetSnippetElement;
_boundElement = boundElement;
_segment = segment;
}
public void OnInsertionCompleted()
{
TargetElement = _context.GetActiveElement(_targetSnippetElement) as IReplaceableActiveElement;
if (TargetElement != null)
{
TargetElement.TextChanged += targetElement_TextChanged;
}
}
private void targetElement_TextChanged(object sender, EventArgs e)
{
// Don't copy text if the segments overlap (we would get an endless loop).
// This can happen if the user deletes the text between the replaceable element and the bound element.
if (SimpleSegment.GetOverlap(_segment, TargetElement.Segment) == SimpleSegment.Invalid)
{
var offset = _segment.Offset;
var length = _segment.Length;
var text = _boundElement.ConvertText(TargetElement.Text);
if (length != text.Length || text != _context.Document.GetText(offset, length))
{
// Call replace only if we're actually changing something.
// Without this check, we would generate an empty undo group when the user pressed undo.
_context.Document.Replace(offset, length, text);
if (length == 0)
{
// replacing an empty anchor segment with text won't enlarge it, so we have to recreate it
_segment = new AnchorSegment(_context.Document, offset, text.Length);
}
}
}
}
public void Deactivate(SnippetEventArgs e)
{
}
public bool IsEditable => false;
public ISegment Segment => _segment;
}
}
<MSG> Merge pull request #40 from danwalmsley/snippet-returns-context
Snippet returns context
<DFF> @@ -123,6 +123,7 @@ namespace AvaloniaEdit.Snippets
public void Deactivate(SnippetEventArgs e)
{
+ TargetElement.TextChanged -= targetElement_TextChanged;
}
public bool IsEditable => false;
| 1 | Merge pull request #40 from danwalmsley/snippet-returns-context | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057675 | <NME> SnippetBoundElement.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 AvaloniaEdit.Document;
namespace AvaloniaEdit.Snippets
{
/// <summary>
/// An element that binds to a <see cref="SnippetReplaceableTextElement"/> and displays the same text.
/// </summary>
public class SnippetBoundElement : SnippetElement
{
/// <summary>
/// Gets/Sets the target element.
/// </summary>
public SnippetReplaceableTextElement TargetElement { get; set; }
/// <summary>
/// Converts the text before copying it.
/// </summary>
public virtual string ConvertText(string input)
{
return input;
}
/// <inheritdoc/>
public override void Insert(InsertionContext context)
{
if (TargetElement != null)
{
var start = context.Document.CreateAnchor(context.InsertionPosition);
start.MovementType = AnchorMovementType.BeforeInsertion;
start.SurviveDeletion = true;
var inputText = TargetElement.Text;
if (inputText != null)
{
context.InsertText(ConvertText(inputText));
}
var end = context.Document.CreateAnchor(context.InsertionPosition);
end.MovementType = AnchorMovementType.BeforeInsertion;
end.SurviveDeletion = true;
var segment = new AnchorSegment(start, end);
context.RegisterActiveElement(this, new BoundActiveElement(context, TargetElement, this, segment));
}
}
///// <inheritdoc/>
//public override Inline ToTextRun()
//{
// if (TargetElement != null) {
// string inputText = TargetElement.Text;
// if (inputText != null) {
// return new Italic(new Run(ConvertText(inputText)));
// }
// }
// return base.ToTextRun();
//}
}
internal sealed class BoundActiveElement : IActiveElement
{
private readonly InsertionContext _context;
private readonly SnippetReplaceableTextElement _targetSnippetElement;
private readonly SnippetBoundElement _boundElement;
internal IReplaceableActiveElement TargetElement;
private AnchorSegment _segment;
public BoundActiveElement(InsertionContext context, SnippetReplaceableTextElement targetSnippetElement, SnippetBoundElement boundElement, AnchorSegment segment)
{
_context = context;
_targetSnippetElement = targetSnippetElement;
_boundElement = boundElement;
_segment = segment;
}
public void OnInsertionCompleted()
{
TargetElement = _context.GetActiveElement(_targetSnippetElement) as IReplaceableActiveElement;
if (TargetElement != null)
{
TargetElement.TextChanged += targetElement_TextChanged;
}
}
private void targetElement_TextChanged(object sender, EventArgs e)
{
// Don't copy text if the segments overlap (we would get an endless loop).
// This can happen if the user deletes the text between the replaceable element and the bound element.
if (SimpleSegment.GetOverlap(_segment, TargetElement.Segment) == SimpleSegment.Invalid)
{
var offset = _segment.Offset;
var length = _segment.Length;
var text = _boundElement.ConvertText(TargetElement.Text);
if (length != text.Length || text != _context.Document.GetText(offset, length))
{
// Call replace only if we're actually changing something.
// Without this check, we would generate an empty undo group when the user pressed undo.
_context.Document.Replace(offset, length, text);
if (length == 0)
{
// replacing an empty anchor segment with text won't enlarge it, so we have to recreate it
_segment = new AnchorSegment(_context.Document, offset, text.Length);
}
}
}
}
public void Deactivate(SnippetEventArgs e)
{
}
public bool IsEditable => false;
public ISegment Segment => _segment;
}
}
<MSG> Merge pull request #40 from danwalmsley/snippet-returns-context
Snippet returns context
<DFF> @@ -123,6 +123,7 @@ namespace AvaloniaEdit.Snippets
public void Deactivate(SnippetEventArgs e)
{
+ TargetElement.TextChanged -= targetElement_TextChanged;
}
public bool IsEditable => false;
| 1 | Merge pull request #40 from danwalmsley/snippet-returns-context | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057676 | <NME> SnippetBoundElement.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 AvaloniaEdit.Document;
namespace AvaloniaEdit.Snippets
{
/// <summary>
/// An element that binds to a <see cref="SnippetReplaceableTextElement"/> and displays the same text.
/// </summary>
public class SnippetBoundElement : SnippetElement
{
/// <summary>
/// Gets/Sets the target element.
/// </summary>
public SnippetReplaceableTextElement TargetElement { get; set; }
/// <summary>
/// Converts the text before copying it.
/// </summary>
public virtual string ConvertText(string input)
{
return input;
}
/// <inheritdoc/>
public override void Insert(InsertionContext context)
{
if (TargetElement != null)
{
var start = context.Document.CreateAnchor(context.InsertionPosition);
start.MovementType = AnchorMovementType.BeforeInsertion;
start.SurviveDeletion = true;
var inputText = TargetElement.Text;
if (inputText != null)
{
context.InsertText(ConvertText(inputText));
}
var end = context.Document.CreateAnchor(context.InsertionPosition);
end.MovementType = AnchorMovementType.BeforeInsertion;
end.SurviveDeletion = true;
var segment = new AnchorSegment(start, end);
context.RegisterActiveElement(this, new BoundActiveElement(context, TargetElement, this, segment));
}
}
///// <inheritdoc/>
//public override Inline ToTextRun()
//{
// if (TargetElement != null) {
// string inputText = TargetElement.Text;
// if (inputText != null) {
// return new Italic(new Run(ConvertText(inputText)));
// }
// }
// return base.ToTextRun();
//}
}
internal sealed class BoundActiveElement : IActiveElement
{
private readonly InsertionContext _context;
private readonly SnippetReplaceableTextElement _targetSnippetElement;
private readonly SnippetBoundElement _boundElement;
internal IReplaceableActiveElement TargetElement;
private AnchorSegment _segment;
public BoundActiveElement(InsertionContext context, SnippetReplaceableTextElement targetSnippetElement, SnippetBoundElement boundElement, AnchorSegment segment)
{
_context = context;
_targetSnippetElement = targetSnippetElement;
_boundElement = boundElement;
_segment = segment;
}
public void OnInsertionCompleted()
{
TargetElement = _context.GetActiveElement(_targetSnippetElement) as IReplaceableActiveElement;
if (TargetElement != null)
{
TargetElement.TextChanged += targetElement_TextChanged;
}
}
private void targetElement_TextChanged(object sender, EventArgs e)
{
// Don't copy text if the segments overlap (we would get an endless loop).
// This can happen if the user deletes the text between the replaceable element and the bound element.
if (SimpleSegment.GetOverlap(_segment, TargetElement.Segment) == SimpleSegment.Invalid)
{
var offset = _segment.Offset;
var length = _segment.Length;
var text = _boundElement.ConvertText(TargetElement.Text);
if (length != text.Length || text != _context.Document.GetText(offset, length))
{
// Call replace only if we're actually changing something.
// Without this check, we would generate an empty undo group when the user pressed undo.
_context.Document.Replace(offset, length, text);
if (length == 0)
{
// replacing an empty anchor segment with text won't enlarge it, so we have to recreate it
_segment = new AnchorSegment(_context.Document, offset, text.Length);
}
}
}
}
public void Deactivate(SnippetEventArgs e)
{
}
public bool IsEditable => false;
public ISegment Segment => _segment;
}
}
<MSG> Merge pull request #40 from danwalmsley/snippet-returns-context
Snippet returns context
<DFF> @@ -123,6 +123,7 @@ namespace AvaloniaEdit.Snippets
public void Deactivate(SnippetEventArgs e)
{
+ TargetElement.TextChanged -= targetElement_TextChanged;
}
public bool IsEditable => false;
| 1 | Merge pull request #40 from danwalmsley/snippet-returns-context | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057677 | <NME> SnippetBoundElement.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 AvaloniaEdit.Document;
namespace AvaloniaEdit.Snippets
{
/// <summary>
/// An element that binds to a <see cref="SnippetReplaceableTextElement"/> and displays the same text.
/// </summary>
public class SnippetBoundElement : SnippetElement
{
/// <summary>
/// Gets/Sets the target element.
/// </summary>
public SnippetReplaceableTextElement TargetElement { get; set; }
/// <summary>
/// Converts the text before copying it.
/// </summary>
public virtual string ConvertText(string input)
{
return input;
}
/// <inheritdoc/>
public override void Insert(InsertionContext context)
{
if (TargetElement != null)
{
var start = context.Document.CreateAnchor(context.InsertionPosition);
start.MovementType = AnchorMovementType.BeforeInsertion;
start.SurviveDeletion = true;
var inputText = TargetElement.Text;
if (inputText != null)
{
context.InsertText(ConvertText(inputText));
}
var end = context.Document.CreateAnchor(context.InsertionPosition);
end.MovementType = AnchorMovementType.BeforeInsertion;
end.SurviveDeletion = true;
var segment = new AnchorSegment(start, end);
context.RegisterActiveElement(this, new BoundActiveElement(context, TargetElement, this, segment));
}
}
///// <inheritdoc/>
//public override Inline ToTextRun()
//{
// if (TargetElement != null) {
// string inputText = TargetElement.Text;
// if (inputText != null) {
// return new Italic(new Run(ConvertText(inputText)));
// }
// }
// return base.ToTextRun();
//}
}
internal sealed class BoundActiveElement : IActiveElement
{
private readonly InsertionContext _context;
private readonly SnippetReplaceableTextElement _targetSnippetElement;
private readonly SnippetBoundElement _boundElement;
internal IReplaceableActiveElement TargetElement;
private AnchorSegment _segment;
public BoundActiveElement(InsertionContext context, SnippetReplaceableTextElement targetSnippetElement, SnippetBoundElement boundElement, AnchorSegment segment)
{
_context = context;
_targetSnippetElement = targetSnippetElement;
_boundElement = boundElement;
_segment = segment;
}
public void OnInsertionCompleted()
{
TargetElement = _context.GetActiveElement(_targetSnippetElement) as IReplaceableActiveElement;
if (TargetElement != null)
{
TargetElement.TextChanged += targetElement_TextChanged;
}
}
private void targetElement_TextChanged(object sender, EventArgs e)
{
// Don't copy text if the segments overlap (we would get an endless loop).
// This can happen if the user deletes the text between the replaceable element and the bound element.
if (SimpleSegment.GetOverlap(_segment, TargetElement.Segment) == SimpleSegment.Invalid)
{
var offset = _segment.Offset;
var length = _segment.Length;
var text = _boundElement.ConvertText(TargetElement.Text);
if (length != text.Length || text != _context.Document.GetText(offset, length))
{
// Call replace only if we're actually changing something.
// Without this check, we would generate an empty undo group when the user pressed undo.
_context.Document.Replace(offset, length, text);
if (length == 0)
{
// replacing an empty anchor segment with text won't enlarge it, so we have to recreate it
_segment = new AnchorSegment(_context.Document, offset, text.Length);
}
}
}
}
public void Deactivate(SnippetEventArgs e)
{
}
public bool IsEditable => false;
public ISegment Segment => _segment;
}
}
<MSG> Merge pull request #40 from danwalmsley/snippet-returns-context
Snippet returns context
<DFF> @@ -123,6 +123,7 @@ namespace AvaloniaEdit.Snippets
public void Deactivate(SnippetEventArgs e)
{
+ TargetElement.TextChanged -= targetElement_TextChanged;
}
public bool IsEditable => false;
| 1 | Merge pull request #40 from danwalmsley/snippet-returns-context | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057678 | <NME> database.js
<BEF>
/**
* Dummy Data Stores
*/
var database = {};
// Mock synchronous API
database.getSync = function() {
return [
{
id: 'article1',
title: 'Article 1'
},
{
id: 'article2',
title: 'Article 2'
},
{
id: 'article3',
title: 'Article 3'
},
{
id: 'article4',
title: 'Article 4'
},
{
id: 'article5',
title: 'Article 5'
}
];
};
// Mock asynchonous API
database.getAsync = function(id, callback) {
var database = {
article1: {
date: '3rd May 2012',
title: 'Article 1',
body: "<p>Big girl's blouse soft southern pansy cack-handed. Tha knows bloomin' 'eck. Is that thine t'foot o' our stairs. Cack-handed big girl's blouse dahn t'coil oil gerritetten. Appens as maybe shurrup where there's muck there's brass big girl's blouse breadcake. Shu' thi gob how much t'foot o' our stairs th'art nesh thee. A pint 'o mild nah then aye gi' o'er ah'll learn thi th'art nesh thee. Appens as maybe. Gi' o'er ey up. Ee by gum ey up shurrup eeh aye. Tha daft apeth where there's muck there's brass big girl's blouse nobbut a lad aye. Shu' thi gob ah'll box thi ears cack-handed. Nay lad. Bloomin' 'eck tintintin.</p>",
author: 'John Smith'
},
article2: {
date: '13th August 2012',
title: 'Article 2',
body: "<p>What's that when it's at ooam nah then t'foot o' our stairs tintintin. Eeh soft lad soft lad aye. Shu' thi gob what's that when it's at ooam chuffin' nora where's tha bin ee by gum be reet. What's that when it's at ooam soft lad wacken thi sen up mardy bum ne'ermind. Nay lad bloomin' 'eck ee by gum nay lad. Where there's muck there's brass mardy bum what's that when it's at ooam tell thi summat for nowt. Sup wi' 'im is that thine tell thi summat for nowt. Ey up wacken thi sen up nay lad ah'll box thi ears. Wacken thi sen up nobbut a lad shurrup what's that when it's at ooam. Where's tha bin tha what dahn t'coil oil dahn t'coil oil. Ne'ermind th'art nesh thee cack-handed chuffin' nora nah then mardy bum. Ne'ermind nah then.</p>",
author: 'John Smith'
},
article3: {
date: '27th July 2012',
title: 'Article 3',
body: "<p>Tha daft apeth nobbut a lad big girl's blouse gi' o'er chuffin' nora. Tell thi summat for nowt. Th'art nesh thee will 'e 'eckerslike will 'e 'eckerslike shurrup where there's muck there's brass. Ah'll gi' thi summat to rooer abaht michael palin. Soft lad by 'eck ah'll gi' thee a thick ear. Where there's muck there's brass th'art nesh thee shu' thi gob nah then. Nah then breadcake michael palin. Aye shu' thi gob how much nah then. Ah'll gi' thi summat to rooer abaht shurrup how much. Aye ne'ermind t'foot o' our stairs th'art nesh thee.</p>",
author: 'John Smith'
},
article4: {
date: '6th March 2013',
title: 'Article 4',
body: "<p>Th'art nesh thee dahn t'coil oil what's that when it's at ooam. Tell thi summat for nowt. Soft southern pansy michael palin any rooad. Ah'll gi' thee a thick ear ah'll gi' thi summat to rooer abaht ah'll learn thi bloomin' 'eck ne'ermind michael palin. Bobbar bloomin' 'eck tintintin sup wi' 'im gi' o'er bloomin' 'eck. Ah'll box thi ears bloomin' 'eck tha knows be reet breadcake appens as maybe. T'foot o' our stairs gi' o'er aye shurrup tell thi summat for nowt that's champion. Ee by gum face like a slapped arse where there's muck there's brass michael palin what's that when it's at ooam. God's own county ah'll box thi ears. Cack-handed appens as maybe shu' thi gob god's own county be reet.</p>",
author: 'John Smith'
},
article5: {
date: '24th December 2012',
title: 'Article 5',
body: '<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium.</p>',
author: 'John Smith'
}
};
setTimeout(function() {
callback(database[id]);
}, 100);
};
<MSG> Merge pull request #91 from debugwand/patch-1
Update database.js
<DFF> @@ -37,25 +37,25 @@ database.getAsync = function(id, callback) {
article1: {
date: '3rd May 2012',
title: 'Article 1',
- body: "<p>Big girl's blouse soft southern pansy cack-handed. Tha knows bloomin' 'eck. Is that thine t'foot o' our stairs. Cack-handed big girl's blouse dahn t'coil oil gerritetten. Appens as maybe shurrup where there's muck there's brass big girl's blouse breadcake. Shu' thi gob how much t'foot o' our stairs th'art nesh thee. A pint 'o mild nah then aye gi' o'er ah'll learn thi th'art nesh thee. Appens as maybe. Gi' o'er ey up. Ee by gum ey up shurrup eeh aye. Tha daft apeth where there's muck there's brass big girl's blouse nobbut a lad aye. Shu' thi gob ah'll box thi ears cack-handed. Nay lad. Bloomin' 'eck tintintin.</p>",
+ body: "<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam volutpat sem dictum, bibendum orci sed, auctor nulla. Nullam mauris eros, lobortis quis mi quis, commodo pellentesque dolor. Fusce purus odio, rutrum id malesuada in, volutpat ut augue. Vivamus in neque posuere, porta ipsum sed, lacinia sem. In tortor turpis, rhoncus consequat elit nec, condimentum accumsan ipsum. Vestibulum sed pellentesque urna. Duis rutrum pulvinar accumsan. Integer sagittis ante enim, ac porttitor ligula rutrum quis.</p>",
author: 'John Smith'
},
article2: {
date: '13th August 2012',
title: 'Article 2',
- body: "<p>What's that when it's at ooam nah then t'foot o' our stairs tintintin. Eeh soft lad soft lad aye. Shu' thi gob what's that when it's at ooam chuffin' nora where's tha bin ee by gum be reet. What's that when it's at ooam soft lad wacken thi sen up mardy bum ne'ermind. Nay lad bloomin' 'eck ee by gum nay lad. Where there's muck there's brass mardy bum what's that when it's at ooam tell thi summat for nowt. Sup wi' 'im is that thine tell thi summat for nowt. Ey up wacken thi sen up nay lad ah'll box thi ears. Wacken thi sen up nobbut a lad shurrup what's that when it's at ooam. Where's tha bin tha what dahn t'coil oil dahn t'coil oil. Ne'ermind th'art nesh thee cack-handed chuffin' nora nah then mardy bum. Ne'ermind nah then.</p>",
+ body: "<p>Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Integer vulputate aliquet quam at aliquam. Praesent pellentesque mauris ut augue congue, sit amet mattis sapien ultrices. Phasellus at semper massa. Pellentesque sollicitudin egestas enim ac rhoncus. Vestibulum quis vehicula turpis, hendrerit dapibus nunc. Etiam eget libero efficitur, vehicula risus id, efficitur neque. Maecenas accumsan tincidunt ultrices. Vestibulum sagittis, felis sed commodo pharetra, velit dolor congue velit, nec porta leo leo sit amet neque. Donec imperdiet porttitor neque, eget faucibus odio eleifend ut.</p>",
author: 'John Smith'
},
article3: {
date: '27th July 2012',
title: 'Article 3',
- body: "<p>Tha daft apeth nobbut a lad big girl's blouse gi' o'er chuffin' nora. Tell thi summat for nowt. Th'art nesh thee will 'e 'eckerslike will 'e 'eckerslike shurrup where there's muck there's brass. Ah'll gi' thi summat to rooer abaht michael palin. Soft lad by 'eck ah'll gi' thee a thick ear. Where there's muck there's brass th'art nesh thee shu' thi gob nah then. Nah then breadcake michael palin. Aye shu' thi gob how much nah then. Ah'll gi' thi summat to rooer abaht shurrup how much. Aye ne'ermind t'foot o' our stairs th'art nesh thee.</p>",
+ body: "<p>Curabitur eget feugiat leo. Nulla lorem nisl, malesuada vel erat eu, mattis viverra magna. Praesent facilisis ornare tristique. Sed congue accumsan lacus, non consequat augue hendrerit et. Maecenas imperdiet placerat leo, sed auctor neque suscipit eget. Aliquam a porttitor massa. Quisque porttitor sed urna eget auctor.</p>",
author: 'John Smith'
},
article4: {
date: '6th March 2013',
title: 'Article 4',
- body: "<p>Th'art nesh thee dahn t'coil oil what's that when it's at ooam. Tell thi summat for nowt. Soft southern pansy michael palin any rooad. Ah'll gi' thee a thick ear ah'll gi' thi summat to rooer abaht ah'll learn thi bloomin' 'eck ne'ermind michael palin. Bobbar bloomin' 'eck tintintin sup wi' 'im gi' o'er bloomin' 'eck. Ah'll box thi ears bloomin' 'eck tha knows be reet breadcake appens as maybe. T'foot o' our stairs gi' o'er aye shurrup tell thi summat for nowt that's champion. Ee by gum face like a slapped arse where there's muck there's brass michael palin what's that when it's at ooam. God's own county ah'll box thi ears. Cack-handed appens as maybe shu' thi gob god's own county be reet.</p>",
+ body: "<p>Vestibulum consectetur, nunc sit amet sodales pharetra, arcu diam molestie ante, ac viverra erat justo id velit. Maecenas consequat fringilla lectus, id pretium ipsum viverra quis. Sed tortor urna, tincidunt ac laoreet eu, finibus finibus sem. Pellentesque venenatis risus sem, eu lacinia neque fermentum eu. In at dui ut odio elementum venenatis at eu tortor. Curabitur vel dui felis. Maecenas sollicitudin, erat sit amet facilisis vehicula, dolor lectus mattis libero, in sagittis justo lorem et libero. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Vestibulum tincidunt ante eget ex gravida, vitae bibendum urna fermentum. Donec commodo magna vel malesuada volutpat. Etiam in ipsum nec est eleifend euismod. Mauris a justo justo. Aenean pulvinar aliquam ligula, at bibendum velit imperdiet at. Etiam euismod tristique ex quis placerat. Morbi mi lorem, cursus in tempus vitae, mollis in risus.</p>",
author: 'John Smith'
},
article5: {
@@ -69,4 +69,4 @@ database.getAsync = function(id, callback) {
setTimeout(function() {
callback(database[id]);
}, 100);
-};
\ No newline at end of file
+};
| 5 | Merge pull request #91 from debugwand/patch-1 | 5 | .js | js | mit | ftlabs/fruitmachine |
10057679 | <NME> RoutedCommand.cs
<BEF> using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Input;
using Avalonia;
using Avalonia.Input;
using Avalonia.Interactivity;
namespace AvaloniaEdit
{
public class RoutedCommand : ICommand
{
public string Name { get; }
public KeyGesture Gesture { get; }
public RoutedCommand(string name, KeyGesture keyGesture = null)
{
Name = name;
Gesture = keyGesture;
}
static RoutedCommand()
{
CanExecuteEvent.AddClassHandler<IRoutedCommandBindable>(CanExecuteEventHandler);
ExecutedEvent.AddClassHandler<IRoutedCommandBindable>(ExecutedEventHandler);
}
private static Action<CanExecuteRoutedEventArgs> CanExecuteEventHandler(IRoutedCommandBindable control)
{
return args =>
{
var binding = control.CommandBindings.Where(c => c != null)
.FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
args.CanExecute = binding != null;
};
}
private static Action<ExecutedRoutedEventArgs> ExecutedEventHandler(IRoutedCommandBindable control)
{
return args =>
{
// ReSharper disable once UnusedVariable
var binding = control.CommandBindings.Where(c => c != null)
.FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
};
}
public static RoutedEvent<CanExecuteRoutedEventArgs> CanExecuteEvent { get; } = RoutedEvent.Register<CanExecuteRoutedEventArgs>(nameof(CanExecuteEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
public bool CanExecute(object parameter, IInputElement target)
{
if (target == null) return false;
var args = new CanExecuteRoutedEventArgs(this, parameter);
target.RaiseEvent(args);
return args.CanExecute;
}
bool ICommand.CanExecute(object parameter)
{
return CanExecute(parameter, Application.Current.FocusManager.Current);
}
public static RoutedEvent<ExecutedRoutedEventArgs> ExecutedEvent { get; } = RoutedEvent.Register<ExecutedRoutedEventArgs>(nameof(ExecutedEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
public void Execute(object parameter, IInputElement target)
{
if (target == null) return;
var args = new ExecutedRoutedEventArgs(this, parameter);
target.RaiseEvent(args);
}
void ICommand.Execute(object parameter)
{
Execute(parameter, Application.Current.FocusManager.Current);
}
// TODO
event EventHandler ICommand.CanExecuteChanged
{
add { }
remove { }
}
}
public interface IRoutedCommandBindable : IInteractive
{
IList<RoutedCommandBinding> CommandBindings { get; }
}
public class RoutedCommandBinding
{
public RoutedCommandBinding(RoutedCommand command,
EventHandler<ExecutedRoutedEventArgs> executed = null,
EventHandler<CanExecuteRoutedEventArgs> canExecute = null)
{
Command = command;
if (executed != null) Executed += executed;
if (canExecute != null) CanExecute += canExecute;
}
public RoutedCommand Command { get; }
public event EventHandler<CanExecuteRoutedEventArgs> CanExecute;
public event EventHandler<ExecutedRoutedEventArgs> Executed;
internal bool DoCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
if (e.Handled) return true;
var canExecute = CanExecute;
if (canExecute == null)
{
if (Executed != null)
{
e.Handled = true;
e.CanExecute = true;
}
}
else
{
canExecute(sender, e);
if (e.CanExecute)
{
e.Handled = true;
}
}
return e.CanExecute;
}
internal bool DoExecuted(object sender, ExecutedRoutedEventArgs e)
{
if (!e.Handled)
{
var executed = Executed;
if (executed != null)
{
if (DoCanExecute(sender, new CanExecuteRoutedEventArgs(e.Command, e.Parameter)))
{
executed(sender, e);
e.Handled = true;
return true;
}
}
}
return false;
}
}
public sealed class CanExecuteRoutedEventArgs : RoutedEventArgs
{
public ICommand Command { get; }
public object Parameter { get; }
public bool CanExecute { get; set; }
internal CanExecuteRoutedEventArgs(ICommand command, object parameter)
{
Command = command ?? throw new ArgumentNullException(nameof(command));
Parameter = parameter;
RoutedEvent = RoutedCommand.CanExecuteEvent;
}
}
public sealed class ExecutedRoutedEventArgs : RoutedEventArgs
{
public ICommand Command { get; }
public object Parameter { get; }
internal ExecutedRoutedEventArgs(ICommand command, object parameter)
{
Command = command ?? throw new ArgumentNullException(nameof(command));
Parameter = parameter;
RoutedEvent = RoutedCommand.ExecutedEvent;
}
}
}
<MSG> Merge pull request #203 from HendrikMennen/fixobsolete
Replace obsolete methods
<DFF> @@ -25,24 +25,18 @@ namespace AvaloniaEdit
ExecutedEvent.AddClassHandler<IRoutedCommandBindable>(ExecutedEventHandler);
}
- private static Action<CanExecuteRoutedEventArgs> CanExecuteEventHandler(IRoutedCommandBindable control)
+ private static void CanExecuteEventHandler(IRoutedCommandBindable control, CanExecuteRoutedEventArgs args)
{
- return args =>
- {
- var binding = control.CommandBindings.Where(c => c != null)
- .FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
- args.CanExecute = binding != null;
- };
+ var binding = control.CommandBindings.Where(c => c != null)
+ .FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
+ args.CanExecute = binding != null;
}
- private static Action<ExecutedRoutedEventArgs> ExecutedEventHandler(IRoutedCommandBindable control)
+ private static void ExecutedEventHandler(IRoutedCommandBindable control, ExecutedRoutedEventArgs args)
{
- return args =>
- {
- // ReSharper disable once UnusedVariable
- var binding = control.CommandBindings.Where(c => c != null)
- .FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
- };
+ // ReSharper disable once UnusedVariable
+ var binding = control.CommandBindings.Where(c => c != null)
+ .FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
}
public static RoutedEvent<CanExecuteRoutedEventArgs> CanExecuteEvent { get; } = RoutedEvent.Register<CanExecuteRoutedEventArgs>(nameof(CanExecuteEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
| 8 | Merge pull request #203 from HendrikMennen/fixobsolete | 14 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057680 | <NME> RoutedCommand.cs
<BEF> using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Input;
using Avalonia;
using Avalonia.Input;
using Avalonia.Interactivity;
namespace AvaloniaEdit
{
public class RoutedCommand : ICommand
{
public string Name { get; }
public KeyGesture Gesture { get; }
public RoutedCommand(string name, KeyGesture keyGesture = null)
{
Name = name;
Gesture = keyGesture;
}
static RoutedCommand()
{
CanExecuteEvent.AddClassHandler<IRoutedCommandBindable>(CanExecuteEventHandler);
ExecutedEvent.AddClassHandler<IRoutedCommandBindable>(ExecutedEventHandler);
}
private static Action<CanExecuteRoutedEventArgs> CanExecuteEventHandler(IRoutedCommandBindable control)
{
return args =>
{
var binding = control.CommandBindings.Where(c => c != null)
.FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
args.CanExecute = binding != null;
};
}
private static Action<ExecutedRoutedEventArgs> ExecutedEventHandler(IRoutedCommandBindable control)
{
return args =>
{
// ReSharper disable once UnusedVariable
var binding = control.CommandBindings.Where(c => c != null)
.FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
};
}
public static RoutedEvent<CanExecuteRoutedEventArgs> CanExecuteEvent { get; } = RoutedEvent.Register<CanExecuteRoutedEventArgs>(nameof(CanExecuteEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
public bool CanExecute(object parameter, IInputElement target)
{
if (target == null) return false;
var args = new CanExecuteRoutedEventArgs(this, parameter);
target.RaiseEvent(args);
return args.CanExecute;
}
bool ICommand.CanExecute(object parameter)
{
return CanExecute(parameter, Application.Current.FocusManager.Current);
}
public static RoutedEvent<ExecutedRoutedEventArgs> ExecutedEvent { get; } = RoutedEvent.Register<ExecutedRoutedEventArgs>(nameof(ExecutedEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
public void Execute(object parameter, IInputElement target)
{
if (target == null) return;
var args = new ExecutedRoutedEventArgs(this, parameter);
target.RaiseEvent(args);
}
void ICommand.Execute(object parameter)
{
Execute(parameter, Application.Current.FocusManager.Current);
}
// TODO
event EventHandler ICommand.CanExecuteChanged
{
add { }
remove { }
}
}
public interface IRoutedCommandBindable : IInteractive
{
IList<RoutedCommandBinding> CommandBindings { get; }
}
public class RoutedCommandBinding
{
public RoutedCommandBinding(RoutedCommand command,
EventHandler<ExecutedRoutedEventArgs> executed = null,
EventHandler<CanExecuteRoutedEventArgs> canExecute = null)
{
Command = command;
if (executed != null) Executed += executed;
if (canExecute != null) CanExecute += canExecute;
}
public RoutedCommand Command { get; }
public event EventHandler<CanExecuteRoutedEventArgs> CanExecute;
public event EventHandler<ExecutedRoutedEventArgs> Executed;
internal bool DoCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
if (e.Handled) return true;
var canExecute = CanExecute;
if (canExecute == null)
{
if (Executed != null)
{
e.Handled = true;
e.CanExecute = true;
}
}
else
{
canExecute(sender, e);
if (e.CanExecute)
{
e.Handled = true;
}
}
return e.CanExecute;
}
internal bool DoExecuted(object sender, ExecutedRoutedEventArgs e)
{
if (!e.Handled)
{
var executed = Executed;
if (executed != null)
{
if (DoCanExecute(sender, new CanExecuteRoutedEventArgs(e.Command, e.Parameter)))
{
executed(sender, e);
e.Handled = true;
return true;
}
}
}
return false;
}
}
public sealed class CanExecuteRoutedEventArgs : RoutedEventArgs
{
public ICommand Command { get; }
public object Parameter { get; }
public bool CanExecute { get; set; }
internal CanExecuteRoutedEventArgs(ICommand command, object parameter)
{
Command = command ?? throw new ArgumentNullException(nameof(command));
Parameter = parameter;
RoutedEvent = RoutedCommand.CanExecuteEvent;
}
}
public sealed class ExecutedRoutedEventArgs : RoutedEventArgs
{
public ICommand Command { get; }
public object Parameter { get; }
internal ExecutedRoutedEventArgs(ICommand command, object parameter)
{
Command = command ?? throw new ArgumentNullException(nameof(command));
Parameter = parameter;
RoutedEvent = RoutedCommand.ExecutedEvent;
}
}
}
<MSG> Merge pull request #203 from HendrikMennen/fixobsolete
Replace obsolete methods
<DFF> @@ -25,24 +25,18 @@ namespace AvaloniaEdit
ExecutedEvent.AddClassHandler<IRoutedCommandBindable>(ExecutedEventHandler);
}
- private static Action<CanExecuteRoutedEventArgs> CanExecuteEventHandler(IRoutedCommandBindable control)
+ private static void CanExecuteEventHandler(IRoutedCommandBindable control, CanExecuteRoutedEventArgs args)
{
- return args =>
- {
- var binding = control.CommandBindings.Where(c => c != null)
- .FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
- args.CanExecute = binding != null;
- };
+ var binding = control.CommandBindings.Where(c => c != null)
+ .FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
+ args.CanExecute = binding != null;
}
- private static Action<ExecutedRoutedEventArgs> ExecutedEventHandler(IRoutedCommandBindable control)
+ private static void ExecutedEventHandler(IRoutedCommandBindable control, ExecutedRoutedEventArgs args)
{
- return args =>
- {
- // ReSharper disable once UnusedVariable
- var binding = control.CommandBindings.Where(c => c != null)
- .FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
- };
+ // ReSharper disable once UnusedVariable
+ var binding = control.CommandBindings.Where(c => c != null)
+ .FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
}
public static RoutedEvent<CanExecuteRoutedEventArgs> CanExecuteEvent { get; } = RoutedEvent.Register<CanExecuteRoutedEventArgs>(nameof(CanExecuteEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
| 8 | Merge pull request #203 from HendrikMennen/fixobsolete | 14 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057681 | <NME> RoutedCommand.cs
<BEF> using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Input;
using Avalonia;
using Avalonia.Input;
using Avalonia.Interactivity;
namespace AvaloniaEdit
{
public class RoutedCommand : ICommand
{
public string Name { get; }
public KeyGesture Gesture { get; }
public RoutedCommand(string name, KeyGesture keyGesture = null)
{
Name = name;
Gesture = keyGesture;
}
static RoutedCommand()
{
CanExecuteEvent.AddClassHandler<IRoutedCommandBindable>(CanExecuteEventHandler);
ExecutedEvent.AddClassHandler<IRoutedCommandBindable>(ExecutedEventHandler);
}
private static Action<CanExecuteRoutedEventArgs> CanExecuteEventHandler(IRoutedCommandBindable control)
{
return args =>
{
var binding = control.CommandBindings.Where(c => c != null)
.FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
args.CanExecute = binding != null;
};
}
private static Action<ExecutedRoutedEventArgs> ExecutedEventHandler(IRoutedCommandBindable control)
{
return args =>
{
// ReSharper disable once UnusedVariable
var binding = control.CommandBindings.Where(c => c != null)
.FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
};
}
public static RoutedEvent<CanExecuteRoutedEventArgs> CanExecuteEvent { get; } = RoutedEvent.Register<CanExecuteRoutedEventArgs>(nameof(CanExecuteEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
public bool CanExecute(object parameter, IInputElement target)
{
if (target == null) return false;
var args = new CanExecuteRoutedEventArgs(this, parameter);
target.RaiseEvent(args);
return args.CanExecute;
}
bool ICommand.CanExecute(object parameter)
{
return CanExecute(parameter, Application.Current.FocusManager.Current);
}
public static RoutedEvent<ExecutedRoutedEventArgs> ExecutedEvent { get; } = RoutedEvent.Register<ExecutedRoutedEventArgs>(nameof(ExecutedEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
public void Execute(object parameter, IInputElement target)
{
if (target == null) return;
var args = new ExecutedRoutedEventArgs(this, parameter);
target.RaiseEvent(args);
}
void ICommand.Execute(object parameter)
{
Execute(parameter, Application.Current.FocusManager.Current);
}
// TODO
event EventHandler ICommand.CanExecuteChanged
{
add { }
remove { }
}
}
public interface IRoutedCommandBindable : IInteractive
{
IList<RoutedCommandBinding> CommandBindings { get; }
}
public class RoutedCommandBinding
{
public RoutedCommandBinding(RoutedCommand command,
EventHandler<ExecutedRoutedEventArgs> executed = null,
EventHandler<CanExecuteRoutedEventArgs> canExecute = null)
{
Command = command;
if (executed != null) Executed += executed;
if (canExecute != null) CanExecute += canExecute;
}
public RoutedCommand Command { get; }
public event EventHandler<CanExecuteRoutedEventArgs> CanExecute;
public event EventHandler<ExecutedRoutedEventArgs> Executed;
internal bool DoCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
if (e.Handled) return true;
var canExecute = CanExecute;
if (canExecute == null)
{
if (Executed != null)
{
e.Handled = true;
e.CanExecute = true;
}
}
else
{
canExecute(sender, e);
if (e.CanExecute)
{
e.Handled = true;
}
}
return e.CanExecute;
}
internal bool DoExecuted(object sender, ExecutedRoutedEventArgs e)
{
if (!e.Handled)
{
var executed = Executed;
if (executed != null)
{
if (DoCanExecute(sender, new CanExecuteRoutedEventArgs(e.Command, e.Parameter)))
{
executed(sender, e);
e.Handled = true;
return true;
}
}
}
return false;
}
}
public sealed class CanExecuteRoutedEventArgs : RoutedEventArgs
{
public ICommand Command { get; }
public object Parameter { get; }
public bool CanExecute { get; set; }
internal CanExecuteRoutedEventArgs(ICommand command, object parameter)
{
Command = command ?? throw new ArgumentNullException(nameof(command));
Parameter = parameter;
RoutedEvent = RoutedCommand.CanExecuteEvent;
}
}
public sealed class ExecutedRoutedEventArgs : RoutedEventArgs
{
public ICommand Command { get; }
public object Parameter { get; }
internal ExecutedRoutedEventArgs(ICommand command, object parameter)
{
Command = command ?? throw new ArgumentNullException(nameof(command));
Parameter = parameter;
RoutedEvent = RoutedCommand.ExecutedEvent;
}
}
}
<MSG> Merge pull request #203 from HendrikMennen/fixobsolete
Replace obsolete methods
<DFF> @@ -25,24 +25,18 @@ namespace AvaloniaEdit
ExecutedEvent.AddClassHandler<IRoutedCommandBindable>(ExecutedEventHandler);
}
- private static Action<CanExecuteRoutedEventArgs> CanExecuteEventHandler(IRoutedCommandBindable control)
+ private static void CanExecuteEventHandler(IRoutedCommandBindable control, CanExecuteRoutedEventArgs args)
{
- return args =>
- {
- var binding = control.CommandBindings.Where(c => c != null)
- .FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
- args.CanExecute = binding != null;
- };
+ var binding = control.CommandBindings.Where(c => c != null)
+ .FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
+ args.CanExecute = binding != null;
}
- private static Action<ExecutedRoutedEventArgs> ExecutedEventHandler(IRoutedCommandBindable control)
+ private static void ExecutedEventHandler(IRoutedCommandBindable control, ExecutedRoutedEventArgs args)
{
- return args =>
- {
- // ReSharper disable once UnusedVariable
- var binding = control.CommandBindings.Where(c => c != null)
- .FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
- };
+ // ReSharper disable once UnusedVariable
+ var binding = control.CommandBindings.Where(c => c != null)
+ .FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
}
public static RoutedEvent<CanExecuteRoutedEventArgs> CanExecuteEvent { get; } = RoutedEvent.Register<CanExecuteRoutedEventArgs>(nameof(CanExecuteEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
| 8 | Merge pull request #203 from HendrikMennen/fixobsolete | 14 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057682 | <NME> RoutedCommand.cs
<BEF> using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Input;
using Avalonia;
using Avalonia.Input;
using Avalonia.Interactivity;
namespace AvaloniaEdit
{
public class RoutedCommand : ICommand
{
public string Name { get; }
public KeyGesture Gesture { get; }
public RoutedCommand(string name, KeyGesture keyGesture = null)
{
Name = name;
Gesture = keyGesture;
}
static RoutedCommand()
{
CanExecuteEvent.AddClassHandler<IRoutedCommandBindable>(CanExecuteEventHandler);
ExecutedEvent.AddClassHandler<IRoutedCommandBindable>(ExecutedEventHandler);
}
private static Action<CanExecuteRoutedEventArgs> CanExecuteEventHandler(IRoutedCommandBindable control)
{
return args =>
{
var binding = control.CommandBindings.Where(c => c != null)
.FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
args.CanExecute = binding != null;
};
}
private static Action<ExecutedRoutedEventArgs> ExecutedEventHandler(IRoutedCommandBindable control)
{
return args =>
{
// ReSharper disable once UnusedVariable
var binding = control.CommandBindings.Where(c => c != null)
.FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
};
}
public static RoutedEvent<CanExecuteRoutedEventArgs> CanExecuteEvent { get; } = RoutedEvent.Register<CanExecuteRoutedEventArgs>(nameof(CanExecuteEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
public bool CanExecute(object parameter, IInputElement target)
{
if (target == null) return false;
var args = new CanExecuteRoutedEventArgs(this, parameter);
target.RaiseEvent(args);
return args.CanExecute;
}
bool ICommand.CanExecute(object parameter)
{
return CanExecute(parameter, Application.Current.FocusManager.Current);
}
public static RoutedEvent<ExecutedRoutedEventArgs> ExecutedEvent { get; } = RoutedEvent.Register<ExecutedRoutedEventArgs>(nameof(ExecutedEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
public void Execute(object parameter, IInputElement target)
{
if (target == null) return;
var args = new ExecutedRoutedEventArgs(this, parameter);
target.RaiseEvent(args);
}
void ICommand.Execute(object parameter)
{
Execute(parameter, Application.Current.FocusManager.Current);
}
// TODO
event EventHandler ICommand.CanExecuteChanged
{
add { }
remove { }
}
}
public interface IRoutedCommandBindable : IInteractive
{
IList<RoutedCommandBinding> CommandBindings { get; }
}
public class RoutedCommandBinding
{
public RoutedCommandBinding(RoutedCommand command,
EventHandler<ExecutedRoutedEventArgs> executed = null,
EventHandler<CanExecuteRoutedEventArgs> canExecute = null)
{
Command = command;
if (executed != null) Executed += executed;
if (canExecute != null) CanExecute += canExecute;
}
public RoutedCommand Command { get; }
public event EventHandler<CanExecuteRoutedEventArgs> CanExecute;
public event EventHandler<ExecutedRoutedEventArgs> Executed;
internal bool DoCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
if (e.Handled) return true;
var canExecute = CanExecute;
if (canExecute == null)
{
if (Executed != null)
{
e.Handled = true;
e.CanExecute = true;
}
}
else
{
canExecute(sender, e);
if (e.CanExecute)
{
e.Handled = true;
}
}
return e.CanExecute;
}
internal bool DoExecuted(object sender, ExecutedRoutedEventArgs e)
{
if (!e.Handled)
{
var executed = Executed;
if (executed != null)
{
if (DoCanExecute(sender, new CanExecuteRoutedEventArgs(e.Command, e.Parameter)))
{
executed(sender, e);
e.Handled = true;
return true;
}
}
}
return false;
}
}
public sealed class CanExecuteRoutedEventArgs : RoutedEventArgs
{
public ICommand Command { get; }
public object Parameter { get; }
public bool CanExecute { get; set; }
internal CanExecuteRoutedEventArgs(ICommand command, object parameter)
{
Command = command ?? throw new ArgumentNullException(nameof(command));
Parameter = parameter;
RoutedEvent = RoutedCommand.CanExecuteEvent;
}
}
public sealed class ExecutedRoutedEventArgs : RoutedEventArgs
{
public ICommand Command { get; }
public object Parameter { get; }
internal ExecutedRoutedEventArgs(ICommand command, object parameter)
{
Command = command ?? throw new ArgumentNullException(nameof(command));
Parameter = parameter;
RoutedEvent = RoutedCommand.ExecutedEvent;
}
}
}
<MSG> Merge pull request #203 from HendrikMennen/fixobsolete
Replace obsolete methods
<DFF> @@ -25,24 +25,18 @@ namespace AvaloniaEdit
ExecutedEvent.AddClassHandler<IRoutedCommandBindable>(ExecutedEventHandler);
}
- private static Action<CanExecuteRoutedEventArgs> CanExecuteEventHandler(IRoutedCommandBindable control)
+ private static void CanExecuteEventHandler(IRoutedCommandBindable control, CanExecuteRoutedEventArgs args)
{
- return args =>
- {
- var binding = control.CommandBindings.Where(c => c != null)
- .FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
- args.CanExecute = binding != null;
- };
+ var binding = control.CommandBindings.Where(c => c != null)
+ .FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
+ args.CanExecute = binding != null;
}
- private static Action<ExecutedRoutedEventArgs> ExecutedEventHandler(IRoutedCommandBindable control)
+ private static void ExecutedEventHandler(IRoutedCommandBindable control, ExecutedRoutedEventArgs args)
{
- return args =>
- {
- // ReSharper disable once UnusedVariable
- var binding = control.CommandBindings.Where(c => c != null)
- .FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
- };
+ // ReSharper disable once UnusedVariable
+ var binding = control.CommandBindings.Where(c => c != null)
+ .FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
}
public static RoutedEvent<CanExecuteRoutedEventArgs> CanExecuteEvent { get; } = RoutedEvent.Register<CanExecuteRoutedEventArgs>(nameof(CanExecuteEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
| 8 | Merge pull request #203 from HendrikMennen/fixobsolete | 14 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057683 | <NME> RoutedCommand.cs
<BEF> using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Input;
using Avalonia;
using Avalonia.Input;
using Avalonia.Interactivity;
namespace AvaloniaEdit
{
public class RoutedCommand : ICommand
{
public string Name { get; }
public KeyGesture Gesture { get; }
public RoutedCommand(string name, KeyGesture keyGesture = null)
{
Name = name;
Gesture = keyGesture;
}
static RoutedCommand()
{
CanExecuteEvent.AddClassHandler<IRoutedCommandBindable>(CanExecuteEventHandler);
ExecutedEvent.AddClassHandler<IRoutedCommandBindable>(ExecutedEventHandler);
}
private static Action<CanExecuteRoutedEventArgs> CanExecuteEventHandler(IRoutedCommandBindable control)
{
return args =>
{
var binding = control.CommandBindings.Where(c => c != null)
.FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
args.CanExecute = binding != null;
};
}
private static Action<ExecutedRoutedEventArgs> ExecutedEventHandler(IRoutedCommandBindable control)
{
return args =>
{
// ReSharper disable once UnusedVariable
var binding = control.CommandBindings.Where(c => c != null)
.FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
};
}
public static RoutedEvent<CanExecuteRoutedEventArgs> CanExecuteEvent { get; } = RoutedEvent.Register<CanExecuteRoutedEventArgs>(nameof(CanExecuteEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
public bool CanExecute(object parameter, IInputElement target)
{
if (target == null) return false;
var args = new CanExecuteRoutedEventArgs(this, parameter);
target.RaiseEvent(args);
return args.CanExecute;
}
bool ICommand.CanExecute(object parameter)
{
return CanExecute(parameter, Application.Current.FocusManager.Current);
}
public static RoutedEvent<ExecutedRoutedEventArgs> ExecutedEvent { get; } = RoutedEvent.Register<ExecutedRoutedEventArgs>(nameof(ExecutedEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
public void Execute(object parameter, IInputElement target)
{
if (target == null) return;
var args = new ExecutedRoutedEventArgs(this, parameter);
target.RaiseEvent(args);
}
void ICommand.Execute(object parameter)
{
Execute(parameter, Application.Current.FocusManager.Current);
}
// TODO
event EventHandler ICommand.CanExecuteChanged
{
add { }
remove { }
}
}
public interface IRoutedCommandBindable : IInteractive
{
IList<RoutedCommandBinding> CommandBindings { get; }
}
public class RoutedCommandBinding
{
public RoutedCommandBinding(RoutedCommand command,
EventHandler<ExecutedRoutedEventArgs> executed = null,
EventHandler<CanExecuteRoutedEventArgs> canExecute = null)
{
Command = command;
if (executed != null) Executed += executed;
if (canExecute != null) CanExecute += canExecute;
}
public RoutedCommand Command { get; }
public event EventHandler<CanExecuteRoutedEventArgs> CanExecute;
public event EventHandler<ExecutedRoutedEventArgs> Executed;
internal bool DoCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
if (e.Handled) return true;
var canExecute = CanExecute;
if (canExecute == null)
{
if (Executed != null)
{
e.Handled = true;
e.CanExecute = true;
}
}
else
{
canExecute(sender, e);
if (e.CanExecute)
{
e.Handled = true;
}
}
return e.CanExecute;
}
internal bool DoExecuted(object sender, ExecutedRoutedEventArgs e)
{
if (!e.Handled)
{
var executed = Executed;
if (executed != null)
{
if (DoCanExecute(sender, new CanExecuteRoutedEventArgs(e.Command, e.Parameter)))
{
executed(sender, e);
e.Handled = true;
return true;
}
}
}
return false;
}
}
public sealed class CanExecuteRoutedEventArgs : RoutedEventArgs
{
public ICommand Command { get; }
public object Parameter { get; }
public bool CanExecute { get; set; }
internal CanExecuteRoutedEventArgs(ICommand command, object parameter)
{
Command = command ?? throw new ArgumentNullException(nameof(command));
Parameter = parameter;
RoutedEvent = RoutedCommand.CanExecuteEvent;
}
}
public sealed class ExecutedRoutedEventArgs : RoutedEventArgs
{
public ICommand Command { get; }
public object Parameter { get; }
internal ExecutedRoutedEventArgs(ICommand command, object parameter)
{
Command = command ?? throw new ArgumentNullException(nameof(command));
Parameter = parameter;
RoutedEvent = RoutedCommand.ExecutedEvent;
}
}
}
<MSG> Merge pull request #203 from HendrikMennen/fixobsolete
Replace obsolete methods
<DFF> @@ -25,24 +25,18 @@ namespace AvaloniaEdit
ExecutedEvent.AddClassHandler<IRoutedCommandBindable>(ExecutedEventHandler);
}
- private static Action<CanExecuteRoutedEventArgs> CanExecuteEventHandler(IRoutedCommandBindable control)
+ private static void CanExecuteEventHandler(IRoutedCommandBindable control, CanExecuteRoutedEventArgs args)
{
- return args =>
- {
- var binding = control.CommandBindings.Where(c => c != null)
- .FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
- args.CanExecute = binding != null;
- };
+ var binding = control.CommandBindings.Where(c => c != null)
+ .FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
+ args.CanExecute = binding != null;
}
- private static Action<ExecutedRoutedEventArgs> ExecutedEventHandler(IRoutedCommandBindable control)
+ private static void ExecutedEventHandler(IRoutedCommandBindable control, ExecutedRoutedEventArgs args)
{
- return args =>
- {
- // ReSharper disable once UnusedVariable
- var binding = control.CommandBindings.Where(c => c != null)
- .FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
- };
+ // ReSharper disable once UnusedVariable
+ var binding = control.CommandBindings.Where(c => c != null)
+ .FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
}
public static RoutedEvent<CanExecuteRoutedEventArgs> CanExecuteEvent { get; } = RoutedEvent.Register<CanExecuteRoutedEventArgs>(nameof(CanExecuteEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
| 8 | Merge pull request #203 from HendrikMennen/fixobsolete | 14 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057684 | <NME> RoutedCommand.cs
<BEF> using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Input;
using Avalonia;
using Avalonia.Input;
using Avalonia.Interactivity;
namespace AvaloniaEdit
{
public class RoutedCommand : ICommand
{
public string Name { get; }
public KeyGesture Gesture { get; }
public RoutedCommand(string name, KeyGesture keyGesture = null)
{
Name = name;
Gesture = keyGesture;
}
static RoutedCommand()
{
CanExecuteEvent.AddClassHandler<IRoutedCommandBindable>(CanExecuteEventHandler);
ExecutedEvent.AddClassHandler<IRoutedCommandBindable>(ExecutedEventHandler);
}
private static Action<CanExecuteRoutedEventArgs> CanExecuteEventHandler(IRoutedCommandBindable control)
{
return args =>
{
var binding = control.CommandBindings.Where(c => c != null)
.FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
args.CanExecute = binding != null;
};
}
private static Action<ExecutedRoutedEventArgs> ExecutedEventHandler(IRoutedCommandBindable control)
{
return args =>
{
// ReSharper disable once UnusedVariable
var binding = control.CommandBindings.Where(c => c != null)
.FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
};
}
public static RoutedEvent<CanExecuteRoutedEventArgs> CanExecuteEvent { get; } = RoutedEvent.Register<CanExecuteRoutedEventArgs>(nameof(CanExecuteEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
public bool CanExecute(object parameter, IInputElement target)
{
if (target == null) return false;
var args = new CanExecuteRoutedEventArgs(this, parameter);
target.RaiseEvent(args);
return args.CanExecute;
}
bool ICommand.CanExecute(object parameter)
{
return CanExecute(parameter, Application.Current.FocusManager.Current);
}
public static RoutedEvent<ExecutedRoutedEventArgs> ExecutedEvent { get; } = RoutedEvent.Register<ExecutedRoutedEventArgs>(nameof(ExecutedEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
public void Execute(object parameter, IInputElement target)
{
if (target == null) return;
var args = new ExecutedRoutedEventArgs(this, parameter);
target.RaiseEvent(args);
}
void ICommand.Execute(object parameter)
{
Execute(parameter, Application.Current.FocusManager.Current);
}
// TODO
event EventHandler ICommand.CanExecuteChanged
{
add { }
remove { }
}
}
public interface IRoutedCommandBindable : IInteractive
{
IList<RoutedCommandBinding> CommandBindings { get; }
}
public class RoutedCommandBinding
{
public RoutedCommandBinding(RoutedCommand command,
EventHandler<ExecutedRoutedEventArgs> executed = null,
EventHandler<CanExecuteRoutedEventArgs> canExecute = null)
{
Command = command;
if (executed != null) Executed += executed;
if (canExecute != null) CanExecute += canExecute;
}
public RoutedCommand Command { get; }
public event EventHandler<CanExecuteRoutedEventArgs> CanExecute;
public event EventHandler<ExecutedRoutedEventArgs> Executed;
internal bool DoCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
if (e.Handled) return true;
var canExecute = CanExecute;
if (canExecute == null)
{
if (Executed != null)
{
e.Handled = true;
e.CanExecute = true;
}
}
else
{
canExecute(sender, e);
if (e.CanExecute)
{
e.Handled = true;
}
}
return e.CanExecute;
}
internal bool DoExecuted(object sender, ExecutedRoutedEventArgs e)
{
if (!e.Handled)
{
var executed = Executed;
if (executed != null)
{
if (DoCanExecute(sender, new CanExecuteRoutedEventArgs(e.Command, e.Parameter)))
{
executed(sender, e);
e.Handled = true;
return true;
}
}
}
return false;
}
}
public sealed class CanExecuteRoutedEventArgs : RoutedEventArgs
{
public ICommand Command { get; }
public object Parameter { get; }
public bool CanExecute { get; set; }
internal CanExecuteRoutedEventArgs(ICommand command, object parameter)
{
Command = command ?? throw new ArgumentNullException(nameof(command));
Parameter = parameter;
RoutedEvent = RoutedCommand.CanExecuteEvent;
}
}
public sealed class ExecutedRoutedEventArgs : RoutedEventArgs
{
public ICommand Command { get; }
public object Parameter { get; }
internal ExecutedRoutedEventArgs(ICommand command, object parameter)
{
Command = command ?? throw new ArgumentNullException(nameof(command));
Parameter = parameter;
RoutedEvent = RoutedCommand.ExecutedEvent;
}
}
}
<MSG> Merge pull request #203 from HendrikMennen/fixobsolete
Replace obsolete methods
<DFF> @@ -25,24 +25,18 @@ namespace AvaloniaEdit
ExecutedEvent.AddClassHandler<IRoutedCommandBindable>(ExecutedEventHandler);
}
- private static Action<CanExecuteRoutedEventArgs> CanExecuteEventHandler(IRoutedCommandBindable control)
+ private static void CanExecuteEventHandler(IRoutedCommandBindable control, CanExecuteRoutedEventArgs args)
{
- return args =>
- {
- var binding = control.CommandBindings.Where(c => c != null)
- .FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
- args.CanExecute = binding != null;
- };
+ var binding = control.CommandBindings.Where(c => c != null)
+ .FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
+ args.CanExecute = binding != null;
}
- private static Action<ExecutedRoutedEventArgs> ExecutedEventHandler(IRoutedCommandBindable control)
+ private static void ExecutedEventHandler(IRoutedCommandBindable control, ExecutedRoutedEventArgs args)
{
- return args =>
- {
- // ReSharper disable once UnusedVariable
- var binding = control.CommandBindings.Where(c => c != null)
- .FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
- };
+ // ReSharper disable once UnusedVariable
+ var binding = control.CommandBindings.Where(c => c != null)
+ .FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
}
public static RoutedEvent<CanExecuteRoutedEventArgs> CanExecuteEvent { get; } = RoutedEvent.Register<CanExecuteRoutedEventArgs>(nameof(CanExecuteEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
| 8 | Merge pull request #203 from HendrikMennen/fixobsolete | 14 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057685 | <NME> RoutedCommand.cs
<BEF> using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Input;
using Avalonia;
using Avalonia.Input;
using Avalonia.Interactivity;
namespace AvaloniaEdit
{
public class RoutedCommand : ICommand
{
public string Name { get; }
public KeyGesture Gesture { get; }
public RoutedCommand(string name, KeyGesture keyGesture = null)
{
Name = name;
Gesture = keyGesture;
}
static RoutedCommand()
{
CanExecuteEvent.AddClassHandler<IRoutedCommandBindable>(CanExecuteEventHandler);
ExecutedEvent.AddClassHandler<IRoutedCommandBindable>(ExecutedEventHandler);
}
private static Action<CanExecuteRoutedEventArgs> CanExecuteEventHandler(IRoutedCommandBindable control)
{
return args =>
{
var binding = control.CommandBindings.Where(c => c != null)
.FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
args.CanExecute = binding != null;
};
}
private static Action<ExecutedRoutedEventArgs> ExecutedEventHandler(IRoutedCommandBindable control)
{
return args =>
{
// ReSharper disable once UnusedVariable
var binding = control.CommandBindings.Where(c => c != null)
.FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
};
}
public static RoutedEvent<CanExecuteRoutedEventArgs> CanExecuteEvent { get; } = RoutedEvent.Register<CanExecuteRoutedEventArgs>(nameof(CanExecuteEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
public bool CanExecute(object parameter, IInputElement target)
{
if (target == null) return false;
var args = new CanExecuteRoutedEventArgs(this, parameter);
target.RaiseEvent(args);
return args.CanExecute;
}
bool ICommand.CanExecute(object parameter)
{
return CanExecute(parameter, Application.Current.FocusManager.Current);
}
public static RoutedEvent<ExecutedRoutedEventArgs> ExecutedEvent { get; } = RoutedEvent.Register<ExecutedRoutedEventArgs>(nameof(ExecutedEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
public void Execute(object parameter, IInputElement target)
{
if (target == null) return;
var args = new ExecutedRoutedEventArgs(this, parameter);
target.RaiseEvent(args);
}
void ICommand.Execute(object parameter)
{
Execute(parameter, Application.Current.FocusManager.Current);
}
// TODO
event EventHandler ICommand.CanExecuteChanged
{
add { }
remove { }
}
}
public interface IRoutedCommandBindable : IInteractive
{
IList<RoutedCommandBinding> CommandBindings { get; }
}
public class RoutedCommandBinding
{
public RoutedCommandBinding(RoutedCommand command,
EventHandler<ExecutedRoutedEventArgs> executed = null,
EventHandler<CanExecuteRoutedEventArgs> canExecute = null)
{
Command = command;
if (executed != null) Executed += executed;
if (canExecute != null) CanExecute += canExecute;
}
public RoutedCommand Command { get; }
public event EventHandler<CanExecuteRoutedEventArgs> CanExecute;
public event EventHandler<ExecutedRoutedEventArgs> Executed;
internal bool DoCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
if (e.Handled) return true;
var canExecute = CanExecute;
if (canExecute == null)
{
if (Executed != null)
{
e.Handled = true;
e.CanExecute = true;
}
}
else
{
canExecute(sender, e);
if (e.CanExecute)
{
e.Handled = true;
}
}
return e.CanExecute;
}
internal bool DoExecuted(object sender, ExecutedRoutedEventArgs e)
{
if (!e.Handled)
{
var executed = Executed;
if (executed != null)
{
if (DoCanExecute(sender, new CanExecuteRoutedEventArgs(e.Command, e.Parameter)))
{
executed(sender, e);
e.Handled = true;
return true;
}
}
}
return false;
}
}
public sealed class CanExecuteRoutedEventArgs : RoutedEventArgs
{
public ICommand Command { get; }
public object Parameter { get; }
public bool CanExecute { get; set; }
internal CanExecuteRoutedEventArgs(ICommand command, object parameter)
{
Command = command ?? throw new ArgumentNullException(nameof(command));
Parameter = parameter;
RoutedEvent = RoutedCommand.CanExecuteEvent;
}
}
public sealed class ExecutedRoutedEventArgs : RoutedEventArgs
{
public ICommand Command { get; }
public object Parameter { get; }
internal ExecutedRoutedEventArgs(ICommand command, object parameter)
{
Command = command ?? throw new ArgumentNullException(nameof(command));
Parameter = parameter;
RoutedEvent = RoutedCommand.ExecutedEvent;
}
}
}
<MSG> Merge pull request #203 from HendrikMennen/fixobsolete
Replace obsolete methods
<DFF> @@ -25,24 +25,18 @@ namespace AvaloniaEdit
ExecutedEvent.AddClassHandler<IRoutedCommandBindable>(ExecutedEventHandler);
}
- private static Action<CanExecuteRoutedEventArgs> CanExecuteEventHandler(IRoutedCommandBindable control)
+ private static void CanExecuteEventHandler(IRoutedCommandBindable control, CanExecuteRoutedEventArgs args)
{
- return args =>
- {
- var binding = control.CommandBindings.Where(c => c != null)
- .FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
- args.CanExecute = binding != null;
- };
+ var binding = control.CommandBindings.Where(c => c != null)
+ .FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
+ args.CanExecute = binding != null;
}
- private static Action<ExecutedRoutedEventArgs> ExecutedEventHandler(IRoutedCommandBindable control)
+ private static void ExecutedEventHandler(IRoutedCommandBindable control, ExecutedRoutedEventArgs args)
{
- return args =>
- {
- // ReSharper disable once UnusedVariable
- var binding = control.CommandBindings.Where(c => c != null)
- .FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
- };
+ // ReSharper disable once UnusedVariable
+ var binding = control.CommandBindings.Where(c => c != null)
+ .FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
}
public static RoutedEvent<CanExecuteRoutedEventArgs> CanExecuteEvent { get; } = RoutedEvent.Register<CanExecuteRoutedEventArgs>(nameof(CanExecuteEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
| 8 | Merge pull request #203 from HendrikMennen/fixobsolete | 14 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057686 | <NME> RoutedCommand.cs
<BEF> using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Input;
using Avalonia;
using Avalonia.Input;
using Avalonia.Interactivity;
namespace AvaloniaEdit
{
public class RoutedCommand : ICommand
{
public string Name { get; }
public KeyGesture Gesture { get; }
public RoutedCommand(string name, KeyGesture keyGesture = null)
{
Name = name;
Gesture = keyGesture;
}
static RoutedCommand()
{
CanExecuteEvent.AddClassHandler<IRoutedCommandBindable>(CanExecuteEventHandler);
ExecutedEvent.AddClassHandler<IRoutedCommandBindable>(ExecutedEventHandler);
}
private static Action<CanExecuteRoutedEventArgs> CanExecuteEventHandler(IRoutedCommandBindable control)
{
return args =>
{
var binding = control.CommandBindings.Where(c => c != null)
.FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
args.CanExecute = binding != null;
};
}
private static Action<ExecutedRoutedEventArgs> ExecutedEventHandler(IRoutedCommandBindable control)
{
return args =>
{
// ReSharper disable once UnusedVariable
var binding = control.CommandBindings.Where(c => c != null)
.FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
};
}
public static RoutedEvent<CanExecuteRoutedEventArgs> CanExecuteEvent { get; } = RoutedEvent.Register<CanExecuteRoutedEventArgs>(nameof(CanExecuteEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
public bool CanExecute(object parameter, IInputElement target)
{
if (target == null) return false;
var args = new CanExecuteRoutedEventArgs(this, parameter);
target.RaiseEvent(args);
return args.CanExecute;
}
bool ICommand.CanExecute(object parameter)
{
return CanExecute(parameter, Application.Current.FocusManager.Current);
}
public static RoutedEvent<ExecutedRoutedEventArgs> ExecutedEvent { get; } = RoutedEvent.Register<ExecutedRoutedEventArgs>(nameof(ExecutedEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
public void Execute(object parameter, IInputElement target)
{
if (target == null) return;
var args = new ExecutedRoutedEventArgs(this, parameter);
target.RaiseEvent(args);
}
void ICommand.Execute(object parameter)
{
Execute(parameter, Application.Current.FocusManager.Current);
}
// TODO
event EventHandler ICommand.CanExecuteChanged
{
add { }
remove { }
}
}
public interface IRoutedCommandBindable : IInteractive
{
IList<RoutedCommandBinding> CommandBindings { get; }
}
public class RoutedCommandBinding
{
public RoutedCommandBinding(RoutedCommand command,
EventHandler<ExecutedRoutedEventArgs> executed = null,
EventHandler<CanExecuteRoutedEventArgs> canExecute = null)
{
Command = command;
if (executed != null) Executed += executed;
if (canExecute != null) CanExecute += canExecute;
}
public RoutedCommand Command { get; }
public event EventHandler<CanExecuteRoutedEventArgs> CanExecute;
public event EventHandler<ExecutedRoutedEventArgs> Executed;
internal bool DoCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
if (e.Handled) return true;
var canExecute = CanExecute;
if (canExecute == null)
{
if (Executed != null)
{
e.Handled = true;
e.CanExecute = true;
}
}
else
{
canExecute(sender, e);
if (e.CanExecute)
{
e.Handled = true;
}
}
return e.CanExecute;
}
internal bool DoExecuted(object sender, ExecutedRoutedEventArgs e)
{
if (!e.Handled)
{
var executed = Executed;
if (executed != null)
{
if (DoCanExecute(sender, new CanExecuteRoutedEventArgs(e.Command, e.Parameter)))
{
executed(sender, e);
e.Handled = true;
return true;
}
}
}
return false;
}
}
public sealed class CanExecuteRoutedEventArgs : RoutedEventArgs
{
public ICommand Command { get; }
public object Parameter { get; }
public bool CanExecute { get; set; }
internal CanExecuteRoutedEventArgs(ICommand command, object parameter)
{
Command = command ?? throw new ArgumentNullException(nameof(command));
Parameter = parameter;
RoutedEvent = RoutedCommand.CanExecuteEvent;
}
}
public sealed class ExecutedRoutedEventArgs : RoutedEventArgs
{
public ICommand Command { get; }
public object Parameter { get; }
internal ExecutedRoutedEventArgs(ICommand command, object parameter)
{
Command = command ?? throw new ArgumentNullException(nameof(command));
Parameter = parameter;
RoutedEvent = RoutedCommand.ExecutedEvent;
}
}
}
<MSG> Merge pull request #203 from HendrikMennen/fixobsolete
Replace obsolete methods
<DFF> @@ -25,24 +25,18 @@ namespace AvaloniaEdit
ExecutedEvent.AddClassHandler<IRoutedCommandBindable>(ExecutedEventHandler);
}
- private static Action<CanExecuteRoutedEventArgs> CanExecuteEventHandler(IRoutedCommandBindable control)
+ private static void CanExecuteEventHandler(IRoutedCommandBindable control, CanExecuteRoutedEventArgs args)
{
- return args =>
- {
- var binding = control.CommandBindings.Where(c => c != null)
- .FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
- args.CanExecute = binding != null;
- };
+ var binding = control.CommandBindings.Where(c => c != null)
+ .FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
+ args.CanExecute = binding != null;
}
- private static Action<ExecutedRoutedEventArgs> ExecutedEventHandler(IRoutedCommandBindable control)
+ private static void ExecutedEventHandler(IRoutedCommandBindable control, ExecutedRoutedEventArgs args)
{
- return args =>
- {
- // ReSharper disable once UnusedVariable
- var binding = control.CommandBindings.Where(c => c != null)
- .FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
- };
+ // ReSharper disable once UnusedVariable
+ var binding = control.CommandBindings.Where(c => c != null)
+ .FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
}
public static RoutedEvent<CanExecuteRoutedEventArgs> CanExecuteEvent { get; } = RoutedEvent.Register<CanExecuteRoutedEventArgs>(nameof(CanExecuteEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
| 8 | Merge pull request #203 from HendrikMennen/fixobsolete | 14 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057687 | <NME> RoutedCommand.cs
<BEF> using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Input;
using Avalonia;
using Avalonia.Input;
using Avalonia.Interactivity;
namespace AvaloniaEdit
{
public class RoutedCommand : ICommand
{
public string Name { get; }
public KeyGesture Gesture { get; }
public RoutedCommand(string name, KeyGesture keyGesture = null)
{
Name = name;
Gesture = keyGesture;
}
static RoutedCommand()
{
CanExecuteEvent.AddClassHandler<IRoutedCommandBindable>(CanExecuteEventHandler);
ExecutedEvent.AddClassHandler<IRoutedCommandBindable>(ExecutedEventHandler);
}
private static Action<CanExecuteRoutedEventArgs> CanExecuteEventHandler(IRoutedCommandBindable control)
{
return args =>
{
var binding = control.CommandBindings.Where(c => c != null)
.FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
args.CanExecute = binding != null;
};
}
private static Action<ExecutedRoutedEventArgs> ExecutedEventHandler(IRoutedCommandBindable control)
{
return args =>
{
// ReSharper disable once UnusedVariable
var binding = control.CommandBindings.Where(c => c != null)
.FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
};
}
public static RoutedEvent<CanExecuteRoutedEventArgs> CanExecuteEvent { get; } = RoutedEvent.Register<CanExecuteRoutedEventArgs>(nameof(CanExecuteEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
public bool CanExecute(object parameter, IInputElement target)
{
if (target == null) return false;
var args = new CanExecuteRoutedEventArgs(this, parameter);
target.RaiseEvent(args);
return args.CanExecute;
}
bool ICommand.CanExecute(object parameter)
{
return CanExecute(parameter, Application.Current.FocusManager.Current);
}
public static RoutedEvent<ExecutedRoutedEventArgs> ExecutedEvent { get; } = RoutedEvent.Register<ExecutedRoutedEventArgs>(nameof(ExecutedEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
public void Execute(object parameter, IInputElement target)
{
if (target == null) return;
var args = new ExecutedRoutedEventArgs(this, parameter);
target.RaiseEvent(args);
}
void ICommand.Execute(object parameter)
{
Execute(parameter, Application.Current.FocusManager.Current);
}
// TODO
event EventHandler ICommand.CanExecuteChanged
{
add { }
remove { }
}
}
public interface IRoutedCommandBindable : IInteractive
{
IList<RoutedCommandBinding> CommandBindings { get; }
}
public class RoutedCommandBinding
{
public RoutedCommandBinding(RoutedCommand command,
EventHandler<ExecutedRoutedEventArgs> executed = null,
EventHandler<CanExecuteRoutedEventArgs> canExecute = null)
{
Command = command;
if (executed != null) Executed += executed;
if (canExecute != null) CanExecute += canExecute;
}
public RoutedCommand Command { get; }
public event EventHandler<CanExecuteRoutedEventArgs> CanExecute;
public event EventHandler<ExecutedRoutedEventArgs> Executed;
internal bool DoCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
if (e.Handled) return true;
var canExecute = CanExecute;
if (canExecute == null)
{
if (Executed != null)
{
e.Handled = true;
e.CanExecute = true;
}
}
else
{
canExecute(sender, e);
if (e.CanExecute)
{
e.Handled = true;
}
}
return e.CanExecute;
}
internal bool DoExecuted(object sender, ExecutedRoutedEventArgs e)
{
if (!e.Handled)
{
var executed = Executed;
if (executed != null)
{
if (DoCanExecute(sender, new CanExecuteRoutedEventArgs(e.Command, e.Parameter)))
{
executed(sender, e);
e.Handled = true;
return true;
}
}
}
return false;
}
}
public sealed class CanExecuteRoutedEventArgs : RoutedEventArgs
{
public ICommand Command { get; }
public object Parameter { get; }
public bool CanExecute { get; set; }
internal CanExecuteRoutedEventArgs(ICommand command, object parameter)
{
Command = command ?? throw new ArgumentNullException(nameof(command));
Parameter = parameter;
RoutedEvent = RoutedCommand.CanExecuteEvent;
}
}
public sealed class ExecutedRoutedEventArgs : RoutedEventArgs
{
public ICommand Command { get; }
public object Parameter { get; }
internal ExecutedRoutedEventArgs(ICommand command, object parameter)
{
Command = command ?? throw new ArgumentNullException(nameof(command));
Parameter = parameter;
RoutedEvent = RoutedCommand.ExecutedEvent;
}
}
}
<MSG> Merge pull request #203 from HendrikMennen/fixobsolete
Replace obsolete methods
<DFF> @@ -25,24 +25,18 @@ namespace AvaloniaEdit
ExecutedEvent.AddClassHandler<IRoutedCommandBindable>(ExecutedEventHandler);
}
- private static Action<CanExecuteRoutedEventArgs> CanExecuteEventHandler(IRoutedCommandBindable control)
+ private static void CanExecuteEventHandler(IRoutedCommandBindable control, CanExecuteRoutedEventArgs args)
{
- return args =>
- {
- var binding = control.CommandBindings.Where(c => c != null)
- .FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
- args.CanExecute = binding != null;
- };
+ var binding = control.CommandBindings.Where(c => c != null)
+ .FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
+ args.CanExecute = binding != null;
}
- private static Action<ExecutedRoutedEventArgs> ExecutedEventHandler(IRoutedCommandBindable control)
+ private static void ExecutedEventHandler(IRoutedCommandBindable control, ExecutedRoutedEventArgs args)
{
- return args =>
- {
- // ReSharper disable once UnusedVariable
- var binding = control.CommandBindings.Where(c => c != null)
- .FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
- };
+ // ReSharper disable once UnusedVariable
+ var binding = control.CommandBindings.Where(c => c != null)
+ .FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
}
public static RoutedEvent<CanExecuteRoutedEventArgs> CanExecuteEvent { get; } = RoutedEvent.Register<CanExecuteRoutedEventArgs>(nameof(CanExecuteEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
| 8 | Merge pull request #203 from HendrikMennen/fixobsolete | 14 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057688 | <NME> RoutedCommand.cs
<BEF> using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Input;
using Avalonia;
using Avalonia.Input;
using Avalonia.Interactivity;
namespace AvaloniaEdit
{
public class RoutedCommand : ICommand
{
public string Name { get; }
public KeyGesture Gesture { get; }
public RoutedCommand(string name, KeyGesture keyGesture = null)
{
Name = name;
Gesture = keyGesture;
}
static RoutedCommand()
{
CanExecuteEvent.AddClassHandler<IRoutedCommandBindable>(CanExecuteEventHandler);
ExecutedEvent.AddClassHandler<IRoutedCommandBindable>(ExecutedEventHandler);
}
private static Action<CanExecuteRoutedEventArgs> CanExecuteEventHandler(IRoutedCommandBindable control)
{
return args =>
{
var binding = control.CommandBindings.Where(c => c != null)
.FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
args.CanExecute = binding != null;
};
}
private static Action<ExecutedRoutedEventArgs> ExecutedEventHandler(IRoutedCommandBindable control)
{
return args =>
{
// ReSharper disable once UnusedVariable
var binding = control.CommandBindings.Where(c => c != null)
.FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
};
}
public static RoutedEvent<CanExecuteRoutedEventArgs> CanExecuteEvent { get; } = RoutedEvent.Register<CanExecuteRoutedEventArgs>(nameof(CanExecuteEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
public bool CanExecute(object parameter, IInputElement target)
{
if (target == null) return false;
var args = new CanExecuteRoutedEventArgs(this, parameter);
target.RaiseEvent(args);
return args.CanExecute;
}
bool ICommand.CanExecute(object parameter)
{
return CanExecute(parameter, Application.Current.FocusManager.Current);
}
public static RoutedEvent<ExecutedRoutedEventArgs> ExecutedEvent { get; } = RoutedEvent.Register<ExecutedRoutedEventArgs>(nameof(ExecutedEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
public void Execute(object parameter, IInputElement target)
{
if (target == null) return;
var args = new ExecutedRoutedEventArgs(this, parameter);
target.RaiseEvent(args);
}
void ICommand.Execute(object parameter)
{
Execute(parameter, Application.Current.FocusManager.Current);
}
// TODO
event EventHandler ICommand.CanExecuteChanged
{
add { }
remove { }
}
}
public interface IRoutedCommandBindable : IInteractive
{
IList<RoutedCommandBinding> CommandBindings { get; }
}
public class RoutedCommandBinding
{
public RoutedCommandBinding(RoutedCommand command,
EventHandler<ExecutedRoutedEventArgs> executed = null,
EventHandler<CanExecuteRoutedEventArgs> canExecute = null)
{
Command = command;
if (executed != null) Executed += executed;
if (canExecute != null) CanExecute += canExecute;
}
public RoutedCommand Command { get; }
public event EventHandler<CanExecuteRoutedEventArgs> CanExecute;
public event EventHandler<ExecutedRoutedEventArgs> Executed;
internal bool DoCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
if (e.Handled) return true;
var canExecute = CanExecute;
if (canExecute == null)
{
if (Executed != null)
{
e.Handled = true;
e.CanExecute = true;
}
}
else
{
canExecute(sender, e);
if (e.CanExecute)
{
e.Handled = true;
}
}
return e.CanExecute;
}
internal bool DoExecuted(object sender, ExecutedRoutedEventArgs e)
{
if (!e.Handled)
{
var executed = Executed;
if (executed != null)
{
if (DoCanExecute(sender, new CanExecuteRoutedEventArgs(e.Command, e.Parameter)))
{
executed(sender, e);
e.Handled = true;
return true;
}
}
}
return false;
}
}
public sealed class CanExecuteRoutedEventArgs : RoutedEventArgs
{
public ICommand Command { get; }
public object Parameter { get; }
public bool CanExecute { get; set; }
internal CanExecuteRoutedEventArgs(ICommand command, object parameter)
{
Command = command ?? throw new ArgumentNullException(nameof(command));
Parameter = parameter;
RoutedEvent = RoutedCommand.CanExecuteEvent;
}
}
public sealed class ExecutedRoutedEventArgs : RoutedEventArgs
{
public ICommand Command { get; }
public object Parameter { get; }
internal ExecutedRoutedEventArgs(ICommand command, object parameter)
{
Command = command ?? throw new ArgumentNullException(nameof(command));
Parameter = parameter;
RoutedEvent = RoutedCommand.ExecutedEvent;
}
}
}
<MSG> Merge pull request #203 from HendrikMennen/fixobsolete
Replace obsolete methods
<DFF> @@ -25,24 +25,18 @@ namespace AvaloniaEdit
ExecutedEvent.AddClassHandler<IRoutedCommandBindable>(ExecutedEventHandler);
}
- private static Action<CanExecuteRoutedEventArgs> CanExecuteEventHandler(IRoutedCommandBindable control)
+ private static void CanExecuteEventHandler(IRoutedCommandBindable control, CanExecuteRoutedEventArgs args)
{
- return args =>
- {
- var binding = control.CommandBindings.Where(c => c != null)
- .FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
- args.CanExecute = binding != null;
- };
+ var binding = control.CommandBindings.Where(c => c != null)
+ .FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
+ args.CanExecute = binding != null;
}
- private static Action<ExecutedRoutedEventArgs> ExecutedEventHandler(IRoutedCommandBindable control)
+ private static void ExecutedEventHandler(IRoutedCommandBindable control, ExecutedRoutedEventArgs args)
{
- return args =>
- {
- // ReSharper disable once UnusedVariable
- var binding = control.CommandBindings.Where(c => c != null)
- .FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
- };
+ // ReSharper disable once UnusedVariable
+ var binding = control.CommandBindings.Where(c => c != null)
+ .FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
}
public static RoutedEvent<CanExecuteRoutedEventArgs> CanExecuteEvent { get; } = RoutedEvent.Register<CanExecuteRoutedEventArgs>(nameof(CanExecuteEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
| 8 | Merge pull request #203 from HendrikMennen/fixobsolete | 14 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057689 | <NME> RoutedCommand.cs
<BEF> using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Input;
using Avalonia;
using Avalonia.Input;
using Avalonia.Interactivity;
namespace AvaloniaEdit
{
public class RoutedCommand : ICommand
{
public string Name { get; }
public KeyGesture Gesture { get; }
public RoutedCommand(string name, KeyGesture keyGesture = null)
{
Name = name;
Gesture = keyGesture;
}
static RoutedCommand()
{
CanExecuteEvent.AddClassHandler<IRoutedCommandBindable>(CanExecuteEventHandler);
ExecutedEvent.AddClassHandler<IRoutedCommandBindable>(ExecutedEventHandler);
}
private static Action<CanExecuteRoutedEventArgs> CanExecuteEventHandler(IRoutedCommandBindable control)
{
return args =>
{
var binding = control.CommandBindings.Where(c => c != null)
.FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
args.CanExecute = binding != null;
};
}
private static Action<ExecutedRoutedEventArgs> ExecutedEventHandler(IRoutedCommandBindable control)
{
return args =>
{
// ReSharper disable once UnusedVariable
var binding = control.CommandBindings.Where(c => c != null)
.FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
};
}
public static RoutedEvent<CanExecuteRoutedEventArgs> CanExecuteEvent { get; } = RoutedEvent.Register<CanExecuteRoutedEventArgs>(nameof(CanExecuteEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
public bool CanExecute(object parameter, IInputElement target)
{
if (target == null) return false;
var args = new CanExecuteRoutedEventArgs(this, parameter);
target.RaiseEvent(args);
return args.CanExecute;
}
bool ICommand.CanExecute(object parameter)
{
return CanExecute(parameter, Application.Current.FocusManager.Current);
}
public static RoutedEvent<ExecutedRoutedEventArgs> ExecutedEvent { get; } = RoutedEvent.Register<ExecutedRoutedEventArgs>(nameof(ExecutedEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
public void Execute(object parameter, IInputElement target)
{
if (target == null) return;
var args = new ExecutedRoutedEventArgs(this, parameter);
target.RaiseEvent(args);
}
void ICommand.Execute(object parameter)
{
Execute(parameter, Application.Current.FocusManager.Current);
}
// TODO
event EventHandler ICommand.CanExecuteChanged
{
add { }
remove { }
}
}
public interface IRoutedCommandBindable : IInteractive
{
IList<RoutedCommandBinding> CommandBindings { get; }
}
public class RoutedCommandBinding
{
public RoutedCommandBinding(RoutedCommand command,
EventHandler<ExecutedRoutedEventArgs> executed = null,
EventHandler<CanExecuteRoutedEventArgs> canExecute = null)
{
Command = command;
if (executed != null) Executed += executed;
if (canExecute != null) CanExecute += canExecute;
}
public RoutedCommand Command { get; }
public event EventHandler<CanExecuteRoutedEventArgs> CanExecute;
public event EventHandler<ExecutedRoutedEventArgs> Executed;
internal bool DoCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
if (e.Handled) return true;
var canExecute = CanExecute;
if (canExecute == null)
{
if (Executed != null)
{
e.Handled = true;
e.CanExecute = true;
}
}
else
{
canExecute(sender, e);
if (e.CanExecute)
{
e.Handled = true;
}
}
return e.CanExecute;
}
internal bool DoExecuted(object sender, ExecutedRoutedEventArgs e)
{
if (!e.Handled)
{
var executed = Executed;
if (executed != null)
{
if (DoCanExecute(sender, new CanExecuteRoutedEventArgs(e.Command, e.Parameter)))
{
executed(sender, e);
e.Handled = true;
return true;
}
}
}
return false;
}
}
public sealed class CanExecuteRoutedEventArgs : RoutedEventArgs
{
public ICommand Command { get; }
public object Parameter { get; }
public bool CanExecute { get; set; }
internal CanExecuteRoutedEventArgs(ICommand command, object parameter)
{
Command = command ?? throw new ArgumentNullException(nameof(command));
Parameter = parameter;
RoutedEvent = RoutedCommand.CanExecuteEvent;
}
}
public sealed class ExecutedRoutedEventArgs : RoutedEventArgs
{
public ICommand Command { get; }
public object Parameter { get; }
internal ExecutedRoutedEventArgs(ICommand command, object parameter)
{
Command = command ?? throw new ArgumentNullException(nameof(command));
Parameter = parameter;
RoutedEvent = RoutedCommand.ExecutedEvent;
}
}
}
<MSG> Merge pull request #203 from HendrikMennen/fixobsolete
Replace obsolete methods
<DFF> @@ -25,24 +25,18 @@ namespace AvaloniaEdit
ExecutedEvent.AddClassHandler<IRoutedCommandBindable>(ExecutedEventHandler);
}
- private static Action<CanExecuteRoutedEventArgs> CanExecuteEventHandler(IRoutedCommandBindable control)
+ private static void CanExecuteEventHandler(IRoutedCommandBindable control, CanExecuteRoutedEventArgs args)
{
- return args =>
- {
- var binding = control.CommandBindings.Where(c => c != null)
- .FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
- args.CanExecute = binding != null;
- };
+ var binding = control.CommandBindings.Where(c => c != null)
+ .FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
+ args.CanExecute = binding != null;
}
- private static Action<ExecutedRoutedEventArgs> ExecutedEventHandler(IRoutedCommandBindable control)
+ private static void ExecutedEventHandler(IRoutedCommandBindable control, ExecutedRoutedEventArgs args)
{
- return args =>
- {
- // ReSharper disable once UnusedVariable
- var binding = control.CommandBindings.Where(c => c != null)
- .FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
- };
+ // ReSharper disable once UnusedVariable
+ var binding = control.CommandBindings.Where(c => c != null)
+ .FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
}
public static RoutedEvent<CanExecuteRoutedEventArgs> CanExecuteEvent { get; } = RoutedEvent.Register<CanExecuteRoutedEventArgs>(nameof(CanExecuteEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
| 8 | Merge pull request #203 from HendrikMennen/fixobsolete | 14 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057690 | <NME> RoutedCommand.cs
<BEF> using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Input;
using Avalonia;
using Avalonia.Input;
using Avalonia.Interactivity;
namespace AvaloniaEdit
{
public class RoutedCommand : ICommand
{
public string Name { get; }
public KeyGesture Gesture { get; }
public RoutedCommand(string name, KeyGesture keyGesture = null)
{
Name = name;
Gesture = keyGesture;
}
static RoutedCommand()
{
CanExecuteEvent.AddClassHandler<IRoutedCommandBindable>(CanExecuteEventHandler);
ExecutedEvent.AddClassHandler<IRoutedCommandBindable>(ExecutedEventHandler);
}
private static Action<CanExecuteRoutedEventArgs> CanExecuteEventHandler(IRoutedCommandBindable control)
{
return args =>
{
var binding = control.CommandBindings.Where(c => c != null)
.FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
args.CanExecute = binding != null;
};
}
private static Action<ExecutedRoutedEventArgs> ExecutedEventHandler(IRoutedCommandBindable control)
{
return args =>
{
// ReSharper disable once UnusedVariable
var binding = control.CommandBindings.Where(c => c != null)
.FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
};
}
public static RoutedEvent<CanExecuteRoutedEventArgs> CanExecuteEvent { get; } = RoutedEvent.Register<CanExecuteRoutedEventArgs>(nameof(CanExecuteEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
public bool CanExecute(object parameter, IInputElement target)
{
if (target == null) return false;
var args = new CanExecuteRoutedEventArgs(this, parameter);
target.RaiseEvent(args);
return args.CanExecute;
}
bool ICommand.CanExecute(object parameter)
{
return CanExecute(parameter, Application.Current.FocusManager.Current);
}
public static RoutedEvent<ExecutedRoutedEventArgs> ExecutedEvent { get; } = RoutedEvent.Register<ExecutedRoutedEventArgs>(nameof(ExecutedEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
public void Execute(object parameter, IInputElement target)
{
if (target == null) return;
var args = new ExecutedRoutedEventArgs(this, parameter);
target.RaiseEvent(args);
}
void ICommand.Execute(object parameter)
{
Execute(parameter, Application.Current.FocusManager.Current);
}
// TODO
event EventHandler ICommand.CanExecuteChanged
{
add { }
remove { }
}
}
public interface IRoutedCommandBindable : IInteractive
{
IList<RoutedCommandBinding> CommandBindings { get; }
}
public class RoutedCommandBinding
{
public RoutedCommandBinding(RoutedCommand command,
EventHandler<ExecutedRoutedEventArgs> executed = null,
EventHandler<CanExecuteRoutedEventArgs> canExecute = null)
{
Command = command;
if (executed != null) Executed += executed;
if (canExecute != null) CanExecute += canExecute;
}
public RoutedCommand Command { get; }
public event EventHandler<CanExecuteRoutedEventArgs> CanExecute;
public event EventHandler<ExecutedRoutedEventArgs> Executed;
internal bool DoCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
if (e.Handled) return true;
var canExecute = CanExecute;
if (canExecute == null)
{
if (Executed != null)
{
e.Handled = true;
e.CanExecute = true;
}
}
else
{
canExecute(sender, e);
if (e.CanExecute)
{
e.Handled = true;
}
}
return e.CanExecute;
}
internal bool DoExecuted(object sender, ExecutedRoutedEventArgs e)
{
if (!e.Handled)
{
var executed = Executed;
if (executed != null)
{
if (DoCanExecute(sender, new CanExecuteRoutedEventArgs(e.Command, e.Parameter)))
{
executed(sender, e);
e.Handled = true;
return true;
}
}
}
return false;
}
}
public sealed class CanExecuteRoutedEventArgs : RoutedEventArgs
{
public ICommand Command { get; }
public object Parameter { get; }
public bool CanExecute { get; set; }
internal CanExecuteRoutedEventArgs(ICommand command, object parameter)
{
Command = command ?? throw new ArgumentNullException(nameof(command));
Parameter = parameter;
RoutedEvent = RoutedCommand.CanExecuteEvent;
}
}
public sealed class ExecutedRoutedEventArgs : RoutedEventArgs
{
public ICommand Command { get; }
public object Parameter { get; }
internal ExecutedRoutedEventArgs(ICommand command, object parameter)
{
Command = command ?? throw new ArgumentNullException(nameof(command));
Parameter = parameter;
RoutedEvent = RoutedCommand.ExecutedEvent;
}
}
}
<MSG> Merge pull request #203 from HendrikMennen/fixobsolete
Replace obsolete methods
<DFF> @@ -25,24 +25,18 @@ namespace AvaloniaEdit
ExecutedEvent.AddClassHandler<IRoutedCommandBindable>(ExecutedEventHandler);
}
- private static Action<CanExecuteRoutedEventArgs> CanExecuteEventHandler(IRoutedCommandBindable control)
+ private static void CanExecuteEventHandler(IRoutedCommandBindable control, CanExecuteRoutedEventArgs args)
{
- return args =>
- {
- var binding = control.CommandBindings.Where(c => c != null)
- .FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
- args.CanExecute = binding != null;
- };
+ var binding = control.CommandBindings.Where(c => c != null)
+ .FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
+ args.CanExecute = binding != null;
}
- private static Action<ExecutedRoutedEventArgs> ExecutedEventHandler(IRoutedCommandBindable control)
+ private static void ExecutedEventHandler(IRoutedCommandBindable control, ExecutedRoutedEventArgs args)
{
- return args =>
- {
- // ReSharper disable once UnusedVariable
- var binding = control.CommandBindings.Where(c => c != null)
- .FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
- };
+ // ReSharper disable once UnusedVariable
+ var binding = control.CommandBindings.Where(c => c != null)
+ .FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
}
public static RoutedEvent<CanExecuteRoutedEventArgs> CanExecuteEvent { get; } = RoutedEvent.Register<CanExecuteRoutedEventArgs>(nameof(CanExecuteEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
| 8 | Merge pull request #203 from HendrikMennen/fixobsolete | 14 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057691 | <NME> RoutedCommand.cs
<BEF> using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Input;
using Avalonia;
using Avalonia.Input;
using Avalonia.Interactivity;
namespace AvaloniaEdit
{
public class RoutedCommand : ICommand
{
public string Name { get; }
public KeyGesture Gesture { get; }
public RoutedCommand(string name, KeyGesture keyGesture = null)
{
Name = name;
Gesture = keyGesture;
}
static RoutedCommand()
{
CanExecuteEvent.AddClassHandler<IRoutedCommandBindable>(CanExecuteEventHandler);
ExecutedEvent.AddClassHandler<IRoutedCommandBindable>(ExecutedEventHandler);
}
private static Action<CanExecuteRoutedEventArgs> CanExecuteEventHandler(IRoutedCommandBindable control)
{
return args =>
{
var binding = control.CommandBindings.Where(c => c != null)
.FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
args.CanExecute = binding != null;
};
}
private static Action<ExecutedRoutedEventArgs> ExecutedEventHandler(IRoutedCommandBindable control)
{
return args =>
{
// ReSharper disable once UnusedVariable
var binding = control.CommandBindings.Where(c => c != null)
.FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
};
}
public static RoutedEvent<CanExecuteRoutedEventArgs> CanExecuteEvent { get; } = RoutedEvent.Register<CanExecuteRoutedEventArgs>(nameof(CanExecuteEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
public bool CanExecute(object parameter, IInputElement target)
{
if (target == null) return false;
var args = new CanExecuteRoutedEventArgs(this, parameter);
target.RaiseEvent(args);
return args.CanExecute;
}
bool ICommand.CanExecute(object parameter)
{
return CanExecute(parameter, Application.Current.FocusManager.Current);
}
public static RoutedEvent<ExecutedRoutedEventArgs> ExecutedEvent { get; } = RoutedEvent.Register<ExecutedRoutedEventArgs>(nameof(ExecutedEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
public void Execute(object parameter, IInputElement target)
{
if (target == null) return;
var args = new ExecutedRoutedEventArgs(this, parameter);
target.RaiseEvent(args);
}
void ICommand.Execute(object parameter)
{
Execute(parameter, Application.Current.FocusManager.Current);
}
// TODO
event EventHandler ICommand.CanExecuteChanged
{
add { }
remove { }
}
}
public interface IRoutedCommandBindable : IInteractive
{
IList<RoutedCommandBinding> CommandBindings { get; }
}
public class RoutedCommandBinding
{
public RoutedCommandBinding(RoutedCommand command,
EventHandler<ExecutedRoutedEventArgs> executed = null,
EventHandler<CanExecuteRoutedEventArgs> canExecute = null)
{
Command = command;
if (executed != null) Executed += executed;
if (canExecute != null) CanExecute += canExecute;
}
public RoutedCommand Command { get; }
public event EventHandler<CanExecuteRoutedEventArgs> CanExecute;
public event EventHandler<ExecutedRoutedEventArgs> Executed;
internal bool DoCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
if (e.Handled) return true;
var canExecute = CanExecute;
if (canExecute == null)
{
if (Executed != null)
{
e.Handled = true;
e.CanExecute = true;
}
}
else
{
canExecute(sender, e);
if (e.CanExecute)
{
e.Handled = true;
}
}
return e.CanExecute;
}
internal bool DoExecuted(object sender, ExecutedRoutedEventArgs e)
{
if (!e.Handled)
{
var executed = Executed;
if (executed != null)
{
if (DoCanExecute(sender, new CanExecuteRoutedEventArgs(e.Command, e.Parameter)))
{
executed(sender, e);
e.Handled = true;
return true;
}
}
}
return false;
}
}
public sealed class CanExecuteRoutedEventArgs : RoutedEventArgs
{
public ICommand Command { get; }
public object Parameter { get; }
public bool CanExecute { get; set; }
internal CanExecuteRoutedEventArgs(ICommand command, object parameter)
{
Command = command ?? throw new ArgumentNullException(nameof(command));
Parameter = parameter;
RoutedEvent = RoutedCommand.CanExecuteEvent;
}
}
public sealed class ExecutedRoutedEventArgs : RoutedEventArgs
{
public ICommand Command { get; }
public object Parameter { get; }
internal ExecutedRoutedEventArgs(ICommand command, object parameter)
{
Command = command ?? throw new ArgumentNullException(nameof(command));
Parameter = parameter;
RoutedEvent = RoutedCommand.ExecutedEvent;
}
}
}
<MSG> Merge pull request #203 from HendrikMennen/fixobsolete
Replace obsolete methods
<DFF> @@ -25,24 +25,18 @@ namespace AvaloniaEdit
ExecutedEvent.AddClassHandler<IRoutedCommandBindable>(ExecutedEventHandler);
}
- private static Action<CanExecuteRoutedEventArgs> CanExecuteEventHandler(IRoutedCommandBindable control)
+ private static void CanExecuteEventHandler(IRoutedCommandBindable control, CanExecuteRoutedEventArgs args)
{
- return args =>
- {
- var binding = control.CommandBindings.Where(c => c != null)
- .FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
- args.CanExecute = binding != null;
- };
+ var binding = control.CommandBindings.Where(c => c != null)
+ .FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
+ args.CanExecute = binding != null;
}
- private static Action<ExecutedRoutedEventArgs> ExecutedEventHandler(IRoutedCommandBindable control)
+ private static void ExecutedEventHandler(IRoutedCommandBindable control, ExecutedRoutedEventArgs args)
{
- return args =>
- {
- // ReSharper disable once UnusedVariable
- var binding = control.CommandBindings.Where(c => c != null)
- .FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
- };
+ // ReSharper disable once UnusedVariable
+ var binding = control.CommandBindings.Where(c => c != null)
+ .FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
}
public static RoutedEvent<CanExecuteRoutedEventArgs> CanExecuteEvent { get; } = RoutedEvent.Register<CanExecuteRoutedEventArgs>(nameof(CanExecuteEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
| 8 | Merge pull request #203 from HendrikMennen/fixobsolete | 14 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057692 | <NME> RoutedCommand.cs
<BEF> using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Input;
using Avalonia;
using Avalonia.Input;
using Avalonia.Interactivity;
namespace AvaloniaEdit
{
public class RoutedCommand : ICommand
{
public string Name { get; }
public KeyGesture Gesture { get; }
public RoutedCommand(string name, KeyGesture keyGesture = null)
{
Name = name;
Gesture = keyGesture;
}
static RoutedCommand()
{
CanExecuteEvent.AddClassHandler<IRoutedCommandBindable>(CanExecuteEventHandler);
ExecutedEvent.AddClassHandler<IRoutedCommandBindable>(ExecutedEventHandler);
}
private static Action<CanExecuteRoutedEventArgs> CanExecuteEventHandler(IRoutedCommandBindable control)
{
return args =>
{
var binding = control.CommandBindings.Where(c => c != null)
.FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
args.CanExecute = binding != null;
};
}
private static Action<ExecutedRoutedEventArgs> ExecutedEventHandler(IRoutedCommandBindable control)
{
return args =>
{
// ReSharper disable once UnusedVariable
var binding = control.CommandBindings.Where(c => c != null)
.FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
};
}
public static RoutedEvent<CanExecuteRoutedEventArgs> CanExecuteEvent { get; } = RoutedEvent.Register<CanExecuteRoutedEventArgs>(nameof(CanExecuteEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
public bool CanExecute(object parameter, IInputElement target)
{
if (target == null) return false;
var args = new CanExecuteRoutedEventArgs(this, parameter);
target.RaiseEvent(args);
return args.CanExecute;
}
bool ICommand.CanExecute(object parameter)
{
return CanExecute(parameter, Application.Current.FocusManager.Current);
}
public static RoutedEvent<ExecutedRoutedEventArgs> ExecutedEvent { get; } = RoutedEvent.Register<ExecutedRoutedEventArgs>(nameof(ExecutedEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
public void Execute(object parameter, IInputElement target)
{
if (target == null) return;
var args = new ExecutedRoutedEventArgs(this, parameter);
target.RaiseEvent(args);
}
void ICommand.Execute(object parameter)
{
Execute(parameter, Application.Current.FocusManager.Current);
}
// TODO
event EventHandler ICommand.CanExecuteChanged
{
add { }
remove { }
}
}
public interface IRoutedCommandBindable : IInteractive
{
IList<RoutedCommandBinding> CommandBindings { get; }
}
public class RoutedCommandBinding
{
public RoutedCommandBinding(RoutedCommand command,
EventHandler<ExecutedRoutedEventArgs> executed = null,
EventHandler<CanExecuteRoutedEventArgs> canExecute = null)
{
Command = command;
if (executed != null) Executed += executed;
if (canExecute != null) CanExecute += canExecute;
}
public RoutedCommand Command { get; }
public event EventHandler<CanExecuteRoutedEventArgs> CanExecute;
public event EventHandler<ExecutedRoutedEventArgs> Executed;
internal bool DoCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
if (e.Handled) return true;
var canExecute = CanExecute;
if (canExecute == null)
{
if (Executed != null)
{
e.Handled = true;
e.CanExecute = true;
}
}
else
{
canExecute(sender, e);
if (e.CanExecute)
{
e.Handled = true;
}
}
return e.CanExecute;
}
internal bool DoExecuted(object sender, ExecutedRoutedEventArgs e)
{
if (!e.Handled)
{
var executed = Executed;
if (executed != null)
{
if (DoCanExecute(sender, new CanExecuteRoutedEventArgs(e.Command, e.Parameter)))
{
executed(sender, e);
e.Handled = true;
return true;
}
}
}
return false;
}
}
public sealed class CanExecuteRoutedEventArgs : RoutedEventArgs
{
public ICommand Command { get; }
public object Parameter { get; }
public bool CanExecute { get; set; }
internal CanExecuteRoutedEventArgs(ICommand command, object parameter)
{
Command = command ?? throw new ArgumentNullException(nameof(command));
Parameter = parameter;
RoutedEvent = RoutedCommand.CanExecuteEvent;
}
}
public sealed class ExecutedRoutedEventArgs : RoutedEventArgs
{
public ICommand Command { get; }
public object Parameter { get; }
internal ExecutedRoutedEventArgs(ICommand command, object parameter)
{
Command = command ?? throw new ArgumentNullException(nameof(command));
Parameter = parameter;
RoutedEvent = RoutedCommand.ExecutedEvent;
}
}
}
<MSG> Merge pull request #203 from HendrikMennen/fixobsolete
Replace obsolete methods
<DFF> @@ -25,24 +25,18 @@ namespace AvaloniaEdit
ExecutedEvent.AddClassHandler<IRoutedCommandBindable>(ExecutedEventHandler);
}
- private static Action<CanExecuteRoutedEventArgs> CanExecuteEventHandler(IRoutedCommandBindable control)
+ private static void CanExecuteEventHandler(IRoutedCommandBindable control, CanExecuteRoutedEventArgs args)
{
- return args =>
- {
- var binding = control.CommandBindings.Where(c => c != null)
- .FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
- args.CanExecute = binding != null;
- };
+ var binding = control.CommandBindings.Where(c => c != null)
+ .FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
+ args.CanExecute = binding != null;
}
- private static Action<ExecutedRoutedEventArgs> ExecutedEventHandler(IRoutedCommandBindable control)
+ private static void ExecutedEventHandler(IRoutedCommandBindable control, ExecutedRoutedEventArgs args)
{
- return args =>
- {
- // ReSharper disable once UnusedVariable
- var binding = control.CommandBindings.Where(c => c != null)
- .FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
- };
+ // ReSharper disable once UnusedVariable
+ var binding = control.CommandBindings.Where(c => c != null)
+ .FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
}
public static RoutedEvent<CanExecuteRoutedEventArgs> CanExecuteEvent { get; } = RoutedEvent.Register<CanExecuteRoutedEventArgs>(nameof(CanExecuteEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
| 8 | Merge pull request #203 from HendrikMennen/fixobsolete | 14 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057693 | <NME> RoutedCommand.cs
<BEF> using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Input;
using Avalonia;
using Avalonia.Input;
using Avalonia.Interactivity;
namespace AvaloniaEdit
{
public class RoutedCommand : ICommand
{
public string Name { get; }
public KeyGesture Gesture { get; }
public RoutedCommand(string name, KeyGesture keyGesture = null)
{
Name = name;
Gesture = keyGesture;
}
static RoutedCommand()
{
CanExecuteEvent.AddClassHandler<IRoutedCommandBindable>(CanExecuteEventHandler);
ExecutedEvent.AddClassHandler<IRoutedCommandBindable>(ExecutedEventHandler);
}
private static Action<CanExecuteRoutedEventArgs> CanExecuteEventHandler(IRoutedCommandBindable control)
{
return args =>
{
var binding = control.CommandBindings.Where(c => c != null)
.FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
args.CanExecute = binding != null;
};
}
private static Action<ExecutedRoutedEventArgs> ExecutedEventHandler(IRoutedCommandBindable control)
{
return args =>
{
// ReSharper disable once UnusedVariable
var binding = control.CommandBindings.Where(c => c != null)
.FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
};
}
public static RoutedEvent<CanExecuteRoutedEventArgs> CanExecuteEvent { get; } = RoutedEvent.Register<CanExecuteRoutedEventArgs>(nameof(CanExecuteEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
public bool CanExecute(object parameter, IInputElement target)
{
if (target == null) return false;
var args = new CanExecuteRoutedEventArgs(this, parameter);
target.RaiseEvent(args);
return args.CanExecute;
}
bool ICommand.CanExecute(object parameter)
{
return CanExecute(parameter, Application.Current.FocusManager.Current);
}
public static RoutedEvent<ExecutedRoutedEventArgs> ExecutedEvent { get; } = RoutedEvent.Register<ExecutedRoutedEventArgs>(nameof(ExecutedEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
public void Execute(object parameter, IInputElement target)
{
if (target == null) return;
var args = new ExecutedRoutedEventArgs(this, parameter);
target.RaiseEvent(args);
}
void ICommand.Execute(object parameter)
{
Execute(parameter, Application.Current.FocusManager.Current);
}
// TODO
event EventHandler ICommand.CanExecuteChanged
{
add { }
remove { }
}
}
public interface IRoutedCommandBindable : IInteractive
{
IList<RoutedCommandBinding> CommandBindings { get; }
}
public class RoutedCommandBinding
{
public RoutedCommandBinding(RoutedCommand command,
EventHandler<ExecutedRoutedEventArgs> executed = null,
EventHandler<CanExecuteRoutedEventArgs> canExecute = null)
{
Command = command;
if (executed != null) Executed += executed;
if (canExecute != null) CanExecute += canExecute;
}
public RoutedCommand Command { get; }
public event EventHandler<CanExecuteRoutedEventArgs> CanExecute;
public event EventHandler<ExecutedRoutedEventArgs> Executed;
internal bool DoCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
if (e.Handled) return true;
var canExecute = CanExecute;
if (canExecute == null)
{
if (Executed != null)
{
e.Handled = true;
e.CanExecute = true;
}
}
else
{
canExecute(sender, e);
if (e.CanExecute)
{
e.Handled = true;
}
}
return e.CanExecute;
}
internal bool DoExecuted(object sender, ExecutedRoutedEventArgs e)
{
if (!e.Handled)
{
var executed = Executed;
if (executed != null)
{
if (DoCanExecute(sender, new CanExecuteRoutedEventArgs(e.Command, e.Parameter)))
{
executed(sender, e);
e.Handled = true;
return true;
}
}
}
return false;
}
}
public sealed class CanExecuteRoutedEventArgs : RoutedEventArgs
{
public ICommand Command { get; }
public object Parameter { get; }
public bool CanExecute { get; set; }
internal CanExecuteRoutedEventArgs(ICommand command, object parameter)
{
Command = command ?? throw new ArgumentNullException(nameof(command));
Parameter = parameter;
RoutedEvent = RoutedCommand.CanExecuteEvent;
}
}
public sealed class ExecutedRoutedEventArgs : RoutedEventArgs
{
public ICommand Command { get; }
public object Parameter { get; }
internal ExecutedRoutedEventArgs(ICommand command, object parameter)
{
Command = command ?? throw new ArgumentNullException(nameof(command));
Parameter = parameter;
RoutedEvent = RoutedCommand.ExecutedEvent;
}
}
}
<MSG> Merge pull request #203 from HendrikMennen/fixobsolete
Replace obsolete methods
<DFF> @@ -25,24 +25,18 @@ namespace AvaloniaEdit
ExecutedEvent.AddClassHandler<IRoutedCommandBindable>(ExecutedEventHandler);
}
- private static Action<CanExecuteRoutedEventArgs> CanExecuteEventHandler(IRoutedCommandBindable control)
+ private static void CanExecuteEventHandler(IRoutedCommandBindable control, CanExecuteRoutedEventArgs args)
{
- return args =>
- {
- var binding = control.CommandBindings.Where(c => c != null)
- .FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
- args.CanExecute = binding != null;
- };
+ var binding = control.CommandBindings.Where(c => c != null)
+ .FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
+ args.CanExecute = binding != null;
}
- private static Action<ExecutedRoutedEventArgs> ExecutedEventHandler(IRoutedCommandBindable control)
+ private static void ExecutedEventHandler(IRoutedCommandBindable control, ExecutedRoutedEventArgs args)
{
- return args =>
- {
- // ReSharper disable once UnusedVariable
- var binding = control.CommandBindings.Where(c => c != null)
- .FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
- };
+ // ReSharper disable once UnusedVariable
+ var binding = control.CommandBindings.Where(c => c != null)
+ .FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
}
public static RoutedEvent<CanExecuteRoutedEventArgs> CanExecuteEvent { get; } = RoutedEvent.Register<CanExecuteRoutedEventArgs>(nameof(CanExecuteEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
| 8 | Merge pull request #203 from HendrikMennen/fixobsolete | 14 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057694 | <NME> AvaloniaEdit.TextMate.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<LangVersion>latest</LangVersion>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\AvaloniaEdit\AvaloniaEdit.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="TextMateSharp" Version="$(TextMateSharpVersion)" />
<PackageReference Include="TextMateSharp.Grammars" Version="$(TextMateSharpVersion)" />
</ItemGroup>
</Project>
</ItemGroup>
<ItemGroup>
<PackageReference Include="TextMateSharp" Version="1.0.18" />
</ItemGroup>
</Project>
<MSG> Update to TextMateSharp 1.0.19
<DFF> @@ -19,7 +19,7 @@
</ItemGroup>
<ItemGroup>
- <PackageReference Include="TextMateSharp" Version="1.0.18" />
+ <PackageReference Include="TextMateSharp" Version="1.0.19" />
</ItemGroup>
</Project>
| 1 | Update to TextMateSharp 1.0.19 | 1 | .csproj | TextMate/AvaloniaEdit | mit | AvaloniaUI/AvaloniaEdit |
10057695 | <NME> AvaloniaEdit.TextMate.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<LangVersion>latest</LangVersion>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\AvaloniaEdit\AvaloniaEdit.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="TextMateSharp" Version="$(TextMateSharpVersion)" />
<PackageReference Include="TextMateSharp.Grammars" Version="$(TextMateSharpVersion)" />
</ItemGroup>
</Project>
</ItemGroup>
<ItemGroup>
<PackageReference Include="TextMateSharp" Version="1.0.18" />
</ItemGroup>
</Project>
<MSG> Update to TextMateSharp 1.0.19
<DFF> @@ -19,7 +19,7 @@
</ItemGroup>
<ItemGroup>
- <PackageReference Include="TextMateSharp" Version="1.0.18" />
+ <PackageReference Include="TextMateSharp" Version="1.0.19" />
</ItemGroup>
</Project>
| 1 | Update to TextMateSharp 1.0.19 | 1 | .csproj | TextMate/AvaloniaEdit | mit | AvaloniaUI/AvaloniaEdit |
10057696 | <NME> AvaloniaEdit.TextMate.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<LangVersion>latest</LangVersion>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\AvaloniaEdit\AvaloniaEdit.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="TextMateSharp" Version="$(TextMateSharpVersion)" />
<PackageReference Include="TextMateSharp.Grammars" Version="$(TextMateSharpVersion)" />
</ItemGroup>
</Project>
</ItemGroup>
<ItemGroup>
<PackageReference Include="TextMateSharp" Version="1.0.18" />
</ItemGroup>
</Project>
<MSG> Update to TextMateSharp 1.0.19
<DFF> @@ -19,7 +19,7 @@
</ItemGroup>
<ItemGroup>
- <PackageReference Include="TextMateSharp" Version="1.0.18" />
+ <PackageReference Include="TextMateSharp" Version="1.0.19" />
</ItemGroup>
</Project>
| 1 | Update to TextMateSharp 1.0.19 | 1 | .csproj | TextMate/AvaloniaEdit | mit | AvaloniaUI/AvaloniaEdit |
10057697 | <NME> AvaloniaEdit.TextMate.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<LangVersion>latest</LangVersion>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\AvaloniaEdit\AvaloniaEdit.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="TextMateSharp" Version="$(TextMateSharpVersion)" />
<PackageReference Include="TextMateSharp.Grammars" Version="$(TextMateSharpVersion)" />
</ItemGroup>
</Project>
</ItemGroup>
<ItemGroup>
<PackageReference Include="TextMateSharp" Version="1.0.18" />
</ItemGroup>
</Project>
<MSG> Update to TextMateSharp 1.0.19
<DFF> @@ -19,7 +19,7 @@
</ItemGroup>
<ItemGroup>
- <PackageReference Include="TextMateSharp" Version="1.0.18" />
+ <PackageReference Include="TextMateSharp" Version="1.0.19" />
</ItemGroup>
</Project>
| 1 | Update to TextMateSharp 1.0.19 | 1 | .csproj | TextMate/AvaloniaEdit | mit | AvaloniaUI/AvaloniaEdit |
10057698 | <NME> AvaloniaEdit.TextMate.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<LangVersion>latest</LangVersion>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\AvaloniaEdit\AvaloniaEdit.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="TextMateSharp" Version="$(TextMateSharpVersion)" />
<PackageReference Include="TextMateSharp.Grammars" Version="$(TextMateSharpVersion)" />
</ItemGroup>
</Project>
</ItemGroup>
<ItemGroup>
<PackageReference Include="TextMateSharp" Version="1.0.18" />
</ItemGroup>
</Project>
<MSG> Update to TextMateSharp 1.0.19
<DFF> @@ -19,7 +19,7 @@
</ItemGroup>
<ItemGroup>
- <PackageReference Include="TextMateSharp" Version="1.0.18" />
+ <PackageReference Include="TextMateSharp" Version="1.0.19" />
</ItemGroup>
</Project>
| 1 | Update to TextMateSharp 1.0.19 | 1 | .csproj | TextMate/AvaloniaEdit | mit | AvaloniaUI/AvaloniaEdit |
10057699 | <NME> AvaloniaEdit.TextMate.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<LangVersion>latest</LangVersion>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\AvaloniaEdit\AvaloniaEdit.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="TextMateSharp" Version="$(TextMateSharpVersion)" />
<PackageReference Include="TextMateSharp.Grammars" Version="$(TextMateSharpVersion)" />
</ItemGroup>
</Project>
</ItemGroup>
<ItemGroup>
<PackageReference Include="TextMateSharp" Version="1.0.18" />
</ItemGroup>
</Project>
<MSG> Update to TextMateSharp 1.0.19
<DFF> @@ -19,7 +19,7 @@
</ItemGroup>
<ItemGroup>
- <PackageReference Include="TextMateSharp" Version="1.0.18" />
+ <PackageReference Include="TextMateSharp" Version="1.0.19" />
</ItemGroup>
</Project>
| 1 | Update to TextMateSharp 1.0.19 | 1 | .csproj | TextMate/AvaloniaEdit | mit | AvaloniaUI/AvaloniaEdit |
10057700 | <NME> AvaloniaEdit.TextMate.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<LangVersion>latest</LangVersion>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\AvaloniaEdit\AvaloniaEdit.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="TextMateSharp" Version="$(TextMateSharpVersion)" />
<PackageReference Include="TextMateSharp.Grammars" Version="$(TextMateSharpVersion)" />
</ItemGroup>
</Project>
</ItemGroup>
<ItemGroup>
<PackageReference Include="TextMateSharp" Version="1.0.18" />
</ItemGroup>
</Project>
<MSG> Update to TextMateSharp 1.0.19
<DFF> @@ -19,7 +19,7 @@
</ItemGroup>
<ItemGroup>
- <PackageReference Include="TextMateSharp" Version="1.0.18" />
+ <PackageReference Include="TextMateSharp" Version="1.0.19" />
</ItemGroup>
</Project>
| 1 | Update to TextMateSharp 1.0.19 | 1 | .csproj | TextMate/AvaloniaEdit | mit | AvaloniaUI/AvaloniaEdit |
10057701 | <NME> AvaloniaEdit.TextMate.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<LangVersion>latest</LangVersion>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\AvaloniaEdit\AvaloniaEdit.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="TextMateSharp" Version="$(TextMateSharpVersion)" />
<PackageReference Include="TextMateSharp.Grammars" Version="$(TextMateSharpVersion)" />
</ItemGroup>
</Project>
</ItemGroup>
<ItemGroup>
<PackageReference Include="TextMateSharp" Version="1.0.18" />
</ItemGroup>
</Project>
<MSG> Update to TextMateSharp 1.0.19
<DFF> @@ -19,7 +19,7 @@
</ItemGroup>
<ItemGroup>
- <PackageReference Include="TextMateSharp" Version="1.0.18" />
+ <PackageReference Include="TextMateSharp" Version="1.0.19" />
</ItemGroup>
</Project>
| 1 | Update to TextMateSharp 1.0.19 | 1 | .csproj | TextMate/AvaloniaEdit | mit | AvaloniaUI/AvaloniaEdit |
10057702 | <NME> AvaloniaEdit.TextMate.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<LangVersion>latest</LangVersion>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\AvaloniaEdit\AvaloniaEdit.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="TextMateSharp" Version="$(TextMateSharpVersion)" />
<PackageReference Include="TextMateSharp.Grammars" Version="$(TextMateSharpVersion)" />
</ItemGroup>
</Project>
</ItemGroup>
<ItemGroup>
<PackageReference Include="TextMateSharp" Version="1.0.18" />
</ItemGroup>
</Project>
<MSG> Update to TextMateSharp 1.0.19
<DFF> @@ -19,7 +19,7 @@
</ItemGroup>
<ItemGroup>
- <PackageReference Include="TextMateSharp" Version="1.0.18" />
+ <PackageReference Include="TextMateSharp" Version="1.0.19" />
</ItemGroup>
</Project>
| 1 | Update to TextMateSharp 1.0.19 | 1 | .csproj | TextMate/AvaloniaEdit | mit | AvaloniaUI/AvaloniaEdit |
10057703 | <NME> AvaloniaEdit.TextMate.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<LangVersion>latest</LangVersion>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\AvaloniaEdit\AvaloniaEdit.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="TextMateSharp" Version="$(TextMateSharpVersion)" />
<PackageReference Include="TextMateSharp.Grammars" Version="$(TextMateSharpVersion)" />
</ItemGroup>
</Project>
</ItemGroup>
<ItemGroup>
<PackageReference Include="TextMateSharp" Version="1.0.18" />
</ItemGroup>
</Project>
<MSG> Update to TextMateSharp 1.0.19
<DFF> @@ -19,7 +19,7 @@
</ItemGroup>
<ItemGroup>
- <PackageReference Include="TextMateSharp" Version="1.0.18" />
+ <PackageReference Include="TextMateSharp" Version="1.0.19" />
</ItemGroup>
</Project>
| 1 | Update to TextMateSharp 1.0.19 | 1 | .csproj | TextMate/AvaloniaEdit | mit | AvaloniaUI/AvaloniaEdit |
10057704 | <NME> AvaloniaEdit.TextMate.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<LangVersion>latest</LangVersion>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\AvaloniaEdit\AvaloniaEdit.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="TextMateSharp" Version="$(TextMateSharpVersion)" />
<PackageReference Include="TextMateSharp.Grammars" Version="$(TextMateSharpVersion)" />
</ItemGroup>
</Project>
</ItemGroup>
<ItemGroup>
<PackageReference Include="TextMateSharp" Version="1.0.18" />
</ItemGroup>
</Project>
<MSG> Update to TextMateSharp 1.0.19
<DFF> @@ -19,7 +19,7 @@
</ItemGroup>
<ItemGroup>
- <PackageReference Include="TextMateSharp" Version="1.0.18" />
+ <PackageReference Include="TextMateSharp" Version="1.0.19" />
</ItemGroup>
</Project>
| 1 | Update to TextMateSharp 1.0.19 | 1 | .csproj | TextMate/AvaloniaEdit | mit | AvaloniaUI/AvaloniaEdit |
10057705 | <NME> AvaloniaEdit.TextMate.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<LangVersion>latest</LangVersion>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\AvaloniaEdit\AvaloniaEdit.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="TextMateSharp" Version="$(TextMateSharpVersion)" />
<PackageReference Include="TextMateSharp.Grammars" Version="$(TextMateSharpVersion)" />
</ItemGroup>
</Project>
</ItemGroup>
<ItemGroup>
<PackageReference Include="TextMateSharp" Version="1.0.18" />
</ItemGroup>
</Project>
<MSG> Update to TextMateSharp 1.0.19
<DFF> @@ -19,7 +19,7 @@
</ItemGroup>
<ItemGroup>
- <PackageReference Include="TextMateSharp" Version="1.0.18" />
+ <PackageReference Include="TextMateSharp" Version="1.0.19" />
</ItemGroup>
</Project>
| 1 | Update to TextMateSharp 1.0.19 | 1 | .csproj | TextMate/AvaloniaEdit | mit | AvaloniaUI/AvaloniaEdit |
10057706 | <NME> AvaloniaEdit.TextMate.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<LangVersion>latest</LangVersion>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\AvaloniaEdit\AvaloniaEdit.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="TextMateSharp" Version="$(TextMateSharpVersion)" />
<PackageReference Include="TextMateSharp.Grammars" Version="$(TextMateSharpVersion)" />
</ItemGroup>
</Project>
</ItemGroup>
<ItemGroup>
<PackageReference Include="TextMateSharp" Version="1.0.18" />
</ItemGroup>
</Project>
<MSG> Update to TextMateSharp 1.0.19
<DFF> @@ -19,7 +19,7 @@
</ItemGroup>
<ItemGroup>
- <PackageReference Include="TextMateSharp" Version="1.0.18" />
+ <PackageReference Include="TextMateSharp" Version="1.0.19" />
</ItemGroup>
</Project>
| 1 | Update to TextMateSharp 1.0.19 | 1 | .csproj | TextMate/AvaloniaEdit | mit | AvaloniaUI/AvaloniaEdit |
10057707 | <NME> AvaloniaEdit.TextMate.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<LangVersion>latest</LangVersion>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\AvaloniaEdit\AvaloniaEdit.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="TextMateSharp" Version="$(TextMateSharpVersion)" />
<PackageReference Include="TextMateSharp.Grammars" Version="$(TextMateSharpVersion)" />
</ItemGroup>
</Project>
</ItemGroup>
<ItemGroup>
<PackageReference Include="TextMateSharp" Version="1.0.18" />
</ItemGroup>
</Project>
<MSG> Update to TextMateSharp 1.0.19
<DFF> @@ -19,7 +19,7 @@
</ItemGroup>
<ItemGroup>
- <PackageReference Include="TextMateSharp" Version="1.0.18" />
+ <PackageReference Include="TextMateSharp" Version="1.0.19" />
</ItemGroup>
</Project>
| 1 | Update to TextMateSharp 1.0.19 | 1 | .csproj | TextMate/AvaloniaEdit | mit | AvaloniaUI/AvaloniaEdit |
10057708 | <NME> AvaloniaEdit.TextMate.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<LangVersion>latest</LangVersion>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\AvaloniaEdit\AvaloniaEdit.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="TextMateSharp" Version="$(TextMateSharpVersion)" />
<PackageReference Include="TextMateSharp.Grammars" Version="$(TextMateSharpVersion)" />
</ItemGroup>
</Project>
</ItemGroup>
<ItemGroup>
<PackageReference Include="TextMateSharp" Version="1.0.18" />
</ItemGroup>
</Project>
<MSG> Update to TextMateSharp 1.0.19
<DFF> @@ -19,7 +19,7 @@
</ItemGroup>
<ItemGroup>
- <PackageReference Include="TextMateSharp" Version="1.0.18" />
+ <PackageReference Include="TextMateSharp" Version="1.0.19" />
</ItemGroup>
</Project>
| 1 | Update to TextMateSharp 1.0.19 | 1 | .csproj | TextMate/AvaloniaEdit | mit | AvaloniaUI/AvaloniaEdit |
10057709 | <NME> README.md
<BEF> # AvaloniaEdit
[](https://www.codefactor.io/repository/github/avaloniaui/avaloniaedit)
[](https://ci.appveyor.com/project/avaloniaui/avaloniaedit)
[](https://travis-ci.org/AvaloniaUI/AvaloniaEdit)
AvaloniaEdit supports features like:
* Syntax highlighting using [TextMate](https://github.com/danipen/TextMateSharp) grammars and themes.
* Code folding.
* Code completion.
* Fully customizable and extensible.
* Line numeration.
* Display whitespaces EOLs and tabs.
* Line virtualization.
* Multi-caret edition.
* Intra-column adornments.
* Word wrapping.
* Scrolling below document.
* Hyperlinks.
and many,many more!
AvaloniaEdit currently consists of 2 packages
* [Avalonia.AvaloniaEdit](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) well-known package that incudes text editor itself.
* [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) package that adds TextMate integration to the AvaloniaEdit.
### How to set up TextMate theme and syntax highlighting for my project?
First of all, if you want to use grammars supported by [TextMateSharp](https://github.com/danipen/TextMateSharp), should install the following packages:
- [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/)
- [TextMateSharp.Grammars](https://www.nuget.org/packages/TextMateSharp.Grammars/)
Alternatively, if you want to support your own grammars, you just need to install the AvaloniaEdit.TextMate package, and implement IRegistryOptions interface, that's currently the easiest way in case you want to use AvaloniaEdit with the set of grammars different from in-bundled TextMateSharp.Grammars.
```csharp
//First of all you need to have a reference for your TextEditor for it to be used inside AvaloniaEdit.TextMate project.
var _textEditor = this.FindControl<TextEditor>("Editor");
//Here we initialize RegistryOptions with the theme we want to use.
var _registryOptions = new RegistryOptions(ThemeName.DarkPlus);
//Initial setup of TextMate.
var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions);
//Here we are getting the language by the extension and right after that we are initializing grammar with this language.
//And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting!
_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id));
```

<MSG> Update README.md
<DFF> @@ -1,6 +1,5 @@
# AvaloniaEdit
-[](https://www.codefactor.io/repository/github/avaloniaui/avaloniaedit)
[](https://ci.appveyor.com/project/avaloniaui/avaloniaedit)
[](https://travis-ci.org/AvaloniaUI/AvaloniaEdit)
| 0 | Update README.md | 1 | .md | md | mit | AvaloniaUI/AvaloniaEdit |
10057710 | <NME> README.md
<BEF> # AvaloniaEdit
[](https://www.codefactor.io/repository/github/avaloniaui/avaloniaedit)
[](https://ci.appveyor.com/project/avaloniaui/avaloniaedit)
[](https://travis-ci.org/AvaloniaUI/AvaloniaEdit)
AvaloniaEdit supports features like:
* Syntax highlighting using [TextMate](https://github.com/danipen/TextMateSharp) grammars and themes.
* Code folding.
* Code completion.
* Fully customizable and extensible.
* Line numeration.
* Display whitespaces EOLs and tabs.
* Line virtualization.
* Multi-caret edition.
* Intra-column adornments.
* Word wrapping.
* Scrolling below document.
* Hyperlinks.
and many,many more!
AvaloniaEdit currently consists of 2 packages
* [Avalonia.AvaloniaEdit](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) well-known package that incudes text editor itself.
* [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) package that adds TextMate integration to the AvaloniaEdit.
### How to set up TextMate theme and syntax highlighting for my project?
First of all, if you want to use grammars supported by [TextMateSharp](https://github.com/danipen/TextMateSharp), should install the following packages:
- [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/)
- [TextMateSharp.Grammars](https://www.nuget.org/packages/TextMateSharp.Grammars/)
Alternatively, if you want to support your own grammars, you just need to install the AvaloniaEdit.TextMate package, and implement IRegistryOptions interface, that's currently the easiest way in case you want to use AvaloniaEdit with the set of grammars different from in-bundled TextMateSharp.Grammars.
```csharp
//First of all you need to have a reference for your TextEditor for it to be used inside AvaloniaEdit.TextMate project.
var _textEditor = this.FindControl<TextEditor>("Editor");
//Here we initialize RegistryOptions with the theme we want to use.
var _registryOptions = new RegistryOptions(ThemeName.DarkPlus);
//Initial setup of TextMate.
var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions);
//Here we are getting the language by the extension and right after that we are initializing grammar with this language.
//And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting!
_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id));
```

<MSG> Update README.md
<DFF> @@ -1,6 +1,5 @@
# AvaloniaEdit
-[](https://www.codefactor.io/repository/github/avaloniaui/avaloniaedit)
[](https://ci.appveyor.com/project/avaloniaui/avaloniaedit)
[](https://travis-ci.org/AvaloniaUI/AvaloniaEdit)
| 0 | Update README.md | 1 | .md | md | mit | AvaloniaUI/AvaloniaEdit |
10057711 | <NME> README.md
<BEF> # AvaloniaEdit
[](https://www.codefactor.io/repository/github/avaloniaui/avaloniaedit)
[](https://ci.appveyor.com/project/avaloniaui/avaloniaedit)
[](https://travis-ci.org/AvaloniaUI/AvaloniaEdit)
AvaloniaEdit supports features like:
* Syntax highlighting using [TextMate](https://github.com/danipen/TextMateSharp) grammars and themes.
* Code folding.
* Code completion.
* Fully customizable and extensible.
* Line numeration.
* Display whitespaces EOLs and tabs.
* Line virtualization.
* Multi-caret edition.
* Intra-column adornments.
* Word wrapping.
* Scrolling below document.
* Hyperlinks.
and many,many more!
AvaloniaEdit currently consists of 2 packages
* [Avalonia.AvaloniaEdit](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) well-known package that incudes text editor itself.
* [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) package that adds TextMate integration to the AvaloniaEdit.
### How to set up TextMate theme and syntax highlighting for my project?
First of all, if you want to use grammars supported by [TextMateSharp](https://github.com/danipen/TextMateSharp), should install the following packages:
- [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/)
- [TextMateSharp.Grammars](https://www.nuget.org/packages/TextMateSharp.Grammars/)
Alternatively, if you want to support your own grammars, you just need to install the AvaloniaEdit.TextMate package, and implement IRegistryOptions interface, that's currently the easiest way in case you want to use AvaloniaEdit with the set of grammars different from in-bundled TextMateSharp.Grammars.
```csharp
//First of all you need to have a reference for your TextEditor for it to be used inside AvaloniaEdit.TextMate project.
var _textEditor = this.FindControl<TextEditor>("Editor");
//Here we initialize RegistryOptions with the theme we want to use.
var _registryOptions = new RegistryOptions(ThemeName.DarkPlus);
//Initial setup of TextMate.
var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions);
//Here we are getting the language by the extension and right after that we are initializing grammar with this language.
//And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting!
_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id));
```

<MSG> Update README.md
<DFF> @@ -1,6 +1,5 @@
# AvaloniaEdit
-[](https://www.codefactor.io/repository/github/avaloniaui/avaloniaedit)
[](https://ci.appveyor.com/project/avaloniaui/avaloniaedit)
[](https://travis-ci.org/AvaloniaUI/AvaloniaEdit)
| 0 | Update README.md | 1 | .md | md | mit | AvaloniaUI/AvaloniaEdit |
10057712 | <NME> README.md
<BEF> # AvaloniaEdit
[](https://www.codefactor.io/repository/github/avaloniaui/avaloniaedit)
[](https://ci.appveyor.com/project/avaloniaui/avaloniaedit)
[](https://travis-ci.org/AvaloniaUI/AvaloniaEdit)
AvaloniaEdit supports features like:
* Syntax highlighting using [TextMate](https://github.com/danipen/TextMateSharp) grammars and themes.
* Code folding.
* Code completion.
* Fully customizable and extensible.
* Line numeration.
* Display whitespaces EOLs and tabs.
* Line virtualization.
* Multi-caret edition.
* Intra-column adornments.
* Word wrapping.
* Scrolling below document.
* Hyperlinks.
and many,many more!
AvaloniaEdit currently consists of 2 packages
* [Avalonia.AvaloniaEdit](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) well-known package that incudes text editor itself.
* [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) package that adds TextMate integration to the AvaloniaEdit.
### How to set up TextMate theme and syntax highlighting for my project?
First of all, if you want to use grammars supported by [TextMateSharp](https://github.com/danipen/TextMateSharp), should install the following packages:
- [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/)
- [TextMateSharp.Grammars](https://www.nuget.org/packages/TextMateSharp.Grammars/)
Alternatively, if you want to support your own grammars, you just need to install the AvaloniaEdit.TextMate package, and implement IRegistryOptions interface, that's currently the easiest way in case you want to use AvaloniaEdit with the set of grammars different from in-bundled TextMateSharp.Grammars.
```csharp
//First of all you need to have a reference for your TextEditor for it to be used inside AvaloniaEdit.TextMate project.
var _textEditor = this.FindControl<TextEditor>("Editor");
//Here we initialize RegistryOptions with the theme we want to use.
var _registryOptions = new RegistryOptions(ThemeName.DarkPlus);
//Initial setup of TextMate.
var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions);
//Here we are getting the language by the extension and right after that we are initializing grammar with this language.
//And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting!
_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id));
```

<MSG> Update README.md
<DFF> @@ -1,6 +1,5 @@
# AvaloniaEdit
-[](https://www.codefactor.io/repository/github/avaloniaui/avaloniaedit)
[](https://ci.appveyor.com/project/avaloniaui/avaloniaedit)
[](https://travis-ci.org/AvaloniaUI/AvaloniaEdit)
| 0 | Update README.md | 1 | .md | md | mit | AvaloniaUI/AvaloniaEdit |
10057713 | <NME> README.md
<BEF> # AvaloniaEdit
[](https://www.codefactor.io/repository/github/avaloniaui/avaloniaedit)
[](https://ci.appveyor.com/project/avaloniaui/avaloniaedit)
[](https://travis-ci.org/AvaloniaUI/AvaloniaEdit)
AvaloniaEdit supports features like:
* Syntax highlighting using [TextMate](https://github.com/danipen/TextMateSharp) grammars and themes.
* Code folding.
* Code completion.
* Fully customizable and extensible.
* Line numeration.
* Display whitespaces EOLs and tabs.
* Line virtualization.
* Multi-caret edition.
* Intra-column adornments.
* Word wrapping.
* Scrolling below document.
* Hyperlinks.
and many,many more!
AvaloniaEdit currently consists of 2 packages
* [Avalonia.AvaloniaEdit](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) well-known package that incudes text editor itself.
* [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) package that adds TextMate integration to the AvaloniaEdit.
### How to set up TextMate theme and syntax highlighting for my project?
First of all, if you want to use grammars supported by [TextMateSharp](https://github.com/danipen/TextMateSharp), should install the following packages:
- [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/)
- [TextMateSharp.Grammars](https://www.nuget.org/packages/TextMateSharp.Grammars/)
Alternatively, if you want to support your own grammars, you just need to install the AvaloniaEdit.TextMate package, and implement IRegistryOptions interface, that's currently the easiest way in case you want to use AvaloniaEdit with the set of grammars different from in-bundled TextMateSharp.Grammars.
```csharp
//First of all you need to have a reference for your TextEditor for it to be used inside AvaloniaEdit.TextMate project.
var _textEditor = this.FindControl<TextEditor>("Editor");
//Here we initialize RegistryOptions with the theme we want to use.
var _registryOptions = new RegistryOptions(ThemeName.DarkPlus);
//Initial setup of TextMate.
var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions);
//Here we are getting the language by the extension and right after that we are initializing grammar with this language.
//And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting!
_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id));
```

<MSG> Update README.md
<DFF> @@ -1,6 +1,5 @@
# AvaloniaEdit
-[](https://www.codefactor.io/repository/github/avaloniaui/avaloniaedit)
[](https://ci.appveyor.com/project/avaloniaui/avaloniaedit)
[](https://travis-ci.org/AvaloniaUI/AvaloniaEdit)
| 0 | Update README.md | 1 | .md | md | mit | AvaloniaUI/AvaloniaEdit |
10057714 | <NME> README.md
<BEF> # AvaloniaEdit
[](https://www.codefactor.io/repository/github/avaloniaui/avaloniaedit)
[](https://ci.appveyor.com/project/avaloniaui/avaloniaedit)
[](https://travis-ci.org/AvaloniaUI/AvaloniaEdit)
AvaloniaEdit supports features like:
* Syntax highlighting using [TextMate](https://github.com/danipen/TextMateSharp) grammars and themes.
* Code folding.
* Code completion.
* Fully customizable and extensible.
* Line numeration.
* Display whitespaces EOLs and tabs.
* Line virtualization.
* Multi-caret edition.
* Intra-column adornments.
* Word wrapping.
* Scrolling below document.
* Hyperlinks.
and many,many more!
AvaloniaEdit currently consists of 2 packages
* [Avalonia.AvaloniaEdit](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) well-known package that incudes text editor itself.
* [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) package that adds TextMate integration to the AvaloniaEdit.
### How to set up TextMate theme and syntax highlighting for my project?
First of all, if you want to use grammars supported by [TextMateSharp](https://github.com/danipen/TextMateSharp), should install the following packages:
- [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/)
- [TextMateSharp.Grammars](https://www.nuget.org/packages/TextMateSharp.Grammars/)
Alternatively, if you want to support your own grammars, you just need to install the AvaloniaEdit.TextMate package, and implement IRegistryOptions interface, that's currently the easiest way in case you want to use AvaloniaEdit with the set of grammars different from in-bundled TextMateSharp.Grammars.
```csharp
//First of all you need to have a reference for your TextEditor for it to be used inside AvaloniaEdit.TextMate project.
var _textEditor = this.FindControl<TextEditor>("Editor");
//Here we initialize RegistryOptions with the theme we want to use.
var _registryOptions = new RegistryOptions(ThemeName.DarkPlus);
//Initial setup of TextMate.
var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions);
//Here we are getting the language by the extension and right after that we are initializing grammar with this language.
//And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting!
_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id));
```

<MSG> Update README.md
<DFF> @@ -1,6 +1,5 @@
# AvaloniaEdit
-[](https://www.codefactor.io/repository/github/avaloniaui/avaloniaedit)
[](https://ci.appveyor.com/project/avaloniaui/avaloniaedit)
[](https://travis-ci.org/AvaloniaUI/AvaloniaEdit)
| 0 | Update README.md | 1 | .md | md | mit | AvaloniaUI/AvaloniaEdit |
10057715 | <NME> README.md
<BEF> # AvaloniaEdit
[](https://www.codefactor.io/repository/github/avaloniaui/avaloniaedit)
[](https://ci.appveyor.com/project/avaloniaui/avaloniaedit)
[](https://travis-ci.org/AvaloniaUI/AvaloniaEdit)
AvaloniaEdit supports features like:
* Syntax highlighting using [TextMate](https://github.com/danipen/TextMateSharp) grammars and themes.
* Code folding.
* Code completion.
* Fully customizable and extensible.
* Line numeration.
* Display whitespaces EOLs and tabs.
* Line virtualization.
* Multi-caret edition.
* Intra-column adornments.
* Word wrapping.
* Scrolling below document.
* Hyperlinks.
and many,many more!
AvaloniaEdit currently consists of 2 packages
* [Avalonia.AvaloniaEdit](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) well-known package that incudes text editor itself.
* [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) package that adds TextMate integration to the AvaloniaEdit.
### How to set up TextMate theme and syntax highlighting for my project?
First of all, if you want to use grammars supported by [TextMateSharp](https://github.com/danipen/TextMateSharp), should install the following packages:
- [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/)
- [TextMateSharp.Grammars](https://www.nuget.org/packages/TextMateSharp.Grammars/)
Alternatively, if you want to support your own grammars, you just need to install the AvaloniaEdit.TextMate package, and implement IRegistryOptions interface, that's currently the easiest way in case you want to use AvaloniaEdit with the set of grammars different from in-bundled TextMateSharp.Grammars.
```csharp
//First of all you need to have a reference for your TextEditor for it to be used inside AvaloniaEdit.TextMate project.
var _textEditor = this.FindControl<TextEditor>("Editor");
//Here we initialize RegistryOptions with the theme we want to use.
var _registryOptions = new RegistryOptions(ThemeName.DarkPlus);
//Initial setup of TextMate.
var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions);
//Here we are getting the language by the extension and right after that we are initializing grammar with this language.
//And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting!
_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id));
```

<MSG> Update README.md
<DFF> @@ -1,6 +1,5 @@
# AvaloniaEdit
-[](https://www.codefactor.io/repository/github/avaloniaui/avaloniaedit)
[](https://ci.appveyor.com/project/avaloniaui/avaloniaedit)
[](https://travis-ci.org/AvaloniaUI/AvaloniaEdit)
| 0 | Update README.md | 1 | .md | md | mit | AvaloniaUI/AvaloniaEdit |
10057716 | <NME> README.md
<BEF> # AvaloniaEdit
[](https://www.codefactor.io/repository/github/avaloniaui/avaloniaedit)
[](https://ci.appveyor.com/project/avaloniaui/avaloniaedit)
[](https://travis-ci.org/AvaloniaUI/AvaloniaEdit)
AvaloniaEdit supports features like:
* Syntax highlighting using [TextMate](https://github.com/danipen/TextMateSharp) grammars and themes.
* Code folding.
* Code completion.
* Fully customizable and extensible.
* Line numeration.
* Display whitespaces EOLs and tabs.
* Line virtualization.
* Multi-caret edition.
* Intra-column adornments.
* Word wrapping.
* Scrolling below document.
* Hyperlinks.
and many,many more!
AvaloniaEdit currently consists of 2 packages
* [Avalonia.AvaloniaEdit](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) well-known package that incudes text editor itself.
* [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) package that adds TextMate integration to the AvaloniaEdit.
### How to set up TextMate theme and syntax highlighting for my project?
First of all, if you want to use grammars supported by [TextMateSharp](https://github.com/danipen/TextMateSharp), should install the following packages:
- [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/)
- [TextMateSharp.Grammars](https://www.nuget.org/packages/TextMateSharp.Grammars/)
Alternatively, if you want to support your own grammars, you just need to install the AvaloniaEdit.TextMate package, and implement IRegistryOptions interface, that's currently the easiest way in case you want to use AvaloniaEdit with the set of grammars different from in-bundled TextMateSharp.Grammars.
```csharp
//First of all you need to have a reference for your TextEditor for it to be used inside AvaloniaEdit.TextMate project.
var _textEditor = this.FindControl<TextEditor>("Editor");
//Here we initialize RegistryOptions with the theme we want to use.
var _registryOptions = new RegistryOptions(ThemeName.DarkPlus);
//Initial setup of TextMate.
var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions);
//Here we are getting the language by the extension and right after that we are initializing grammar with this language.
//And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting!
_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id));
```

<MSG> Update README.md
<DFF> @@ -1,6 +1,5 @@
# AvaloniaEdit
-[](https://www.codefactor.io/repository/github/avaloniaui/avaloniaedit)
[](https://ci.appveyor.com/project/avaloniaui/avaloniaedit)
[](https://travis-ci.org/AvaloniaUI/AvaloniaEdit)
| 0 | Update README.md | 1 | .md | md | mit | AvaloniaUI/AvaloniaEdit |
10057717 | <NME> README.md
<BEF> # AvaloniaEdit
[](https://www.codefactor.io/repository/github/avaloniaui/avaloniaedit)
[](https://ci.appveyor.com/project/avaloniaui/avaloniaedit)
[](https://travis-ci.org/AvaloniaUI/AvaloniaEdit)
AvaloniaEdit supports features like:
* Syntax highlighting using [TextMate](https://github.com/danipen/TextMateSharp) grammars and themes.
* Code folding.
* Code completion.
* Fully customizable and extensible.
* Line numeration.
* Display whitespaces EOLs and tabs.
* Line virtualization.
* Multi-caret edition.
* Intra-column adornments.
* Word wrapping.
* Scrolling below document.
* Hyperlinks.
and many,many more!
AvaloniaEdit currently consists of 2 packages
* [Avalonia.AvaloniaEdit](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) well-known package that incudes text editor itself.
* [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) package that adds TextMate integration to the AvaloniaEdit.
### How to set up TextMate theme and syntax highlighting for my project?
First of all, if you want to use grammars supported by [TextMateSharp](https://github.com/danipen/TextMateSharp), should install the following packages:
- [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/)
- [TextMateSharp.Grammars](https://www.nuget.org/packages/TextMateSharp.Grammars/)
Alternatively, if you want to support your own grammars, you just need to install the AvaloniaEdit.TextMate package, and implement IRegistryOptions interface, that's currently the easiest way in case you want to use AvaloniaEdit with the set of grammars different from in-bundled TextMateSharp.Grammars.
```csharp
//First of all you need to have a reference for your TextEditor for it to be used inside AvaloniaEdit.TextMate project.
var _textEditor = this.FindControl<TextEditor>("Editor");
//Here we initialize RegistryOptions with the theme we want to use.
var _registryOptions = new RegistryOptions(ThemeName.DarkPlus);
//Initial setup of TextMate.
var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions);
//Here we are getting the language by the extension and right after that we are initializing grammar with this language.
//And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting!
_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id));
```

<MSG> Update README.md
<DFF> @@ -1,6 +1,5 @@
# AvaloniaEdit
-[](https://www.codefactor.io/repository/github/avaloniaui/avaloniaedit)
[](https://ci.appveyor.com/project/avaloniaui/avaloniaedit)
[](https://travis-ci.org/AvaloniaUI/AvaloniaEdit)
| 0 | Update README.md | 1 | .md | md | mit | AvaloniaUI/AvaloniaEdit |
10057718 | <NME> README.md
<BEF> # AvaloniaEdit
[](https://www.codefactor.io/repository/github/avaloniaui/avaloniaedit)
[](https://ci.appveyor.com/project/avaloniaui/avaloniaedit)
[](https://travis-ci.org/AvaloniaUI/AvaloniaEdit)
AvaloniaEdit supports features like:
* Syntax highlighting using [TextMate](https://github.com/danipen/TextMateSharp) grammars and themes.
* Code folding.
* Code completion.
* Fully customizable and extensible.
* Line numeration.
* Display whitespaces EOLs and tabs.
* Line virtualization.
* Multi-caret edition.
* Intra-column adornments.
* Word wrapping.
* Scrolling below document.
* Hyperlinks.
and many,many more!
AvaloniaEdit currently consists of 2 packages
* [Avalonia.AvaloniaEdit](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) well-known package that incudes text editor itself.
* [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) package that adds TextMate integration to the AvaloniaEdit.
### How to set up TextMate theme and syntax highlighting for my project?
First of all, if you want to use grammars supported by [TextMateSharp](https://github.com/danipen/TextMateSharp), should install the following packages:
- [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/)
- [TextMateSharp.Grammars](https://www.nuget.org/packages/TextMateSharp.Grammars/)
Alternatively, if you want to support your own grammars, you just need to install the AvaloniaEdit.TextMate package, and implement IRegistryOptions interface, that's currently the easiest way in case you want to use AvaloniaEdit with the set of grammars different from in-bundled TextMateSharp.Grammars.
```csharp
//First of all you need to have a reference for your TextEditor for it to be used inside AvaloniaEdit.TextMate project.
var _textEditor = this.FindControl<TextEditor>("Editor");
//Here we initialize RegistryOptions with the theme we want to use.
var _registryOptions = new RegistryOptions(ThemeName.DarkPlus);
//Initial setup of TextMate.
var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions);
//Here we are getting the language by the extension and right after that we are initializing grammar with this language.
//And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting!
_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id));
```

<MSG> Update README.md
<DFF> @@ -1,6 +1,5 @@
# AvaloniaEdit
-[](https://www.codefactor.io/repository/github/avaloniaui/avaloniaedit)
[](https://ci.appveyor.com/project/avaloniaui/avaloniaedit)
[](https://travis-ci.org/AvaloniaUI/AvaloniaEdit)
| 0 | Update README.md | 1 | .md | md | mit | AvaloniaUI/AvaloniaEdit |
10057719 | <NME> README.md
<BEF> # AvaloniaEdit
[](https://www.codefactor.io/repository/github/avaloniaui/avaloniaedit)
[](https://ci.appveyor.com/project/avaloniaui/avaloniaedit)
[](https://travis-ci.org/AvaloniaUI/AvaloniaEdit)
AvaloniaEdit supports features like:
* Syntax highlighting using [TextMate](https://github.com/danipen/TextMateSharp) grammars and themes.
* Code folding.
* Code completion.
* Fully customizable and extensible.
* Line numeration.
* Display whitespaces EOLs and tabs.
* Line virtualization.
* Multi-caret edition.
* Intra-column adornments.
* Word wrapping.
* Scrolling below document.
* Hyperlinks.
and many,many more!
AvaloniaEdit currently consists of 2 packages
* [Avalonia.AvaloniaEdit](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) well-known package that incudes text editor itself.
* [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) package that adds TextMate integration to the AvaloniaEdit.
### How to set up TextMate theme and syntax highlighting for my project?
First of all, if you want to use grammars supported by [TextMateSharp](https://github.com/danipen/TextMateSharp), should install the following packages:
- [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/)
- [TextMateSharp.Grammars](https://www.nuget.org/packages/TextMateSharp.Grammars/)
Alternatively, if you want to support your own grammars, you just need to install the AvaloniaEdit.TextMate package, and implement IRegistryOptions interface, that's currently the easiest way in case you want to use AvaloniaEdit with the set of grammars different from in-bundled TextMateSharp.Grammars.
```csharp
//First of all you need to have a reference for your TextEditor for it to be used inside AvaloniaEdit.TextMate project.
var _textEditor = this.FindControl<TextEditor>("Editor");
//Here we initialize RegistryOptions with the theme we want to use.
var _registryOptions = new RegistryOptions(ThemeName.DarkPlus);
//Initial setup of TextMate.
var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions);
//Here we are getting the language by the extension and right after that we are initializing grammar with this language.
//And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting!
_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id));
```

<MSG> Update README.md
<DFF> @@ -1,6 +1,5 @@
# AvaloniaEdit
-[](https://www.codefactor.io/repository/github/avaloniaui/avaloniaedit)
[](https://ci.appveyor.com/project/avaloniaui/avaloniaedit)
[](https://travis-ci.org/AvaloniaUI/AvaloniaEdit)
| 0 | Update README.md | 1 | .md | md | mit | AvaloniaUI/AvaloniaEdit |
10057720 | <NME> README.md
<BEF> # AvaloniaEdit
[](https://www.codefactor.io/repository/github/avaloniaui/avaloniaedit)
[](https://ci.appveyor.com/project/avaloniaui/avaloniaedit)
[](https://travis-ci.org/AvaloniaUI/AvaloniaEdit)
AvaloniaEdit supports features like:
* Syntax highlighting using [TextMate](https://github.com/danipen/TextMateSharp) grammars and themes.
* Code folding.
* Code completion.
* Fully customizable and extensible.
* Line numeration.
* Display whitespaces EOLs and tabs.
* Line virtualization.
* Multi-caret edition.
* Intra-column adornments.
* Word wrapping.
* Scrolling below document.
* Hyperlinks.
and many,many more!
AvaloniaEdit currently consists of 2 packages
* [Avalonia.AvaloniaEdit](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) well-known package that incudes text editor itself.
* [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) package that adds TextMate integration to the AvaloniaEdit.
### How to set up TextMate theme and syntax highlighting for my project?
First of all, if you want to use grammars supported by [TextMateSharp](https://github.com/danipen/TextMateSharp), should install the following packages:
- [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/)
- [TextMateSharp.Grammars](https://www.nuget.org/packages/TextMateSharp.Grammars/)
Alternatively, if you want to support your own grammars, you just need to install the AvaloniaEdit.TextMate package, and implement IRegistryOptions interface, that's currently the easiest way in case you want to use AvaloniaEdit with the set of grammars different from in-bundled TextMateSharp.Grammars.
```csharp
//First of all you need to have a reference for your TextEditor for it to be used inside AvaloniaEdit.TextMate project.
var _textEditor = this.FindControl<TextEditor>("Editor");
//Here we initialize RegistryOptions with the theme we want to use.
var _registryOptions = new RegistryOptions(ThemeName.DarkPlus);
//Initial setup of TextMate.
var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions);
//Here we are getting the language by the extension and right after that we are initializing grammar with this language.
//And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting!
_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id));
```

<MSG> Update README.md
<DFF> @@ -1,6 +1,5 @@
# AvaloniaEdit
-[](https://www.codefactor.io/repository/github/avaloniaui/avaloniaedit)
[](https://ci.appveyor.com/project/avaloniaui/avaloniaedit)
[](https://travis-ci.org/AvaloniaUI/AvaloniaEdit)
| 0 | Update README.md | 1 | .md | md | mit | AvaloniaUI/AvaloniaEdit |
10057721 | <NME> README.md
<BEF> # AvaloniaEdit
[](https://www.codefactor.io/repository/github/avaloniaui/avaloniaedit)
[](https://ci.appveyor.com/project/avaloniaui/avaloniaedit)
[](https://travis-ci.org/AvaloniaUI/AvaloniaEdit)
AvaloniaEdit supports features like:
* Syntax highlighting using [TextMate](https://github.com/danipen/TextMateSharp) grammars and themes.
* Code folding.
* Code completion.
* Fully customizable and extensible.
* Line numeration.
* Display whitespaces EOLs and tabs.
* Line virtualization.
* Multi-caret edition.
* Intra-column adornments.
* Word wrapping.
* Scrolling below document.
* Hyperlinks.
and many,many more!
AvaloniaEdit currently consists of 2 packages
* [Avalonia.AvaloniaEdit](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) well-known package that incudes text editor itself.
* [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) package that adds TextMate integration to the AvaloniaEdit.
### How to set up TextMate theme and syntax highlighting for my project?
First of all, if you want to use grammars supported by [TextMateSharp](https://github.com/danipen/TextMateSharp), should install the following packages:
- [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/)
- [TextMateSharp.Grammars](https://www.nuget.org/packages/TextMateSharp.Grammars/)
Alternatively, if you want to support your own grammars, you just need to install the AvaloniaEdit.TextMate package, and implement IRegistryOptions interface, that's currently the easiest way in case you want to use AvaloniaEdit with the set of grammars different from in-bundled TextMateSharp.Grammars.
```csharp
//First of all you need to have a reference for your TextEditor for it to be used inside AvaloniaEdit.TextMate project.
var _textEditor = this.FindControl<TextEditor>("Editor");
//Here we initialize RegistryOptions with the theme we want to use.
var _registryOptions = new RegistryOptions(ThemeName.DarkPlus);
//Initial setup of TextMate.
var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions);
//Here we are getting the language by the extension and right after that we are initializing grammar with this language.
//And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting!
_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id));
```

<MSG> Update README.md
<DFF> @@ -1,6 +1,5 @@
# AvaloniaEdit
-[](https://www.codefactor.io/repository/github/avaloniaui/avaloniaedit)
[](https://ci.appveyor.com/project/avaloniaui/avaloniaedit)
[](https://travis-ci.org/AvaloniaUI/AvaloniaEdit)
| 0 | Update README.md | 1 | .md | md | mit | AvaloniaUI/AvaloniaEdit |
10057722 | <NME> README.md
<BEF> # AvaloniaEdit
[](https://www.codefactor.io/repository/github/avaloniaui/avaloniaedit)
[](https://ci.appveyor.com/project/avaloniaui/avaloniaedit)
[](https://travis-ci.org/AvaloniaUI/AvaloniaEdit)
AvaloniaEdit supports features like:
* Syntax highlighting using [TextMate](https://github.com/danipen/TextMateSharp) grammars and themes.
* Code folding.
* Code completion.
* Fully customizable and extensible.
* Line numeration.
* Display whitespaces EOLs and tabs.
* Line virtualization.
* Multi-caret edition.
* Intra-column adornments.
* Word wrapping.
* Scrolling below document.
* Hyperlinks.
and many,many more!
AvaloniaEdit currently consists of 2 packages
* [Avalonia.AvaloniaEdit](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) well-known package that incudes text editor itself.
* [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) package that adds TextMate integration to the AvaloniaEdit.
### How to set up TextMate theme and syntax highlighting for my project?
First of all, if you want to use grammars supported by [TextMateSharp](https://github.com/danipen/TextMateSharp), should install the following packages:
- [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/)
- [TextMateSharp.Grammars](https://www.nuget.org/packages/TextMateSharp.Grammars/)
Alternatively, if you want to support your own grammars, you just need to install the AvaloniaEdit.TextMate package, and implement IRegistryOptions interface, that's currently the easiest way in case you want to use AvaloniaEdit with the set of grammars different from in-bundled TextMateSharp.Grammars.
```csharp
//First of all you need to have a reference for your TextEditor for it to be used inside AvaloniaEdit.TextMate project.
var _textEditor = this.FindControl<TextEditor>("Editor");
//Here we initialize RegistryOptions with the theme we want to use.
var _registryOptions = new RegistryOptions(ThemeName.DarkPlus);
//Initial setup of TextMate.
var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions);
//Here we are getting the language by the extension and right after that we are initializing grammar with this language.
//And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting!
_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id));
```

<MSG> Update README.md
<DFF> @@ -1,6 +1,5 @@
# AvaloniaEdit
-[](https://www.codefactor.io/repository/github/avaloniaui/avaloniaedit)
[](https://ci.appveyor.com/project/avaloniaui/avaloniaedit)
[](https://travis-ci.org/AvaloniaUI/AvaloniaEdit)
| 0 | Update README.md | 1 | .md | md | mit | AvaloniaUI/AvaloniaEdit |
10057723 | <NME> README.md
<BEF> # AvaloniaEdit
[](https://www.codefactor.io/repository/github/avaloniaui/avaloniaedit)
[](https://ci.appveyor.com/project/avaloniaui/avaloniaedit)
[](https://travis-ci.org/AvaloniaUI/AvaloniaEdit)
AvaloniaEdit supports features like:
* Syntax highlighting using [TextMate](https://github.com/danipen/TextMateSharp) grammars and themes.
* Code folding.
* Code completion.
* Fully customizable and extensible.
* Line numeration.
* Display whitespaces EOLs and tabs.
* Line virtualization.
* Multi-caret edition.
* Intra-column adornments.
* Word wrapping.
* Scrolling below document.
* Hyperlinks.
and many,many more!
AvaloniaEdit currently consists of 2 packages
* [Avalonia.AvaloniaEdit](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) well-known package that incudes text editor itself.
* [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) package that adds TextMate integration to the AvaloniaEdit.
### How to set up TextMate theme and syntax highlighting for my project?
First of all, if you want to use grammars supported by [TextMateSharp](https://github.com/danipen/TextMateSharp), should install the following packages:
- [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/)
- [TextMateSharp.Grammars](https://www.nuget.org/packages/TextMateSharp.Grammars/)
Alternatively, if you want to support your own grammars, you just need to install the AvaloniaEdit.TextMate package, and implement IRegistryOptions interface, that's currently the easiest way in case you want to use AvaloniaEdit with the set of grammars different from in-bundled TextMateSharp.Grammars.
```csharp
//First of all you need to have a reference for your TextEditor for it to be used inside AvaloniaEdit.TextMate project.
var _textEditor = this.FindControl<TextEditor>("Editor");
//Here we initialize RegistryOptions with the theme we want to use.
var _registryOptions = new RegistryOptions(ThemeName.DarkPlus);
//Initial setup of TextMate.
var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions);
//Here we are getting the language by the extension and right after that we are initializing grammar with this language.
//And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting!
_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id));
```

<MSG> Update README.md
<DFF> @@ -1,6 +1,5 @@
# AvaloniaEdit
-[](https://www.codefactor.io/repository/github/avaloniaui/avaloniaedit)
[](https://ci.appveyor.com/project/avaloniaui/avaloniaedit)
[](https://travis-ci.org/AvaloniaUI/AvaloniaEdit)
| 0 | Update README.md | 1 | .md | md | mit | AvaloniaUI/AvaloniaEdit |
10057724 | <NME> CompletionList.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.Collections.ObjectModel;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml.Templates;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.CodeCompletion
{
/// <summary>
/// The listbox used inside the CompletionWindow, contains CompletionListBox.
/// </summary>
public class CompletionList : TemplatedControl
{
public CompletionList()
{
DoubleTapped += OnDoubleTapped;
}
/// <summary>
/// If true, the CompletionList is filtered to show only matching items. Also enables search by substring.
/// If false, enables the old behavior: no filtering, search by string.StartsWith.
/// </summary>
public bool IsFiltering { get; set; } = true;
/// <summary>
/// Dependency property for <see cref="EmptyTemplate" />.
/// </summary>
public static readonly StyledProperty<ControlTemplate> EmptyTemplateProperty =
AvaloniaProperty.Register<CompletionList, ControlTemplate>(nameof(EmptyTemplate));
/// <summary>
/// Content of EmptyTemplate will be shown when CompletionList contains no items.
/// If EmptyTemplate is null, nothing will be shown.
/// </summary>
public ControlTemplate EmptyTemplate
{
get => GetValue(EmptyTemplateProperty);
set => SetValue(EmptyTemplateProperty, value);
}
/// <summary>
/// Is raised when the completion list indicates that the user has chosen
/// an entry to be completed.
/// </summary>
public event EventHandler InsertionRequested;
/// <summary>
/// Raises the InsertionRequested event.
/// </summary>
public void RequestInsertion(EventArgs e)
{
InsertionRequested?.Invoke(this, e);
}
private CompletionListBox _listBox;
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
_listBox = e.NameScope.Find("PART_ListBox") as CompletionListBox;
if (_listBox != null)
{
_listBox.Items = _completionData;
}
}
/// <summary>
/// Gets the list box.
/// </summary>
public CompletionListBox ListBox
{
get
{
if (_listBox == null)
ApplyTemplate();
return _listBox;
}
}
/// <summary>
/// Gets the scroll viewer used in this list box.
/// </summary>
public ScrollViewer ScrollViewer => _listBox?.ScrollViewer;
private readonly ObservableCollection<ICompletionData> _completionData = new ObservableCollection<ICompletionData>();
/// <summary>
/// Gets the list to which completion data can be added.
/// </summary>
public IList<ICompletionData> CompletionData => _completionData;
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (!e.Handled)
{
HandleKey(e);
}
}
/// <summary>
/// Handles a key press. Used to let the completion list handle key presses while the
/// focus is still on the text editor.
/// </summary>
public void HandleKey(KeyEventArgs e)
{
if (_listBox == null)
return;
// We have to do some key handling manually, because the default doesn't work with
// our simulated events.
// Also, the default PageUp/PageDown implementation changes the focus, so we avoid it.
switch (e.Key)
{
case Key.Down:
e.Handled = true;
_listBox.SelectIndex(_listBox.SelectedIndex + 1);
break;
case Key.Up:
e.Handled = true;
_listBox.SelectIndex(_listBox.SelectedIndex - 1);
break;
case Key.PageDown:
e.Handled = true;
_listBox.SelectIndex(_listBox.SelectedIndex + _listBox.VisibleItemCount);
break;
case Key.PageUp:
e.Handled = true;
_listBox.SelectIndex(_listBox.SelectedIndex - _listBox.VisibleItemCount);
break;
case Key.Home:
e.Handled = true;
_listBox.SelectIndex(0);
break;
case Key.End:
e.Handled = true;
_listBox.SelectIndex(_listBox.ItemCount - 1);
break;
case Key.Tab:
case Key.Enter:
if(CurrentList.Count > 0)
{
e.Handled = true;
RequestInsertion(e);
}
break;
}
}
protected void OnDoubleTapped(object sender, RoutedEventArgs e)
{
//TODO TEST
if (((AvaloniaObject)e.Source).VisualAncestorsAndSelf()
.TakeWhile(obj => obj != this).Any(obj => obj is ListBoxItem))
{
e.Handled = true;
RequestInsertion(e);
}
}
/// <summary>
/// Gets/Sets the selected item.
/// </summary>
/// <remarks>
/// The setter of this property does not scroll to the selected item.
/// You might want to also call <see cref="ScrollIntoView"/>.
/// </remarks>
public ICompletionData SelectedItem
{
get => _listBox?.SelectedItem as ICompletionData;
set
{
if (_listBox == null && value != null)
ApplyTemplate();
if (_listBox != null) // may still be null if ApplyTemplate fails, or if listBox and value both are null
_listBox.SelectedItem = value;
}
}
/// <summary>
/// Scrolls the specified item into view.
/// </summary>
public void ScrollIntoView(ICompletionData item)
{
if (_listBox == null)
ApplyTemplate();
_listBox?.ScrollIntoView(item);
}
/// <summary>
/// Occurs when the SelectedItem property changes.
/// </summary>
public event EventHandler<SelectionChangedEventArgs> SelectionChanged
{
add => AddHandler(SelectingItemsControl.SelectionChangedEvent, value);
remove => RemoveHandler(SelectingItemsControl.SelectionChangedEvent, value);
}
// SelectItem gets called twice for every typed character (once from FormatLine), this helps execute SelectItem only once
private string _currentText;
private ObservableCollection<ICompletionData> _currentList;
public List<ICompletionData> CurrentList
{
get => ListBox.Items.Cast<ICompletionData>().ToList();
}
/// <summary>
/// Selects the best match, and filter the items if turned on using <see cref="IsFiltering" />.
/// </summary>
public void SelectItem(string text)
{
if (text == _currentText)
return;
if (_listBox == null)
ApplyTemplate();
if (IsFiltering)
{
SelectItemFiltering(text);
}
else
{
SelectItemWithStart(text);
}
_currentText = text;
}
/// <summary>
/// Filters CompletionList items to show only those matching given query, and selects the best match.
/// </summary>
private void SelectItemFiltering(string query)
{
// if the user just typed one more character, don't filter all data but just filter what we are already displaying
var listToFilter = _currentList != null && !string.IsNullOrEmpty(_currentText) && !string.IsNullOrEmpty(query) &&
query.StartsWith(_currentText, StringComparison.Ordinal) ?
_currentList : _completionData;
var matchingItems =
from item in listToFilter
let quality = GetMatchQuality(item.Text, query)
where quality > 0
select new { Item = item, Quality = quality };
// e.g. "DateTimeKind k = (*cc here suggests DateTimeKind*)"
var suggestedItem = _listBox.SelectedIndex != -1 ? (ICompletionData)_listBox.SelectedItem : null;
var listBoxItems = new ObservableCollection<ICompletionData>();
var bestIndex = -1;
var bestQuality = -1;
double bestPriority = 0;
var i = 0;
foreach (var matchingItem in matchingItems)
{
var priority = matchingItem.Item == suggestedItem ? double.PositiveInfinity : matchingItem.Item.Priority;
var quality = matchingItem.Quality;
}
_currentList = listBoxItems;
_listBox.Items = null;
_listBox.Items = listBoxItems;
SelectIndexCentered(bestIndex);
}
i++;
}
_currentList = listBoxItems;
//_listBox.Items = null; Makes no sense? Tooltip disappeared because of this
_listBox.Items = listBoxItems;
SelectIndexCentered(bestIndex);
}
/// <summary>
/// Selects the item that starts with the specified query.
/// </summary>
private void SelectItemWithStart(string query)
{
if (string.IsNullOrEmpty(query))
return;
var suggestedIndex = _listBox.SelectedIndex;
var bestIndex = -1;
var bestQuality = -1;
double bestPriority = 0;
for (var i = 0; i < _completionData.Count; ++i)
{
var quality = GetMatchQuality(_completionData[i].Text, query);
if (quality < 0)
continue;
var priority = _completionData[i].Priority;
bool useThisItem;
if (bestQuality < quality)
{
useThisItem = true;
}
else
{
if (bestIndex == suggestedIndex)
{
useThisItem = false;
}
else if (i == suggestedIndex)
{
// prefer recommendedItem, regardless of its priority
useThisItem = bestQuality == quality;
}
else
{
useThisItem = bestQuality == quality && bestPriority < priority;
}
}
if (useThisItem)
{
bestIndex = i;
bestPriority = priority;
bestQuality = quality;
}
}
SelectIndexCentered(bestIndex);
}
private void SelectIndexCentered(int bestIndex)
{
if (bestIndex < 0)
{
_listBox.ClearSelection();
}
else
{
var firstItem = _listBox.FirstVisibleItem;
if (bestIndex < firstItem || firstItem + _listBox.VisibleItemCount <= bestIndex)
{
// CenterViewOn does nothing as CompletionListBox.ScrollViewer is null
_listBox.CenterViewOn(bestIndex);
_listBox.SelectIndex(bestIndex);
}
else
{
_listBox.SelectIndex(bestIndex);
}
}
}
private int GetMatchQuality(string itemText, string query)
{
if (itemText == null)
throw new ArgumentNullException(nameof(itemText), "ICompletionData.Text returned null");
// Qualities:
// 8 = full match case sensitive
// 7 = full match
// 6 = match start case sensitive
// 5 = match start
// 4 = match CamelCase when length of query is 1 or 2 characters
// 3 = match substring case sensitive
// 2 = match substring
// 1 = match CamelCase
// -1 = no match
if (query == itemText)
return 8;
if (string.Equals(itemText, query, StringComparison.CurrentCultureIgnoreCase))
return 7;
if (itemText.StartsWith(query, StringComparison.CurrentCulture))
return 6;
if (itemText.StartsWith(query, StringComparison.CurrentCultureIgnoreCase))
return 5;
bool? camelCaseMatch = null;
if (query.Length <= 2)
{
camelCaseMatch = CamelCaseMatch(itemText, query);
if (camelCaseMatch == true) return 4;
}
// search by substring, if filtering (i.e. new behavior) turned on
if (IsFiltering)
{
if (itemText.IndexOf(query, StringComparison.CurrentCulture) >= 0)
return 3;
if (itemText.IndexOf(query, StringComparison.CurrentCultureIgnoreCase) >= 0)
return 2;
}
if (!camelCaseMatch.HasValue)
camelCaseMatch = CamelCaseMatch(itemText, query);
if (camelCaseMatch == true)
return 1;
return -1;
}
private static bool CamelCaseMatch(string text, string query)
{
// We take the first letter of the text regardless of whether or not it's upper case so we match
// against camelCase text as well as PascalCase text ("cct" matches "camelCaseText")
var theFirstLetterOfEachWord = text.AsEnumerable()
.Take(1)
.Concat(text.AsEnumerable().Skip(1).Where(char.IsUpper));
var i = 0;
foreach (var letter in theFirstLetterOfEachWord)
{
if (i > query.Length - 1)
return true; // return true here for CamelCase partial match ("CQ" matches "CodeQualityAnalysis")
if (char.ToUpperInvariant(query[i]) != char.ToUpperInvariant(letter))
return false;
i++;
}
if (i >= query.Length)
return true;
return false;
}
}
}
<MSG> Fix tooltip disappearing
<DFF> @@ -285,7 +285,7 @@ namespace AvaloniaEdit.CodeCompletion
}
_currentList = listBoxItems;
- _listBox.Items = null;
+ //_listBox.Items = null; Makes no sense? Tooltip disappeared because of this
_listBox.Items = listBoxItems;
SelectIndexCentered(bestIndex);
}
| 1 | Fix tooltip disappearing | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057725 | <NME> CompletionList.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.Collections.ObjectModel;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml.Templates;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.CodeCompletion
{
/// <summary>
/// The listbox used inside the CompletionWindow, contains CompletionListBox.
/// </summary>
public class CompletionList : TemplatedControl
{
public CompletionList()
{
DoubleTapped += OnDoubleTapped;
}
/// <summary>
/// If true, the CompletionList is filtered to show only matching items. Also enables search by substring.
/// If false, enables the old behavior: no filtering, search by string.StartsWith.
/// </summary>
public bool IsFiltering { get; set; } = true;
/// <summary>
/// Dependency property for <see cref="EmptyTemplate" />.
/// </summary>
public static readonly StyledProperty<ControlTemplate> EmptyTemplateProperty =
AvaloniaProperty.Register<CompletionList, ControlTemplate>(nameof(EmptyTemplate));
/// <summary>
/// Content of EmptyTemplate will be shown when CompletionList contains no items.
/// If EmptyTemplate is null, nothing will be shown.
/// </summary>
public ControlTemplate EmptyTemplate
{
get => GetValue(EmptyTemplateProperty);
set => SetValue(EmptyTemplateProperty, value);
}
/// <summary>
/// Is raised when the completion list indicates that the user has chosen
/// an entry to be completed.
/// </summary>
public event EventHandler InsertionRequested;
/// <summary>
/// Raises the InsertionRequested event.
/// </summary>
public void RequestInsertion(EventArgs e)
{
InsertionRequested?.Invoke(this, e);
}
private CompletionListBox _listBox;
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
_listBox = e.NameScope.Find("PART_ListBox") as CompletionListBox;
if (_listBox != null)
{
_listBox.Items = _completionData;
}
}
/// <summary>
/// Gets the list box.
/// </summary>
public CompletionListBox ListBox
{
get
{
if (_listBox == null)
ApplyTemplate();
return _listBox;
}
}
/// <summary>
/// Gets the scroll viewer used in this list box.
/// </summary>
public ScrollViewer ScrollViewer => _listBox?.ScrollViewer;
private readonly ObservableCollection<ICompletionData> _completionData = new ObservableCollection<ICompletionData>();
/// <summary>
/// Gets the list to which completion data can be added.
/// </summary>
public IList<ICompletionData> CompletionData => _completionData;
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (!e.Handled)
{
HandleKey(e);
}
}
/// <summary>
/// Handles a key press. Used to let the completion list handle key presses while the
/// focus is still on the text editor.
/// </summary>
public void HandleKey(KeyEventArgs e)
{
if (_listBox == null)
return;
// We have to do some key handling manually, because the default doesn't work with
// our simulated events.
// Also, the default PageUp/PageDown implementation changes the focus, so we avoid it.
switch (e.Key)
{
case Key.Down:
e.Handled = true;
_listBox.SelectIndex(_listBox.SelectedIndex + 1);
break;
case Key.Up:
e.Handled = true;
_listBox.SelectIndex(_listBox.SelectedIndex - 1);
break;
case Key.PageDown:
e.Handled = true;
_listBox.SelectIndex(_listBox.SelectedIndex + _listBox.VisibleItemCount);
break;
case Key.PageUp:
e.Handled = true;
_listBox.SelectIndex(_listBox.SelectedIndex - _listBox.VisibleItemCount);
break;
case Key.Home:
e.Handled = true;
_listBox.SelectIndex(0);
break;
case Key.End:
e.Handled = true;
_listBox.SelectIndex(_listBox.ItemCount - 1);
break;
case Key.Tab:
case Key.Enter:
if(CurrentList.Count > 0)
{
e.Handled = true;
RequestInsertion(e);
}
break;
}
}
protected void OnDoubleTapped(object sender, RoutedEventArgs e)
{
//TODO TEST
if (((AvaloniaObject)e.Source).VisualAncestorsAndSelf()
.TakeWhile(obj => obj != this).Any(obj => obj is ListBoxItem))
{
e.Handled = true;
RequestInsertion(e);
}
}
/// <summary>
/// Gets/Sets the selected item.
/// </summary>
/// <remarks>
/// The setter of this property does not scroll to the selected item.
/// You might want to also call <see cref="ScrollIntoView"/>.
/// </remarks>
public ICompletionData SelectedItem
{
get => _listBox?.SelectedItem as ICompletionData;
set
{
if (_listBox == null && value != null)
ApplyTemplate();
if (_listBox != null) // may still be null if ApplyTemplate fails, or if listBox and value both are null
_listBox.SelectedItem = value;
}
}
/// <summary>
/// Scrolls the specified item into view.
/// </summary>
public void ScrollIntoView(ICompletionData item)
{
if (_listBox == null)
ApplyTemplate();
_listBox?.ScrollIntoView(item);
}
/// <summary>
/// Occurs when the SelectedItem property changes.
/// </summary>
public event EventHandler<SelectionChangedEventArgs> SelectionChanged
{
add => AddHandler(SelectingItemsControl.SelectionChangedEvent, value);
remove => RemoveHandler(SelectingItemsControl.SelectionChangedEvent, value);
}
// SelectItem gets called twice for every typed character (once from FormatLine), this helps execute SelectItem only once
private string _currentText;
private ObservableCollection<ICompletionData> _currentList;
public List<ICompletionData> CurrentList
{
get => ListBox.Items.Cast<ICompletionData>().ToList();
}
/// <summary>
/// Selects the best match, and filter the items if turned on using <see cref="IsFiltering" />.
/// </summary>
public void SelectItem(string text)
{
if (text == _currentText)
return;
if (_listBox == null)
ApplyTemplate();
if (IsFiltering)
{
SelectItemFiltering(text);
}
else
{
SelectItemWithStart(text);
}
_currentText = text;
}
/// <summary>
/// Filters CompletionList items to show only those matching given query, and selects the best match.
/// </summary>
private void SelectItemFiltering(string query)
{
// if the user just typed one more character, don't filter all data but just filter what we are already displaying
var listToFilter = _currentList != null && !string.IsNullOrEmpty(_currentText) && !string.IsNullOrEmpty(query) &&
query.StartsWith(_currentText, StringComparison.Ordinal) ?
_currentList : _completionData;
var matchingItems =
from item in listToFilter
let quality = GetMatchQuality(item.Text, query)
where quality > 0
select new { Item = item, Quality = quality };
// e.g. "DateTimeKind k = (*cc here suggests DateTimeKind*)"
var suggestedItem = _listBox.SelectedIndex != -1 ? (ICompletionData)_listBox.SelectedItem : null;
var listBoxItems = new ObservableCollection<ICompletionData>();
var bestIndex = -1;
var bestQuality = -1;
double bestPriority = 0;
var i = 0;
foreach (var matchingItem in matchingItems)
{
var priority = matchingItem.Item == suggestedItem ? double.PositiveInfinity : matchingItem.Item.Priority;
var quality = matchingItem.Quality;
}
_currentList = listBoxItems;
_listBox.Items = null;
_listBox.Items = listBoxItems;
SelectIndexCentered(bestIndex);
}
i++;
}
_currentList = listBoxItems;
//_listBox.Items = null; Makes no sense? Tooltip disappeared because of this
_listBox.Items = listBoxItems;
SelectIndexCentered(bestIndex);
}
/// <summary>
/// Selects the item that starts with the specified query.
/// </summary>
private void SelectItemWithStart(string query)
{
if (string.IsNullOrEmpty(query))
return;
var suggestedIndex = _listBox.SelectedIndex;
var bestIndex = -1;
var bestQuality = -1;
double bestPriority = 0;
for (var i = 0; i < _completionData.Count; ++i)
{
var quality = GetMatchQuality(_completionData[i].Text, query);
if (quality < 0)
continue;
var priority = _completionData[i].Priority;
bool useThisItem;
if (bestQuality < quality)
{
useThisItem = true;
}
else
{
if (bestIndex == suggestedIndex)
{
useThisItem = false;
}
else if (i == suggestedIndex)
{
// prefer recommendedItem, regardless of its priority
useThisItem = bestQuality == quality;
}
else
{
useThisItem = bestQuality == quality && bestPriority < priority;
}
}
if (useThisItem)
{
bestIndex = i;
bestPriority = priority;
bestQuality = quality;
}
}
SelectIndexCentered(bestIndex);
}
private void SelectIndexCentered(int bestIndex)
{
if (bestIndex < 0)
{
_listBox.ClearSelection();
}
else
{
var firstItem = _listBox.FirstVisibleItem;
if (bestIndex < firstItem || firstItem + _listBox.VisibleItemCount <= bestIndex)
{
// CenterViewOn does nothing as CompletionListBox.ScrollViewer is null
_listBox.CenterViewOn(bestIndex);
_listBox.SelectIndex(bestIndex);
}
else
{
_listBox.SelectIndex(bestIndex);
}
}
}
private int GetMatchQuality(string itemText, string query)
{
if (itemText == null)
throw new ArgumentNullException(nameof(itemText), "ICompletionData.Text returned null");
// Qualities:
// 8 = full match case sensitive
// 7 = full match
// 6 = match start case sensitive
// 5 = match start
// 4 = match CamelCase when length of query is 1 or 2 characters
// 3 = match substring case sensitive
// 2 = match substring
// 1 = match CamelCase
// -1 = no match
if (query == itemText)
return 8;
if (string.Equals(itemText, query, StringComparison.CurrentCultureIgnoreCase))
return 7;
if (itemText.StartsWith(query, StringComparison.CurrentCulture))
return 6;
if (itemText.StartsWith(query, StringComparison.CurrentCultureIgnoreCase))
return 5;
bool? camelCaseMatch = null;
if (query.Length <= 2)
{
camelCaseMatch = CamelCaseMatch(itemText, query);
if (camelCaseMatch == true) return 4;
}
// search by substring, if filtering (i.e. new behavior) turned on
if (IsFiltering)
{
if (itemText.IndexOf(query, StringComparison.CurrentCulture) >= 0)
return 3;
if (itemText.IndexOf(query, StringComparison.CurrentCultureIgnoreCase) >= 0)
return 2;
}
if (!camelCaseMatch.HasValue)
camelCaseMatch = CamelCaseMatch(itemText, query);
if (camelCaseMatch == true)
return 1;
return -1;
}
private static bool CamelCaseMatch(string text, string query)
{
// We take the first letter of the text regardless of whether or not it's upper case so we match
// against camelCase text as well as PascalCase text ("cct" matches "camelCaseText")
var theFirstLetterOfEachWord = text.AsEnumerable()
.Take(1)
.Concat(text.AsEnumerable().Skip(1).Where(char.IsUpper));
var i = 0;
foreach (var letter in theFirstLetterOfEachWord)
{
if (i > query.Length - 1)
return true; // return true here for CamelCase partial match ("CQ" matches "CodeQualityAnalysis")
if (char.ToUpperInvariant(query[i]) != char.ToUpperInvariant(letter))
return false;
i++;
}
if (i >= query.Length)
return true;
return false;
}
}
}
<MSG> Fix tooltip disappearing
<DFF> @@ -285,7 +285,7 @@ namespace AvaloniaEdit.CodeCompletion
}
_currentList = listBoxItems;
- _listBox.Items = null;
+ //_listBox.Items = null; Makes no sense? Tooltip disappeared because of this
_listBox.Items = listBoxItems;
SelectIndexCentered(bestIndex);
}
| 1 | Fix tooltip disappearing | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057726 | <NME> CompletionList.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.Collections.ObjectModel;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml.Templates;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.CodeCompletion
{
/// <summary>
/// The listbox used inside the CompletionWindow, contains CompletionListBox.
/// </summary>
public class CompletionList : TemplatedControl
{
public CompletionList()
{
DoubleTapped += OnDoubleTapped;
}
/// <summary>
/// If true, the CompletionList is filtered to show only matching items. Also enables search by substring.
/// If false, enables the old behavior: no filtering, search by string.StartsWith.
/// </summary>
public bool IsFiltering { get; set; } = true;
/// <summary>
/// Dependency property for <see cref="EmptyTemplate" />.
/// </summary>
public static readonly StyledProperty<ControlTemplate> EmptyTemplateProperty =
AvaloniaProperty.Register<CompletionList, ControlTemplate>(nameof(EmptyTemplate));
/// <summary>
/// Content of EmptyTemplate will be shown when CompletionList contains no items.
/// If EmptyTemplate is null, nothing will be shown.
/// </summary>
public ControlTemplate EmptyTemplate
{
get => GetValue(EmptyTemplateProperty);
set => SetValue(EmptyTemplateProperty, value);
}
/// <summary>
/// Is raised when the completion list indicates that the user has chosen
/// an entry to be completed.
/// </summary>
public event EventHandler InsertionRequested;
/// <summary>
/// Raises the InsertionRequested event.
/// </summary>
public void RequestInsertion(EventArgs e)
{
InsertionRequested?.Invoke(this, e);
}
private CompletionListBox _listBox;
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
_listBox = e.NameScope.Find("PART_ListBox") as CompletionListBox;
if (_listBox != null)
{
_listBox.Items = _completionData;
}
}
/// <summary>
/// Gets the list box.
/// </summary>
public CompletionListBox ListBox
{
get
{
if (_listBox == null)
ApplyTemplate();
return _listBox;
}
}
/// <summary>
/// Gets the scroll viewer used in this list box.
/// </summary>
public ScrollViewer ScrollViewer => _listBox?.ScrollViewer;
private readonly ObservableCollection<ICompletionData> _completionData = new ObservableCollection<ICompletionData>();
/// <summary>
/// Gets the list to which completion data can be added.
/// </summary>
public IList<ICompletionData> CompletionData => _completionData;
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (!e.Handled)
{
HandleKey(e);
}
}
/// <summary>
/// Handles a key press. Used to let the completion list handle key presses while the
/// focus is still on the text editor.
/// </summary>
public void HandleKey(KeyEventArgs e)
{
if (_listBox == null)
return;
// We have to do some key handling manually, because the default doesn't work with
// our simulated events.
// Also, the default PageUp/PageDown implementation changes the focus, so we avoid it.
switch (e.Key)
{
case Key.Down:
e.Handled = true;
_listBox.SelectIndex(_listBox.SelectedIndex + 1);
break;
case Key.Up:
e.Handled = true;
_listBox.SelectIndex(_listBox.SelectedIndex - 1);
break;
case Key.PageDown:
e.Handled = true;
_listBox.SelectIndex(_listBox.SelectedIndex + _listBox.VisibleItemCount);
break;
case Key.PageUp:
e.Handled = true;
_listBox.SelectIndex(_listBox.SelectedIndex - _listBox.VisibleItemCount);
break;
case Key.Home:
e.Handled = true;
_listBox.SelectIndex(0);
break;
case Key.End:
e.Handled = true;
_listBox.SelectIndex(_listBox.ItemCount - 1);
break;
case Key.Tab:
case Key.Enter:
if(CurrentList.Count > 0)
{
e.Handled = true;
RequestInsertion(e);
}
break;
}
}
protected void OnDoubleTapped(object sender, RoutedEventArgs e)
{
//TODO TEST
if (((AvaloniaObject)e.Source).VisualAncestorsAndSelf()
.TakeWhile(obj => obj != this).Any(obj => obj is ListBoxItem))
{
e.Handled = true;
RequestInsertion(e);
}
}
/// <summary>
/// Gets/Sets the selected item.
/// </summary>
/// <remarks>
/// The setter of this property does not scroll to the selected item.
/// You might want to also call <see cref="ScrollIntoView"/>.
/// </remarks>
public ICompletionData SelectedItem
{
get => _listBox?.SelectedItem as ICompletionData;
set
{
if (_listBox == null && value != null)
ApplyTemplate();
if (_listBox != null) // may still be null if ApplyTemplate fails, or if listBox and value both are null
_listBox.SelectedItem = value;
}
}
/// <summary>
/// Scrolls the specified item into view.
/// </summary>
public void ScrollIntoView(ICompletionData item)
{
if (_listBox == null)
ApplyTemplate();
_listBox?.ScrollIntoView(item);
}
/// <summary>
/// Occurs when the SelectedItem property changes.
/// </summary>
public event EventHandler<SelectionChangedEventArgs> SelectionChanged
{
add => AddHandler(SelectingItemsControl.SelectionChangedEvent, value);
remove => RemoveHandler(SelectingItemsControl.SelectionChangedEvent, value);
}
// SelectItem gets called twice for every typed character (once from FormatLine), this helps execute SelectItem only once
private string _currentText;
private ObservableCollection<ICompletionData> _currentList;
public List<ICompletionData> CurrentList
{
get => ListBox.Items.Cast<ICompletionData>().ToList();
}
/// <summary>
/// Selects the best match, and filter the items if turned on using <see cref="IsFiltering" />.
/// </summary>
public void SelectItem(string text)
{
if (text == _currentText)
return;
if (_listBox == null)
ApplyTemplate();
if (IsFiltering)
{
SelectItemFiltering(text);
}
else
{
SelectItemWithStart(text);
}
_currentText = text;
}
/// <summary>
/// Filters CompletionList items to show only those matching given query, and selects the best match.
/// </summary>
private void SelectItemFiltering(string query)
{
// if the user just typed one more character, don't filter all data but just filter what we are already displaying
var listToFilter = _currentList != null && !string.IsNullOrEmpty(_currentText) && !string.IsNullOrEmpty(query) &&
query.StartsWith(_currentText, StringComparison.Ordinal) ?
_currentList : _completionData;
var matchingItems =
from item in listToFilter
let quality = GetMatchQuality(item.Text, query)
where quality > 0
select new { Item = item, Quality = quality };
// e.g. "DateTimeKind k = (*cc here suggests DateTimeKind*)"
var suggestedItem = _listBox.SelectedIndex != -1 ? (ICompletionData)_listBox.SelectedItem : null;
var listBoxItems = new ObservableCollection<ICompletionData>();
var bestIndex = -1;
var bestQuality = -1;
double bestPriority = 0;
var i = 0;
foreach (var matchingItem in matchingItems)
{
var priority = matchingItem.Item == suggestedItem ? double.PositiveInfinity : matchingItem.Item.Priority;
var quality = matchingItem.Quality;
}
_currentList = listBoxItems;
_listBox.Items = null;
_listBox.Items = listBoxItems;
SelectIndexCentered(bestIndex);
}
i++;
}
_currentList = listBoxItems;
//_listBox.Items = null; Makes no sense? Tooltip disappeared because of this
_listBox.Items = listBoxItems;
SelectIndexCentered(bestIndex);
}
/// <summary>
/// Selects the item that starts with the specified query.
/// </summary>
private void SelectItemWithStart(string query)
{
if (string.IsNullOrEmpty(query))
return;
var suggestedIndex = _listBox.SelectedIndex;
var bestIndex = -1;
var bestQuality = -1;
double bestPriority = 0;
for (var i = 0; i < _completionData.Count; ++i)
{
var quality = GetMatchQuality(_completionData[i].Text, query);
if (quality < 0)
continue;
var priority = _completionData[i].Priority;
bool useThisItem;
if (bestQuality < quality)
{
useThisItem = true;
}
else
{
if (bestIndex == suggestedIndex)
{
useThisItem = false;
}
else if (i == suggestedIndex)
{
// prefer recommendedItem, regardless of its priority
useThisItem = bestQuality == quality;
}
else
{
useThisItem = bestQuality == quality && bestPriority < priority;
}
}
if (useThisItem)
{
bestIndex = i;
bestPriority = priority;
bestQuality = quality;
}
}
SelectIndexCentered(bestIndex);
}
private void SelectIndexCentered(int bestIndex)
{
if (bestIndex < 0)
{
_listBox.ClearSelection();
}
else
{
var firstItem = _listBox.FirstVisibleItem;
if (bestIndex < firstItem || firstItem + _listBox.VisibleItemCount <= bestIndex)
{
// CenterViewOn does nothing as CompletionListBox.ScrollViewer is null
_listBox.CenterViewOn(bestIndex);
_listBox.SelectIndex(bestIndex);
}
else
{
_listBox.SelectIndex(bestIndex);
}
}
}
private int GetMatchQuality(string itemText, string query)
{
if (itemText == null)
throw new ArgumentNullException(nameof(itemText), "ICompletionData.Text returned null");
// Qualities:
// 8 = full match case sensitive
// 7 = full match
// 6 = match start case sensitive
// 5 = match start
// 4 = match CamelCase when length of query is 1 or 2 characters
// 3 = match substring case sensitive
// 2 = match substring
// 1 = match CamelCase
// -1 = no match
if (query == itemText)
return 8;
if (string.Equals(itemText, query, StringComparison.CurrentCultureIgnoreCase))
return 7;
if (itemText.StartsWith(query, StringComparison.CurrentCulture))
return 6;
if (itemText.StartsWith(query, StringComparison.CurrentCultureIgnoreCase))
return 5;
bool? camelCaseMatch = null;
if (query.Length <= 2)
{
camelCaseMatch = CamelCaseMatch(itemText, query);
if (camelCaseMatch == true) return 4;
}
// search by substring, if filtering (i.e. new behavior) turned on
if (IsFiltering)
{
if (itemText.IndexOf(query, StringComparison.CurrentCulture) >= 0)
return 3;
if (itemText.IndexOf(query, StringComparison.CurrentCultureIgnoreCase) >= 0)
return 2;
}
if (!camelCaseMatch.HasValue)
camelCaseMatch = CamelCaseMatch(itemText, query);
if (camelCaseMatch == true)
return 1;
return -1;
}
private static bool CamelCaseMatch(string text, string query)
{
// We take the first letter of the text regardless of whether or not it's upper case so we match
// against camelCase text as well as PascalCase text ("cct" matches "camelCaseText")
var theFirstLetterOfEachWord = text.AsEnumerable()
.Take(1)
.Concat(text.AsEnumerable().Skip(1).Where(char.IsUpper));
var i = 0;
foreach (var letter in theFirstLetterOfEachWord)
{
if (i > query.Length - 1)
return true; // return true here for CamelCase partial match ("CQ" matches "CodeQualityAnalysis")
if (char.ToUpperInvariant(query[i]) != char.ToUpperInvariant(letter))
return false;
i++;
}
if (i >= query.Length)
return true;
return false;
}
}
}
<MSG> Fix tooltip disappearing
<DFF> @@ -285,7 +285,7 @@ namespace AvaloniaEdit.CodeCompletion
}
_currentList = listBoxItems;
- _listBox.Items = null;
+ //_listBox.Items = null; Makes no sense? Tooltip disappeared because of this
_listBox.Items = listBoxItems;
SelectIndexCentered(bestIndex);
}
| 1 | Fix tooltip disappearing | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057727 | <NME> CompletionList.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.Collections.ObjectModel;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml.Templates;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.CodeCompletion
{
/// <summary>
/// The listbox used inside the CompletionWindow, contains CompletionListBox.
/// </summary>
public class CompletionList : TemplatedControl
{
public CompletionList()
{
DoubleTapped += OnDoubleTapped;
}
/// <summary>
/// If true, the CompletionList is filtered to show only matching items. Also enables search by substring.
/// If false, enables the old behavior: no filtering, search by string.StartsWith.
/// </summary>
public bool IsFiltering { get; set; } = true;
/// <summary>
/// Dependency property for <see cref="EmptyTemplate" />.
/// </summary>
public static readonly StyledProperty<ControlTemplate> EmptyTemplateProperty =
AvaloniaProperty.Register<CompletionList, ControlTemplate>(nameof(EmptyTemplate));
/// <summary>
/// Content of EmptyTemplate will be shown when CompletionList contains no items.
/// If EmptyTemplate is null, nothing will be shown.
/// </summary>
public ControlTemplate EmptyTemplate
{
get => GetValue(EmptyTemplateProperty);
set => SetValue(EmptyTemplateProperty, value);
}
/// <summary>
/// Is raised when the completion list indicates that the user has chosen
/// an entry to be completed.
/// </summary>
public event EventHandler InsertionRequested;
/// <summary>
/// Raises the InsertionRequested event.
/// </summary>
public void RequestInsertion(EventArgs e)
{
InsertionRequested?.Invoke(this, e);
}
private CompletionListBox _listBox;
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
_listBox = e.NameScope.Find("PART_ListBox") as CompletionListBox;
if (_listBox != null)
{
_listBox.Items = _completionData;
}
}
/// <summary>
/// Gets the list box.
/// </summary>
public CompletionListBox ListBox
{
get
{
if (_listBox == null)
ApplyTemplate();
return _listBox;
}
}
/// <summary>
/// Gets the scroll viewer used in this list box.
/// </summary>
public ScrollViewer ScrollViewer => _listBox?.ScrollViewer;
private readonly ObservableCollection<ICompletionData> _completionData = new ObservableCollection<ICompletionData>();
/// <summary>
/// Gets the list to which completion data can be added.
/// </summary>
public IList<ICompletionData> CompletionData => _completionData;
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (!e.Handled)
{
HandleKey(e);
}
}
/// <summary>
/// Handles a key press. Used to let the completion list handle key presses while the
/// focus is still on the text editor.
/// </summary>
public void HandleKey(KeyEventArgs e)
{
if (_listBox == null)
return;
// We have to do some key handling manually, because the default doesn't work with
// our simulated events.
// Also, the default PageUp/PageDown implementation changes the focus, so we avoid it.
switch (e.Key)
{
case Key.Down:
e.Handled = true;
_listBox.SelectIndex(_listBox.SelectedIndex + 1);
break;
case Key.Up:
e.Handled = true;
_listBox.SelectIndex(_listBox.SelectedIndex - 1);
break;
case Key.PageDown:
e.Handled = true;
_listBox.SelectIndex(_listBox.SelectedIndex + _listBox.VisibleItemCount);
break;
case Key.PageUp:
e.Handled = true;
_listBox.SelectIndex(_listBox.SelectedIndex - _listBox.VisibleItemCount);
break;
case Key.Home:
e.Handled = true;
_listBox.SelectIndex(0);
break;
case Key.End:
e.Handled = true;
_listBox.SelectIndex(_listBox.ItemCount - 1);
break;
case Key.Tab:
case Key.Enter:
if(CurrentList.Count > 0)
{
e.Handled = true;
RequestInsertion(e);
}
break;
}
}
protected void OnDoubleTapped(object sender, RoutedEventArgs e)
{
//TODO TEST
if (((AvaloniaObject)e.Source).VisualAncestorsAndSelf()
.TakeWhile(obj => obj != this).Any(obj => obj is ListBoxItem))
{
e.Handled = true;
RequestInsertion(e);
}
}
/// <summary>
/// Gets/Sets the selected item.
/// </summary>
/// <remarks>
/// The setter of this property does not scroll to the selected item.
/// You might want to also call <see cref="ScrollIntoView"/>.
/// </remarks>
public ICompletionData SelectedItem
{
get => _listBox?.SelectedItem as ICompletionData;
set
{
if (_listBox == null && value != null)
ApplyTemplate();
if (_listBox != null) // may still be null if ApplyTemplate fails, or if listBox and value both are null
_listBox.SelectedItem = value;
}
}
/// <summary>
/// Scrolls the specified item into view.
/// </summary>
public void ScrollIntoView(ICompletionData item)
{
if (_listBox == null)
ApplyTemplate();
_listBox?.ScrollIntoView(item);
}
/// <summary>
/// Occurs when the SelectedItem property changes.
/// </summary>
public event EventHandler<SelectionChangedEventArgs> SelectionChanged
{
add => AddHandler(SelectingItemsControl.SelectionChangedEvent, value);
remove => RemoveHandler(SelectingItemsControl.SelectionChangedEvent, value);
}
// SelectItem gets called twice for every typed character (once from FormatLine), this helps execute SelectItem only once
private string _currentText;
private ObservableCollection<ICompletionData> _currentList;
public List<ICompletionData> CurrentList
{
get => ListBox.Items.Cast<ICompletionData>().ToList();
}
/// <summary>
/// Selects the best match, and filter the items if turned on using <see cref="IsFiltering" />.
/// </summary>
public void SelectItem(string text)
{
if (text == _currentText)
return;
if (_listBox == null)
ApplyTemplate();
if (IsFiltering)
{
SelectItemFiltering(text);
}
else
{
SelectItemWithStart(text);
}
_currentText = text;
}
/// <summary>
/// Filters CompletionList items to show only those matching given query, and selects the best match.
/// </summary>
private void SelectItemFiltering(string query)
{
// if the user just typed one more character, don't filter all data but just filter what we are already displaying
var listToFilter = _currentList != null && !string.IsNullOrEmpty(_currentText) && !string.IsNullOrEmpty(query) &&
query.StartsWith(_currentText, StringComparison.Ordinal) ?
_currentList : _completionData;
var matchingItems =
from item in listToFilter
let quality = GetMatchQuality(item.Text, query)
where quality > 0
select new { Item = item, Quality = quality };
// e.g. "DateTimeKind k = (*cc here suggests DateTimeKind*)"
var suggestedItem = _listBox.SelectedIndex != -1 ? (ICompletionData)_listBox.SelectedItem : null;
var listBoxItems = new ObservableCollection<ICompletionData>();
var bestIndex = -1;
var bestQuality = -1;
double bestPriority = 0;
var i = 0;
foreach (var matchingItem in matchingItems)
{
var priority = matchingItem.Item == suggestedItem ? double.PositiveInfinity : matchingItem.Item.Priority;
var quality = matchingItem.Quality;
}
_currentList = listBoxItems;
_listBox.Items = null;
_listBox.Items = listBoxItems;
SelectIndexCentered(bestIndex);
}
i++;
}
_currentList = listBoxItems;
//_listBox.Items = null; Makes no sense? Tooltip disappeared because of this
_listBox.Items = listBoxItems;
SelectIndexCentered(bestIndex);
}
/// <summary>
/// Selects the item that starts with the specified query.
/// </summary>
private void SelectItemWithStart(string query)
{
if (string.IsNullOrEmpty(query))
return;
var suggestedIndex = _listBox.SelectedIndex;
var bestIndex = -1;
var bestQuality = -1;
double bestPriority = 0;
for (var i = 0; i < _completionData.Count; ++i)
{
var quality = GetMatchQuality(_completionData[i].Text, query);
if (quality < 0)
continue;
var priority = _completionData[i].Priority;
bool useThisItem;
if (bestQuality < quality)
{
useThisItem = true;
}
else
{
if (bestIndex == suggestedIndex)
{
useThisItem = false;
}
else if (i == suggestedIndex)
{
// prefer recommendedItem, regardless of its priority
useThisItem = bestQuality == quality;
}
else
{
useThisItem = bestQuality == quality && bestPriority < priority;
}
}
if (useThisItem)
{
bestIndex = i;
bestPriority = priority;
bestQuality = quality;
}
}
SelectIndexCentered(bestIndex);
}
private void SelectIndexCentered(int bestIndex)
{
if (bestIndex < 0)
{
_listBox.ClearSelection();
}
else
{
var firstItem = _listBox.FirstVisibleItem;
if (bestIndex < firstItem || firstItem + _listBox.VisibleItemCount <= bestIndex)
{
// CenterViewOn does nothing as CompletionListBox.ScrollViewer is null
_listBox.CenterViewOn(bestIndex);
_listBox.SelectIndex(bestIndex);
}
else
{
_listBox.SelectIndex(bestIndex);
}
}
}
private int GetMatchQuality(string itemText, string query)
{
if (itemText == null)
throw new ArgumentNullException(nameof(itemText), "ICompletionData.Text returned null");
// Qualities:
// 8 = full match case sensitive
// 7 = full match
// 6 = match start case sensitive
// 5 = match start
// 4 = match CamelCase when length of query is 1 or 2 characters
// 3 = match substring case sensitive
// 2 = match substring
// 1 = match CamelCase
// -1 = no match
if (query == itemText)
return 8;
if (string.Equals(itemText, query, StringComparison.CurrentCultureIgnoreCase))
return 7;
if (itemText.StartsWith(query, StringComparison.CurrentCulture))
return 6;
if (itemText.StartsWith(query, StringComparison.CurrentCultureIgnoreCase))
return 5;
bool? camelCaseMatch = null;
if (query.Length <= 2)
{
camelCaseMatch = CamelCaseMatch(itemText, query);
if (camelCaseMatch == true) return 4;
}
// search by substring, if filtering (i.e. new behavior) turned on
if (IsFiltering)
{
if (itemText.IndexOf(query, StringComparison.CurrentCulture) >= 0)
return 3;
if (itemText.IndexOf(query, StringComparison.CurrentCultureIgnoreCase) >= 0)
return 2;
}
if (!camelCaseMatch.HasValue)
camelCaseMatch = CamelCaseMatch(itemText, query);
if (camelCaseMatch == true)
return 1;
return -1;
}
private static bool CamelCaseMatch(string text, string query)
{
// We take the first letter of the text regardless of whether or not it's upper case so we match
// against camelCase text as well as PascalCase text ("cct" matches "camelCaseText")
var theFirstLetterOfEachWord = text.AsEnumerable()
.Take(1)
.Concat(text.AsEnumerable().Skip(1).Where(char.IsUpper));
var i = 0;
foreach (var letter in theFirstLetterOfEachWord)
{
if (i > query.Length - 1)
return true; // return true here for CamelCase partial match ("CQ" matches "CodeQualityAnalysis")
if (char.ToUpperInvariant(query[i]) != char.ToUpperInvariant(letter))
return false;
i++;
}
if (i >= query.Length)
return true;
return false;
}
}
}
<MSG> Fix tooltip disappearing
<DFF> @@ -285,7 +285,7 @@ namespace AvaloniaEdit.CodeCompletion
}
_currentList = listBoxItems;
- _listBox.Items = null;
+ //_listBox.Items = null; Makes no sense? Tooltip disappeared because of this
_listBox.Items = listBoxItems;
SelectIndexCentered(bestIndex);
}
| 1 | Fix tooltip disappearing | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057728 | <NME> CompletionList.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.Collections.ObjectModel;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml.Templates;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.CodeCompletion
{
/// <summary>
/// The listbox used inside the CompletionWindow, contains CompletionListBox.
/// </summary>
public class CompletionList : TemplatedControl
{
public CompletionList()
{
DoubleTapped += OnDoubleTapped;
}
/// <summary>
/// If true, the CompletionList is filtered to show only matching items. Also enables search by substring.
/// If false, enables the old behavior: no filtering, search by string.StartsWith.
/// </summary>
public bool IsFiltering { get; set; } = true;
/// <summary>
/// Dependency property for <see cref="EmptyTemplate" />.
/// </summary>
public static readonly StyledProperty<ControlTemplate> EmptyTemplateProperty =
AvaloniaProperty.Register<CompletionList, ControlTemplate>(nameof(EmptyTemplate));
/// <summary>
/// Content of EmptyTemplate will be shown when CompletionList contains no items.
/// If EmptyTemplate is null, nothing will be shown.
/// </summary>
public ControlTemplate EmptyTemplate
{
get => GetValue(EmptyTemplateProperty);
set => SetValue(EmptyTemplateProperty, value);
}
/// <summary>
/// Is raised when the completion list indicates that the user has chosen
/// an entry to be completed.
/// </summary>
public event EventHandler InsertionRequested;
/// <summary>
/// Raises the InsertionRequested event.
/// </summary>
public void RequestInsertion(EventArgs e)
{
InsertionRequested?.Invoke(this, e);
}
private CompletionListBox _listBox;
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
_listBox = e.NameScope.Find("PART_ListBox") as CompletionListBox;
if (_listBox != null)
{
_listBox.Items = _completionData;
}
}
/// <summary>
/// Gets the list box.
/// </summary>
public CompletionListBox ListBox
{
get
{
if (_listBox == null)
ApplyTemplate();
return _listBox;
}
}
/// <summary>
/// Gets the scroll viewer used in this list box.
/// </summary>
public ScrollViewer ScrollViewer => _listBox?.ScrollViewer;
private readonly ObservableCollection<ICompletionData> _completionData = new ObservableCollection<ICompletionData>();
/// <summary>
/// Gets the list to which completion data can be added.
/// </summary>
public IList<ICompletionData> CompletionData => _completionData;
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (!e.Handled)
{
HandleKey(e);
}
}
/// <summary>
/// Handles a key press. Used to let the completion list handle key presses while the
/// focus is still on the text editor.
/// </summary>
public void HandleKey(KeyEventArgs e)
{
if (_listBox == null)
return;
// We have to do some key handling manually, because the default doesn't work with
// our simulated events.
// Also, the default PageUp/PageDown implementation changes the focus, so we avoid it.
switch (e.Key)
{
case Key.Down:
e.Handled = true;
_listBox.SelectIndex(_listBox.SelectedIndex + 1);
break;
case Key.Up:
e.Handled = true;
_listBox.SelectIndex(_listBox.SelectedIndex - 1);
break;
case Key.PageDown:
e.Handled = true;
_listBox.SelectIndex(_listBox.SelectedIndex + _listBox.VisibleItemCount);
break;
case Key.PageUp:
e.Handled = true;
_listBox.SelectIndex(_listBox.SelectedIndex - _listBox.VisibleItemCount);
break;
case Key.Home:
e.Handled = true;
_listBox.SelectIndex(0);
break;
case Key.End:
e.Handled = true;
_listBox.SelectIndex(_listBox.ItemCount - 1);
break;
case Key.Tab:
case Key.Enter:
if(CurrentList.Count > 0)
{
e.Handled = true;
RequestInsertion(e);
}
break;
}
}
protected void OnDoubleTapped(object sender, RoutedEventArgs e)
{
//TODO TEST
if (((AvaloniaObject)e.Source).VisualAncestorsAndSelf()
.TakeWhile(obj => obj != this).Any(obj => obj is ListBoxItem))
{
e.Handled = true;
RequestInsertion(e);
}
}
/// <summary>
/// Gets/Sets the selected item.
/// </summary>
/// <remarks>
/// The setter of this property does not scroll to the selected item.
/// You might want to also call <see cref="ScrollIntoView"/>.
/// </remarks>
public ICompletionData SelectedItem
{
get => _listBox?.SelectedItem as ICompletionData;
set
{
if (_listBox == null && value != null)
ApplyTemplate();
if (_listBox != null) // may still be null if ApplyTemplate fails, or if listBox and value both are null
_listBox.SelectedItem = value;
}
}
/// <summary>
/// Scrolls the specified item into view.
/// </summary>
public void ScrollIntoView(ICompletionData item)
{
if (_listBox == null)
ApplyTemplate();
_listBox?.ScrollIntoView(item);
}
/// <summary>
/// Occurs when the SelectedItem property changes.
/// </summary>
public event EventHandler<SelectionChangedEventArgs> SelectionChanged
{
add => AddHandler(SelectingItemsControl.SelectionChangedEvent, value);
remove => RemoveHandler(SelectingItemsControl.SelectionChangedEvent, value);
}
// SelectItem gets called twice for every typed character (once from FormatLine), this helps execute SelectItem only once
private string _currentText;
private ObservableCollection<ICompletionData> _currentList;
public List<ICompletionData> CurrentList
{
get => ListBox.Items.Cast<ICompletionData>().ToList();
}
/// <summary>
/// Selects the best match, and filter the items if turned on using <see cref="IsFiltering" />.
/// </summary>
public void SelectItem(string text)
{
if (text == _currentText)
return;
if (_listBox == null)
ApplyTemplate();
if (IsFiltering)
{
SelectItemFiltering(text);
}
else
{
SelectItemWithStart(text);
}
_currentText = text;
}
/// <summary>
/// Filters CompletionList items to show only those matching given query, and selects the best match.
/// </summary>
private void SelectItemFiltering(string query)
{
// if the user just typed one more character, don't filter all data but just filter what we are already displaying
var listToFilter = _currentList != null && !string.IsNullOrEmpty(_currentText) && !string.IsNullOrEmpty(query) &&
query.StartsWith(_currentText, StringComparison.Ordinal) ?
_currentList : _completionData;
var matchingItems =
from item in listToFilter
let quality = GetMatchQuality(item.Text, query)
where quality > 0
select new { Item = item, Quality = quality };
// e.g. "DateTimeKind k = (*cc here suggests DateTimeKind*)"
var suggestedItem = _listBox.SelectedIndex != -1 ? (ICompletionData)_listBox.SelectedItem : null;
var listBoxItems = new ObservableCollection<ICompletionData>();
var bestIndex = -1;
var bestQuality = -1;
double bestPriority = 0;
var i = 0;
foreach (var matchingItem in matchingItems)
{
var priority = matchingItem.Item == suggestedItem ? double.PositiveInfinity : matchingItem.Item.Priority;
var quality = matchingItem.Quality;
}
_currentList = listBoxItems;
_listBox.Items = null;
_listBox.Items = listBoxItems;
SelectIndexCentered(bestIndex);
}
i++;
}
_currentList = listBoxItems;
//_listBox.Items = null; Makes no sense? Tooltip disappeared because of this
_listBox.Items = listBoxItems;
SelectIndexCentered(bestIndex);
}
/// <summary>
/// Selects the item that starts with the specified query.
/// </summary>
private void SelectItemWithStart(string query)
{
if (string.IsNullOrEmpty(query))
return;
var suggestedIndex = _listBox.SelectedIndex;
var bestIndex = -1;
var bestQuality = -1;
double bestPriority = 0;
for (var i = 0; i < _completionData.Count; ++i)
{
var quality = GetMatchQuality(_completionData[i].Text, query);
if (quality < 0)
continue;
var priority = _completionData[i].Priority;
bool useThisItem;
if (bestQuality < quality)
{
useThisItem = true;
}
else
{
if (bestIndex == suggestedIndex)
{
useThisItem = false;
}
else if (i == suggestedIndex)
{
// prefer recommendedItem, regardless of its priority
useThisItem = bestQuality == quality;
}
else
{
useThisItem = bestQuality == quality && bestPriority < priority;
}
}
if (useThisItem)
{
bestIndex = i;
bestPriority = priority;
bestQuality = quality;
}
}
SelectIndexCentered(bestIndex);
}
private void SelectIndexCentered(int bestIndex)
{
if (bestIndex < 0)
{
_listBox.ClearSelection();
}
else
{
var firstItem = _listBox.FirstVisibleItem;
if (bestIndex < firstItem || firstItem + _listBox.VisibleItemCount <= bestIndex)
{
// CenterViewOn does nothing as CompletionListBox.ScrollViewer is null
_listBox.CenterViewOn(bestIndex);
_listBox.SelectIndex(bestIndex);
}
else
{
_listBox.SelectIndex(bestIndex);
}
}
}
private int GetMatchQuality(string itemText, string query)
{
if (itemText == null)
throw new ArgumentNullException(nameof(itemText), "ICompletionData.Text returned null");
// Qualities:
// 8 = full match case sensitive
// 7 = full match
// 6 = match start case sensitive
// 5 = match start
// 4 = match CamelCase when length of query is 1 or 2 characters
// 3 = match substring case sensitive
// 2 = match substring
// 1 = match CamelCase
// -1 = no match
if (query == itemText)
return 8;
if (string.Equals(itemText, query, StringComparison.CurrentCultureIgnoreCase))
return 7;
if (itemText.StartsWith(query, StringComparison.CurrentCulture))
return 6;
if (itemText.StartsWith(query, StringComparison.CurrentCultureIgnoreCase))
return 5;
bool? camelCaseMatch = null;
if (query.Length <= 2)
{
camelCaseMatch = CamelCaseMatch(itemText, query);
if (camelCaseMatch == true) return 4;
}
// search by substring, if filtering (i.e. new behavior) turned on
if (IsFiltering)
{
if (itemText.IndexOf(query, StringComparison.CurrentCulture) >= 0)
return 3;
if (itemText.IndexOf(query, StringComparison.CurrentCultureIgnoreCase) >= 0)
return 2;
}
if (!camelCaseMatch.HasValue)
camelCaseMatch = CamelCaseMatch(itemText, query);
if (camelCaseMatch == true)
return 1;
return -1;
}
private static bool CamelCaseMatch(string text, string query)
{
// We take the first letter of the text regardless of whether or not it's upper case so we match
// against camelCase text as well as PascalCase text ("cct" matches "camelCaseText")
var theFirstLetterOfEachWord = text.AsEnumerable()
.Take(1)
.Concat(text.AsEnumerable().Skip(1).Where(char.IsUpper));
var i = 0;
foreach (var letter in theFirstLetterOfEachWord)
{
if (i > query.Length - 1)
return true; // return true here for CamelCase partial match ("CQ" matches "CodeQualityAnalysis")
if (char.ToUpperInvariant(query[i]) != char.ToUpperInvariant(letter))
return false;
i++;
}
if (i >= query.Length)
return true;
return false;
}
}
}
<MSG> Fix tooltip disappearing
<DFF> @@ -285,7 +285,7 @@ namespace AvaloniaEdit.CodeCompletion
}
_currentList = listBoxItems;
- _listBox.Items = null;
+ //_listBox.Items = null; Makes no sense? Tooltip disappeared because of this
_listBox.Items = listBoxItems;
SelectIndexCentered(bestIndex);
}
| 1 | Fix tooltip disappearing | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057729 | <NME> CompletionList.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.Collections.ObjectModel;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml.Templates;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.CodeCompletion
{
/// <summary>
/// The listbox used inside the CompletionWindow, contains CompletionListBox.
/// </summary>
public class CompletionList : TemplatedControl
{
public CompletionList()
{
DoubleTapped += OnDoubleTapped;
}
/// <summary>
/// If true, the CompletionList is filtered to show only matching items. Also enables search by substring.
/// If false, enables the old behavior: no filtering, search by string.StartsWith.
/// </summary>
public bool IsFiltering { get; set; } = true;
/// <summary>
/// Dependency property for <see cref="EmptyTemplate" />.
/// </summary>
public static readonly StyledProperty<ControlTemplate> EmptyTemplateProperty =
AvaloniaProperty.Register<CompletionList, ControlTemplate>(nameof(EmptyTemplate));
/// <summary>
/// Content of EmptyTemplate will be shown when CompletionList contains no items.
/// If EmptyTemplate is null, nothing will be shown.
/// </summary>
public ControlTemplate EmptyTemplate
{
get => GetValue(EmptyTemplateProperty);
set => SetValue(EmptyTemplateProperty, value);
}
/// <summary>
/// Is raised when the completion list indicates that the user has chosen
/// an entry to be completed.
/// </summary>
public event EventHandler InsertionRequested;
/// <summary>
/// Raises the InsertionRequested event.
/// </summary>
public void RequestInsertion(EventArgs e)
{
InsertionRequested?.Invoke(this, e);
}
private CompletionListBox _listBox;
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
_listBox = e.NameScope.Find("PART_ListBox") as CompletionListBox;
if (_listBox != null)
{
_listBox.Items = _completionData;
}
}
/// <summary>
/// Gets the list box.
/// </summary>
public CompletionListBox ListBox
{
get
{
if (_listBox == null)
ApplyTemplate();
return _listBox;
}
}
/// <summary>
/// Gets the scroll viewer used in this list box.
/// </summary>
public ScrollViewer ScrollViewer => _listBox?.ScrollViewer;
private readonly ObservableCollection<ICompletionData> _completionData = new ObservableCollection<ICompletionData>();
/// <summary>
/// Gets the list to which completion data can be added.
/// </summary>
public IList<ICompletionData> CompletionData => _completionData;
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (!e.Handled)
{
HandleKey(e);
}
}
/// <summary>
/// Handles a key press. Used to let the completion list handle key presses while the
/// focus is still on the text editor.
/// </summary>
public void HandleKey(KeyEventArgs e)
{
if (_listBox == null)
return;
// We have to do some key handling manually, because the default doesn't work with
// our simulated events.
// Also, the default PageUp/PageDown implementation changes the focus, so we avoid it.
switch (e.Key)
{
case Key.Down:
e.Handled = true;
_listBox.SelectIndex(_listBox.SelectedIndex + 1);
break;
case Key.Up:
e.Handled = true;
_listBox.SelectIndex(_listBox.SelectedIndex - 1);
break;
case Key.PageDown:
e.Handled = true;
_listBox.SelectIndex(_listBox.SelectedIndex + _listBox.VisibleItemCount);
break;
case Key.PageUp:
e.Handled = true;
_listBox.SelectIndex(_listBox.SelectedIndex - _listBox.VisibleItemCount);
break;
case Key.Home:
e.Handled = true;
_listBox.SelectIndex(0);
break;
case Key.End:
e.Handled = true;
_listBox.SelectIndex(_listBox.ItemCount - 1);
break;
case Key.Tab:
case Key.Enter:
if(CurrentList.Count > 0)
{
e.Handled = true;
RequestInsertion(e);
}
break;
}
}
protected void OnDoubleTapped(object sender, RoutedEventArgs e)
{
//TODO TEST
if (((AvaloniaObject)e.Source).VisualAncestorsAndSelf()
.TakeWhile(obj => obj != this).Any(obj => obj is ListBoxItem))
{
e.Handled = true;
RequestInsertion(e);
}
}
/// <summary>
/// Gets/Sets the selected item.
/// </summary>
/// <remarks>
/// The setter of this property does not scroll to the selected item.
/// You might want to also call <see cref="ScrollIntoView"/>.
/// </remarks>
public ICompletionData SelectedItem
{
get => _listBox?.SelectedItem as ICompletionData;
set
{
if (_listBox == null && value != null)
ApplyTemplate();
if (_listBox != null) // may still be null if ApplyTemplate fails, or if listBox and value both are null
_listBox.SelectedItem = value;
}
}
/// <summary>
/// Scrolls the specified item into view.
/// </summary>
public void ScrollIntoView(ICompletionData item)
{
if (_listBox == null)
ApplyTemplate();
_listBox?.ScrollIntoView(item);
}
/// <summary>
/// Occurs when the SelectedItem property changes.
/// </summary>
public event EventHandler<SelectionChangedEventArgs> SelectionChanged
{
add => AddHandler(SelectingItemsControl.SelectionChangedEvent, value);
remove => RemoveHandler(SelectingItemsControl.SelectionChangedEvent, value);
}
// SelectItem gets called twice for every typed character (once from FormatLine), this helps execute SelectItem only once
private string _currentText;
private ObservableCollection<ICompletionData> _currentList;
public List<ICompletionData> CurrentList
{
get => ListBox.Items.Cast<ICompletionData>().ToList();
}
/// <summary>
/// Selects the best match, and filter the items if turned on using <see cref="IsFiltering" />.
/// </summary>
public void SelectItem(string text)
{
if (text == _currentText)
return;
if (_listBox == null)
ApplyTemplate();
if (IsFiltering)
{
SelectItemFiltering(text);
}
else
{
SelectItemWithStart(text);
}
_currentText = text;
}
/// <summary>
/// Filters CompletionList items to show only those matching given query, and selects the best match.
/// </summary>
private void SelectItemFiltering(string query)
{
// if the user just typed one more character, don't filter all data but just filter what we are already displaying
var listToFilter = _currentList != null && !string.IsNullOrEmpty(_currentText) && !string.IsNullOrEmpty(query) &&
query.StartsWith(_currentText, StringComparison.Ordinal) ?
_currentList : _completionData;
var matchingItems =
from item in listToFilter
let quality = GetMatchQuality(item.Text, query)
where quality > 0
select new { Item = item, Quality = quality };
// e.g. "DateTimeKind k = (*cc here suggests DateTimeKind*)"
var suggestedItem = _listBox.SelectedIndex != -1 ? (ICompletionData)_listBox.SelectedItem : null;
var listBoxItems = new ObservableCollection<ICompletionData>();
var bestIndex = -1;
var bestQuality = -1;
double bestPriority = 0;
var i = 0;
foreach (var matchingItem in matchingItems)
{
var priority = matchingItem.Item == suggestedItem ? double.PositiveInfinity : matchingItem.Item.Priority;
var quality = matchingItem.Quality;
}
_currentList = listBoxItems;
_listBox.Items = null;
_listBox.Items = listBoxItems;
SelectIndexCentered(bestIndex);
}
i++;
}
_currentList = listBoxItems;
//_listBox.Items = null; Makes no sense? Tooltip disappeared because of this
_listBox.Items = listBoxItems;
SelectIndexCentered(bestIndex);
}
/// <summary>
/// Selects the item that starts with the specified query.
/// </summary>
private void SelectItemWithStart(string query)
{
if (string.IsNullOrEmpty(query))
return;
var suggestedIndex = _listBox.SelectedIndex;
var bestIndex = -1;
var bestQuality = -1;
double bestPriority = 0;
for (var i = 0; i < _completionData.Count; ++i)
{
var quality = GetMatchQuality(_completionData[i].Text, query);
if (quality < 0)
continue;
var priority = _completionData[i].Priority;
bool useThisItem;
if (bestQuality < quality)
{
useThisItem = true;
}
else
{
if (bestIndex == suggestedIndex)
{
useThisItem = false;
}
else if (i == suggestedIndex)
{
// prefer recommendedItem, regardless of its priority
useThisItem = bestQuality == quality;
}
else
{
useThisItem = bestQuality == quality && bestPriority < priority;
}
}
if (useThisItem)
{
bestIndex = i;
bestPriority = priority;
bestQuality = quality;
}
}
SelectIndexCentered(bestIndex);
}
private void SelectIndexCentered(int bestIndex)
{
if (bestIndex < 0)
{
_listBox.ClearSelection();
}
else
{
var firstItem = _listBox.FirstVisibleItem;
if (bestIndex < firstItem || firstItem + _listBox.VisibleItemCount <= bestIndex)
{
// CenterViewOn does nothing as CompletionListBox.ScrollViewer is null
_listBox.CenterViewOn(bestIndex);
_listBox.SelectIndex(bestIndex);
}
else
{
_listBox.SelectIndex(bestIndex);
}
}
}
private int GetMatchQuality(string itemText, string query)
{
if (itemText == null)
throw new ArgumentNullException(nameof(itemText), "ICompletionData.Text returned null");
// Qualities:
// 8 = full match case sensitive
// 7 = full match
// 6 = match start case sensitive
// 5 = match start
// 4 = match CamelCase when length of query is 1 or 2 characters
// 3 = match substring case sensitive
// 2 = match substring
// 1 = match CamelCase
// -1 = no match
if (query == itemText)
return 8;
if (string.Equals(itemText, query, StringComparison.CurrentCultureIgnoreCase))
return 7;
if (itemText.StartsWith(query, StringComparison.CurrentCulture))
return 6;
if (itemText.StartsWith(query, StringComparison.CurrentCultureIgnoreCase))
return 5;
bool? camelCaseMatch = null;
if (query.Length <= 2)
{
camelCaseMatch = CamelCaseMatch(itemText, query);
if (camelCaseMatch == true) return 4;
}
// search by substring, if filtering (i.e. new behavior) turned on
if (IsFiltering)
{
if (itemText.IndexOf(query, StringComparison.CurrentCulture) >= 0)
return 3;
if (itemText.IndexOf(query, StringComparison.CurrentCultureIgnoreCase) >= 0)
return 2;
}
if (!camelCaseMatch.HasValue)
camelCaseMatch = CamelCaseMatch(itemText, query);
if (camelCaseMatch == true)
return 1;
return -1;
}
private static bool CamelCaseMatch(string text, string query)
{
// We take the first letter of the text regardless of whether or not it's upper case so we match
// against camelCase text as well as PascalCase text ("cct" matches "camelCaseText")
var theFirstLetterOfEachWord = text.AsEnumerable()
.Take(1)
.Concat(text.AsEnumerable().Skip(1).Where(char.IsUpper));
var i = 0;
foreach (var letter in theFirstLetterOfEachWord)
{
if (i > query.Length - 1)
return true; // return true here for CamelCase partial match ("CQ" matches "CodeQualityAnalysis")
if (char.ToUpperInvariant(query[i]) != char.ToUpperInvariant(letter))
return false;
i++;
}
if (i >= query.Length)
return true;
return false;
}
}
}
<MSG> Fix tooltip disappearing
<DFF> @@ -285,7 +285,7 @@ namespace AvaloniaEdit.CodeCompletion
}
_currentList = listBoxItems;
- _listBox.Items = null;
+ //_listBox.Items = null; Makes no sense? Tooltip disappeared because of this
_listBox.Items = listBoxItems;
SelectIndexCentered(bestIndex);
}
| 1 | Fix tooltip disappearing | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057730 | <NME> CompletionList.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.Collections.ObjectModel;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml.Templates;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.CodeCompletion
{
/// <summary>
/// The listbox used inside the CompletionWindow, contains CompletionListBox.
/// </summary>
public class CompletionList : TemplatedControl
{
public CompletionList()
{
DoubleTapped += OnDoubleTapped;
}
/// <summary>
/// If true, the CompletionList is filtered to show only matching items. Also enables search by substring.
/// If false, enables the old behavior: no filtering, search by string.StartsWith.
/// </summary>
public bool IsFiltering { get; set; } = true;
/// <summary>
/// Dependency property for <see cref="EmptyTemplate" />.
/// </summary>
public static readonly StyledProperty<ControlTemplate> EmptyTemplateProperty =
AvaloniaProperty.Register<CompletionList, ControlTemplate>(nameof(EmptyTemplate));
/// <summary>
/// Content of EmptyTemplate will be shown when CompletionList contains no items.
/// If EmptyTemplate is null, nothing will be shown.
/// </summary>
public ControlTemplate EmptyTemplate
{
get => GetValue(EmptyTemplateProperty);
set => SetValue(EmptyTemplateProperty, value);
}
/// <summary>
/// Is raised when the completion list indicates that the user has chosen
/// an entry to be completed.
/// </summary>
public event EventHandler InsertionRequested;
/// <summary>
/// Raises the InsertionRequested event.
/// </summary>
public void RequestInsertion(EventArgs e)
{
InsertionRequested?.Invoke(this, e);
}
private CompletionListBox _listBox;
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
_listBox = e.NameScope.Find("PART_ListBox") as CompletionListBox;
if (_listBox != null)
{
_listBox.Items = _completionData;
}
}
/// <summary>
/// Gets the list box.
/// </summary>
public CompletionListBox ListBox
{
get
{
if (_listBox == null)
ApplyTemplate();
return _listBox;
}
}
/// <summary>
/// Gets the scroll viewer used in this list box.
/// </summary>
public ScrollViewer ScrollViewer => _listBox?.ScrollViewer;
private readonly ObservableCollection<ICompletionData> _completionData = new ObservableCollection<ICompletionData>();
/// <summary>
/// Gets the list to which completion data can be added.
/// </summary>
public IList<ICompletionData> CompletionData => _completionData;
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (!e.Handled)
{
HandleKey(e);
}
}
/// <summary>
/// Handles a key press. Used to let the completion list handle key presses while the
/// focus is still on the text editor.
/// </summary>
public void HandleKey(KeyEventArgs e)
{
if (_listBox == null)
return;
// We have to do some key handling manually, because the default doesn't work with
// our simulated events.
// Also, the default PageUp/PageDown implementation changes the focus, so we avoid it.
switch (e.Key)
{
case Key.Down:
e.Handled = true;
_listBox.SelectIndex(_listBox.SelectedIndex + 1);
break;
case Key.Up:
e.Handled = true;
_listBox.SelectIndex(_listBox.SelectedIndex - 1);
break;
case Key.PageDown:
e.Handled = true;
_listBox.SelectIndex(_listBox.SelectedIndex + _listBox.VisibleItemCount);
break;
case Key.PageUp:
e.Handled = true;
_listBox.SelectIndex(_listBox.SelectedIndex - _listBox.VisibleItemCount);
break;
case Key.Home:
e.Handled = true;
_listBox.SelectIndex(0);
break;
case Key.End:
e.Handled = true;
_listBox.SelectIndex(_listBox.ItemCount - 1);
break;
case Key.Tab:
case Key.Enter:
if(CurrentList.Count > 0)
{
e.Handled = true;
RequestInsertion(e);
}
break;
}
}
protected void OnDoubleTapped(object sender, RoutedEventArgs e)
{
//TODO TEST
if (((AvaloniaObject)e.Source).VisualAncestorsAndSelf()
.TakeWhile(obj => obj != this).Any(obj => obj is ListBoxItem))
{
e.Handled = true;
RequestInsertion(e);
}
}
/// <summary>
/// Gets/Sets the selected item.
/// </summary>
/// <remarks>
/// The setter of this property does not scroll to the selected item.
/// You might want to also call <see cref="ScrollIntoView"/>.
/// </remarks>
public ICompletionData SelectedItem
{
get => _listBox?.SelectedItem as ICompletionData;
set
{
if (_listBox == null && value != null)
ApplyTemplate();
if (_listBox != null) // may still be null if ApplyTemplate fails, or if listBox and value both are null
_listBox.SelectedItem = value;
}
}
/// <summary>
/// Scrolls the specified item into view.
/// </summary>
public void ScrollIntoView(ICompletionData item)
{
if (_listBox == null)
ApplyTemplate();
_listBox?.ScrollIntoView(item);
}
/// <summary>
/// Occurs when the SelectedItem property changes.
/// </summary>
public event EventHandler<SelectionChangedEventArgs> SelectionChanged
{
add => AddHandler(SelectingItemsControl.SelectionChangedEvent, value);
remove => RemoveHandler(SelectingItemsControl.SelectionChangedEvent, value);
}
// SelectItem gets called twice for every typed character (once from FormatLine), this helps execute SelectItem only once
private string _currentText;
private ObservableCollection<ICompletionData> _currentList;
public List<ICompletionData> CurrentList
{
get => ListBox.Items.Cast<ICompletionData>().ToList();
}
/// <summary>
/// Selects the best match, and filter the items if turned on using <see cref="IsFiltering" />.
/// </summary>
public void SelectItem(string text)
{
if (text == _currentText)
return;
if (_listBox == null)
ApplyTemplate();
if (IsFiltering)
{
SelectItemFiltering(text);
}
else
{
SelectItemWithStart(text);
}
_currentText = text;
}
/// <summary>
/// Filters CompletionList items to show only those matching given query, and selects the best match.
/// </summary>
private void SelectItemFiltering(string query)
{
// if the user just typed one more character, don't filter all data but just filter what we are already displaying
var listToFilter = _currentList != null && !string.IsNullOrEmpty(_currentText) && !string.IsNullOrEmpty(query) &&
query.StartsWith(_currentText, StringComparison.Ordinal) ?
_currentList : _completionData;
var matchingItems =
from item in listToFilter
let quality = GetMatchQuality(item.Text, query)
where quality > 0
select new { Item = item, Quality = quality };
// e.g. "DateTimeKind k = (*cc here suggests DateTimeKind*)"
var suggestedItem = _listBox.SelectedIndex != -1 ? (ICompletionData)_listBox.SelectedItem : null;
var listBoxItems = new ObservableCollection<ICompletionData>();
var bestIndex = -1;
var bestQuality = -1;
double bestPriority = 0;
var i = 0;
foreach (var matchingItem in matchingItems)
{
var priority = matchingItem.Item == suggestedItem ? double.PositiveInfinity : matchingItem.Item.Priority;
var quality = matchingItem.Quality;
}
_currentList = listBoxItems;
_listBox.Items = null;
_listBox.Items = listBoxItems;
SelectIndexCentered(bestIndex);
}
i++;
}
_currentList = listBoxItems;
//_listBox.Items = null; Makes no sense? Tooltip disappeared because of this
_listBox.Items = listBoxItems;
SelectIndexCentered(bestIndex);
}
/// <summary>
/// Selects the item that starts with the specified query.
/// </summary>
private void SelectItemWithStart(string query)
{
if (string.IsNullOrEmpty(query))
return;
var suggestedIndex = _listBox.SelectedIndex;
var bestIndex = -1;
var bestQuality = -1;
double bestPriority = 0;
for (var i = 0; i < _completionData.Count; ++i)
{
var quality = GetMatchQuality(_completionData[i].Text, query);
if (quality < 0)
continue;
var priority = _completionData[i].Priority;
bool useThisItem;
if (bestQuality < quality)
{
useThisItem = true;
}
else
{
if (bestIndex == suggestedIndex)
{
useThisItem = false;
}
else if (i == suggestedIndex)
{
// prefer recommendedItem, regardless of its priority
useThisItem = bestQuality == quality;
}
else
{
useThisItem = bestQuality == quality && bestPriority < priority;
}
}
if (useThisItem)
{
bestIndex = i;
bestPriority = priority;
bestQuality = quality;
}
}
SelectIndexCentered(bestIndex);
}
private void SelectIndexCentered(int bestIndex)
{
if (bestIndex < 0)
{
_listBox.ClearSelection();
}
else
{
var firstItem = _listBox.FirstVisibleItem;
if (bestIndex < firstItem || firstItem + _listBox.VisibleItemCount <= bestIndex)
{
// CenterViewOn does nothing as CompletionListBox.ScrollViewer is null
_listBox.CenterViewOn(bestIndex);
_listBox.SelectIndex(bestIndex);
}
else
{
_listBox.SelectIndex(bestIndex);
}
}
}
private int GetMatchQuality(string itemText, string query)
{
if (itemText == null)
throw new ArgumentNullException(nameof(itemText), "ICompletionData.Text returned null");
// Qualities:
// 8 = full match case sensitive
// 7 = full match
// 6 = match start case sensitive
// 5 = match start
// 4 = match CamelCase when length of query is 1 or 2 characters
// 3 = match substring case sensitive
// 2 = match substring
// 1 = match CamelCase
// -1 = no match
if (query == itemText)
return 8;
if (string.Equals(itemText, query, StringComparison.CurrentCultureIgnoreCase))
return 7;
if (itemText.StartsWith(query, StringComparison.CurrentCulture))
return 6;
if (itemText.StartsWith(query, StringComparison.CurrentCultureIgnoreCase))
return 5;
bool? camelCaseMatch = null;
if (query.Length <= 2)
{
camelCaseMatch = CamelCaseMatch(itemText, query);
if (camelCaseMatch == true) return 4;
}
// search by substring, if filtering (i.e. new behavior) turned on
if (IsFiltering)
{
if (itemText.IndexOf(query, StringComparison.CurrentCulture) >= 0)
return 3;
if (itemText.IndexOf(query, StringComparison.CurrentCultureIgnoreCase) >= 0)
return 2;
}
if (!camelCaseMatch.HasValue)
camelCaseMatch = CamelCaseMatch(itemText, query);
if (camelCaseMatch == true)
return 1;
return -1;
}
private static bool CamelCaseMatch(string text, string query)
{
// We take the first letter of the text regardless of whether or not it's upper case so we match
// against camelCase text as well as PascalCase text ("cct" matches "camelCaseText")
var theFirstLetterOfEachWord = text.AsEnumerable()
.Take(1)
.Concat(text.AsEnumerable().Skip(1).Where(char.IsUpper));
var i = 0;
foreach (var letter in theFirstLetterOfEachWord)
{
if (i > query.Length - 1)
return true; // return true here for CamelCase partial match ("CQ" matches "CodeQualityAnalysis")
if (char.ToUpperInvariant(query[i]) != char.ToUpperInvariant(letter))
return false;
i++;
}
if (i >= query.Length)
return true;
return false;
}
}
}
<MSG> Fix tooltip disappearing
<DFF> @@ -285,7 +285,7 @@ namespace AvaloniaEdit.CodeCompletion
}
_currentList = listBoxItems;
- _listBox.Items = null;
+ //_listBox.Items = null; Makes no sense? Tooltip disappeared because of this
_listBox.Items = listBoxItems;
SelectIndexCentered(bestIndex);
}
| 1 | Fix tooltip disappearing | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057731 | <NME> CompletionList.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.Collections.ObjectModel;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml.Templates;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.CodeCompletion
{
/// <summary>
/// The listbox used inside the CompletionWindow, contains CompletionListBox.
/// </summary>
public class CompletionList : TemplatedControl
{
public CompletionList()
{
DoubleTapped += OnDoubleTapped;
}
/// <summary>
/// If true, the CompletionList is filtered to show only matching items. Also enables search by substring.
/// If false, enables the old behavior: no filtering, search by string.StartsWith.
/// </summary>
public bool IsFiltering { get; set; } = true;
/// <summary>
/// Dependency property for <see cref="EmptyTemplate" />.
/// </summary>
public static readonly StyledProperty<ControlTemplate> EmptyTemplateProperty =
AvaloniaProperty.Register<CompletionList, ControlTemplate>(nameof(EmptyTemplate));
/// <summary>
/// Content of EmptyTemplate will be shown when CompletionList contains no items.
/// If EmptyTemplate is null, nothing will be shown.
/// </summary>
public ControlTemplate EmptyTemplate
{
get => GetValue(EmptyTemplateProperty);
set => SetValue(EmptyTemplateProperty, value);
}
/// <summary>
/// Is raised when the completion list indicates that the user has chosen
/// an entry to be completed.
/// </summary>
public event EventHandler InsertionRequested;
/// <summary>
/// Raises the InsertionRequested event.
/// </summary>
public void RequestInsertion(EventArgs e)
{
InsertionRequested?.Invoke(this, e);
}
private CompletionListBox _listBox;
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
_listBox = e.NameScope.Find("PART_ListBox") as CompletionListBox;
if (_listBox != null)
{
_listBox.Items = _completionData;
}
}
/// <summary>
/// Gets the list box.
/// </summary>
public CompletionListBox ListBox
{
get
{
if (_listBox == null)
ApplyTemplate();
return _listBox;
}
}
/// <summary>
/// Gets the scroll viewer used in this list box.
/// </summary>
public ScrollViewer ScrollViewer => _listBox?.ScrollViewer;
private readonly ObservableCollection<ICompletionData> _completionData = new ObservableCollection<ICompletionData>();
/// <summary>
/// Gets the list to which completion data can be added.
/// </summary>
public IList<ICompletionData> CompletionData => _completionData;
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (!e.Handled)
{
HandleKey(e);
}
}
/// <summary>
/// Handles a key press. Used to let the completion list handle key presses while the
/// focus is still on the text editor.
/// </summary>
public void HandleKey(KeyEventArgs e)
{
if (_listBox == null)
return;
// We have to do some key handling manually, because the default doesn't work with
// our simulated events.
// Also, the default PageUp/PageDown implementation changes the focus, so we avoid it.
switch (e.Key)
{
case Key.Down:
e.Handled = true;
_listBox.SelectIndex(_listBox.SelectedIndex + 1);
break;
case Key.Up:
e.Handled = true;
_listBox.SelectIndex(_listBox.SelectedIndex - 1);
break;
case Key.PageDown:
e.Handled = true;
_listBox.SelectIndex(_listBox.SelectedIndex + _listBox.VisibleItemCount);
break;
case Key.PageUp:
e.Handled = true;
_listBox.SelectIndex(_listBox.SelectedIndex - _listBox.VisibleItemCount);
break;
case Key.Home:
e.Handled = true;
_listBox.SelectIndex(0);
break;
case Key.End:
e.Handled = true;
_listBox.SelectIndex(_listBox.ItemCount - 1);
break;
case Key.Tab:
case Key.Enter:
if(CurrentList.Count > 0)
{
e.Handled = true;
RequestInsertion(e);
}
break;
}
}
protected void OnDoubleTapped(object sender, RoutedEventArgs e)
{
//TODO TEST
if (((AvaloniaObject)e.Source).VisualAncestorsAndSelf()
.TakeWhile(obj => obj != this).Any(obj => obj is ListBoxItem))
{
e.Handled = true;
RequestInsertion(e);
}
}
/// <summary>
/// Gets/Sets the selected item.
/// </summary>
/// <remarks>
/// The setter of this property does not scroll to the selected item.
/// You might want to also call <see cref="ScrollIntoView"/>.
/// </remarks>
public ICompletionData SelectedItem
{
get => _listBox?.SelectedItem as ICompletionData;
set
{
if (_listBox == null && value != null)
ApplyTemplate();
if (_listBox != null) // may still be null if ApplyTemplate fails, or if listBox and value both are null
_listBox.SelectedItem = value;
}
}
/// <summary>
/// Scrolls the specified item into view.
/// </summary>
public void ScrollIntoView(ICompletionData item)
{
if (_listBox == null)
ApplyTemplate();
_listBox?.ScrollIntoView(item);
}
/// <summary>
/// Occurs when the SelectedItem property changes.
/// </summary>
public event EventHandler<SelectionChangedEventArgs> SelectionChanged
{
add => AddHandler(SelectingItemsControl.SelectionChangedEvent, value);
remove => RemoveHandler(SelectingItemsControl.SelectionChangedEvent, value);
}
// SelectItem gets called twice for every typed character (once from FormatLine), this helps execute SelectItem only once
private string _currentText;
private ObservableCollection<ICompletionData> _currentList;
public List<ICompletionData> CurrentList
{
get => ListBox.Items.Cast<ICompletionData>().ToList();
}
/// <summary>
/// Selects the best match, and filter the items if turned on using <see cref="IsFiltering" />.
/// </summary>
public void SelectItem(string text)
{
if (text == _currentText)
return;
if (_listBox == null)
ApplyTemplate();
if (IsFiltering)
{
SelectItemFiltering(text);
}
else
{
SelectItemWithStart(text);
}
_currentText = text;
}
/// <summary>
/// Filters CompletionList items to show only those matching given query, and selects the best match.
/// </summary>
private void SelectItemFiltering(string query)
{
// if the user just typed one more character, don't filter all data but just filter what we are already displaying
var listToFilter = _currentList != null && !string.IsNullOrEmpty(_currentText) && !string.IsNullOrEmpty(query) &&
query.StartsWith(_currentText, StringComparison.Ordinal) ?
_currentList : _completionData;
var matchingItems =
from item in listToFilter
let quality = GetMatchQuality(item.Text, query)
where quality > 0
select new { Item = item, Quality = quality };
// e.g. "DateTimeKind k = (*cc here suggests DateTimeKind*)"
var suggestedItem = _listBox.SelectedIndex != -1 ? (ICompletionData)_listBox.SelectedItem : null;
var listBoxItems = new ObservableCollection<ICompletionData>();
var bestIndex = -1;
var bestQuality = -1;
double bestPriority = 0;
var i = 0;
foreach (var matchingItem in matchingItems)
{
var priority = matchingItem.Item == suggestedItem ? double.PositiveInfinity : matchingItem.Item.Priority;
var quality = matchingItem.Quality;
}
_currentList = listBoxItems;
_listBox.Items = null;
_listBox.Items = listBoxItems;
SelectIndexCentered(bestIndex);
}
i++;
}
_currentList = listBoxItems;
//_listBox.Items = null; Makes no sense? Tooltip disappeared because of this
_listBox.Items = listBoxItems;
SelectIndexCentered(bestIndex);
}
/// <summary>
/// Selects the item that starts with the specified query.
/// </summary>
private void SelectItemWithStart(string query)
{
if (string.IsNullOrEmpty(query))
return;
var suggestedIndex = _listBox.SelectedIndex;
var bestIndex = -1;
var bestQuality = -1;
double bestPriority = 0;
for (var i = 0; i < _completionData.Count; ++i)
{
var quality = GetMatchQuality(_completionData[i].Text, query);
if (quality < 0)
continue;
var priority = _completionData[i].Priority;
bool useThisItem;
if (bestQuality < quality)
{
useThisItem = true;
}
else
{
if (bestIndex == suggestedIndex)
{
useThisItem = false;
}
else if (i == suggestedIndex)
{
// prefer recommendedItem, regardless of its priority
useThisItem = bestQuality == quality;
}
else
{
useThisItem = bestQuality == quality && bestPriority < priority;
}
}
if (useThisItem)
{
bestIndex = i;
bestPriority = priority;
bestQuality = quality;
}
}
SelectIndexCentered(bestIndex);
}
private void SelectIndexCentered(int bestIndex)
{
if (bestIndex < 0)
{
_listBox.ClearSelection();
}
else
{
var firstItem = _listBox.FirstVisibleItem;
if (bestIndex < firstItem || firstItem + _listBox.VisibleItemCount <= bestIndex)
{
// CenterViewOn does nothing as CompletionListBox.ScrollViewer is null
_listBox.CenterViewOn(bestIndex);
_listBox.SelectIndex(bestIndex);
}
else
{
_listBox.SelectIndex(bestIndex);
}
}
}
private int GetMatchQuality(string itemText, string query)
{
if (itemText == null)
throw new ArgumentNullException(nameof(itemText), "ICompletionData.Text returned null");
// Qualities:
// 8 = full match case sensitive
// 7 = full match
// 6 = match start case sensitive
// 5 = match start
// 4 = match CamelCase when length of query is 1 or 2 characters
// 3 = match substring case sensitive
// 2 = match substring
// 1 = match CamelCase
// -1 = no match
if (query == itemText)
return 8;
if (string.Equals(itemText, query, StringComparison.CurrentCultureIgnoreCase))
return 7;
if (itemText.StartsWith(query, StringComparison.CurrentCulture))
return 6;
if (itemText.StartsWith(query, StringComparison.CurrentCultureIgnoreCase))
return 5;
bool? camelCaseMatch = null;
if (query.Length <= 2)
{
camelCaseMatch = CamelCaseMatch(itemText, query);
if (camelCaseMatch == true) return 4;
}
// search by substring, if filtering (i.e. new behavior) turned on
if (IsFiltering)
{
if (itemText.IndexOf(query, StringComparison.CurrentCulture) >= 0)
return 3;
if (itemText.IndexOf(query, StringComparison.CurrentCultureIgnoreCase) >= 0)
return 2;
}
if (!camelCaseMatch.HasValue)
camelCaseMatch = CamelCaseMatch(itemText, query);
if (camelCaseMatch == true)
return 1;
return -1;
}
private static bool CamelCaseMatch(string text, string query)
{
// We take the first letter of the text regardless of whether or not it's upper case so we match
// against camelCase text as well as PascalCase text ("cct" matches "camelCaseText")
var theFirstLetterOfEachWord = text.AsEnumerable()
.Take(1)
.Concat(text.AsEnumerable().Skip(1).Where(char.IsUpper));
var i = 0;
foreach (var letter in theFirstLetterOfEachWord)
{
if (i > query.Length - 1)
return true; // return true here for CamelCase partial match ("CQ" matches "CodeQualityAnalysis")
if (char.ToUpperInvariant(query[i]) != char.ToUpperInvariant(letter))
return false;
i++;
}
if (i >= query.Length)
return true;
return false;
}
}
}
<MSG> Fix tooltip disappearing
<DFF> @@ -285,7 +285,7 @@ namespace AvaloniaEdit.CodeCompletion
}
_currentList = listBoxItems;
- _listBox.Items = null;
+ //_listBox.Items = null; Makes no sense? Tooltip disappeared because of this
_listBox.Items = listBoxItems;
SelectIndexCentered(bestIndex);
}
| 1 | Fix tooltip disappearing | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057732 | <NME> CompletionList.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.Collections.ObjectModel;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml.Templates;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.CodeCompletion
{
/// <summary>
/// The listbox used inside the CompletionWindow, contains CompletionListBox.
/// </summary>
public class CompletionList : TemplatedControl
{
public CompletionList()
{
DoubleTapped += OnDoubleTapped;
}
/// <summary>
/// If true, the CompletionList is filtered to show only matching items. Also enables search by substring.
/// If false, enables the old behavior: no filtering, search by string.StartsWith.
/// </summary>
public bool IsFiltering { get; set; } = true;
/// <summary>
/// Dependency property for <see cref="EmptyTemplate" />.
/// </summary>
public static readonly StyledProperty<ControlTemplate> EmptyTemplateProperty =
AvaloniaProperty.Register<CompletionList, ControlTemplate>(nameof(EmptyTemplate));
/// <summary>
/// Content of EmptyTemplate will be shown when CompletionList contains no items.
/// If EmptyTemplate is null, nothing will be shown.
/// </summary>
public ControlTemplate EmptyTemplate
{
get => GetValue(EmptyTemplateProperty);
set => SetValue(EmptyTemplateProperty, value);
}
/// <summary>
/// Is raised when the completion list indicates that the user has chosen
/// an entry to be completed.
/// </summary>
public event EventHandler InsertionRequested;
/// <summary>
/// Raises the InsertionRequested event.
/// </summary>
public void RequestInsertion(EventArgs e)
{
InsertionRequested?.Invoke(this, e);
}
private CompletionListBox _listBox;
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
_listBox = e.NameScope.Find("PART_ListBox") as CompletionListBox;
if (_listBox != null)
{
_listBox.Items = _completionData;
}
}
/// <summary>
/// Gets the list box.
/// </summary>
public CompletionListBox ListBox
{
get
{
if (_listBox == null)
ApplyTemplate();
return _listBox;
}
}
/// <summary>
/// Gets the scroll viewer used in this list box.
/// </summary>
public ScrollViewer ScrollViewer => _listBox?.ScrollViewer;
private readonly ObservableCollection<ICompletionData> _completionData = new ObservableCollection<ICompletionData>();
/// <summary>
/// Gets the list to which completion data can be added.
/// </summary>
public IList<ICompletionData> CompletionData => _completionData;
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (!e.Handled)
{
HandleKey(e);
}
}
/// <summary>
/// Handles a key press. Used to let the completion list handle key presses while the
/// focus is still on the text editor.
/// </summary>
public void HandleKey(KeyEventArgs e)
{
if (_listBox == null)
return;
// We have to do some key handling manually, because the default doesn't work with
// our simulated events.
// Also, the default PageUp/PageDown implementation changes the focus, so we avoid it.
switch (e.Key)
{
case Key.Down:
e.Handled = true;
_listBox.SelectIndex(_listBox.SelectedIndex + 1);
break;
case Key.Up:
e.Handled = true;
_listBox.SelectIndex(_listBox.SelectedIndex - 1);
break;
case Key.PageDown:
e.Handled = true;
_listBox.SelectIndex(_listBox.SelectedIndex + _listBox.VisibleItemCount);
break;
case Key.PageUp:
e.Handled = true;
_listBox.SelectIndex(_listBox.SelectedIndex - _listBox.VisibleItemCount);
break;
case Key.Home:
e.Handled = true;
_listBox.SelectIndex(0);
break;
case Key.End:
e.Handled = true;
_listBox.SelectIndex(_listBox.ItemCount - 1);
break;
case Key.Tab:
case Key.Enter:
if(CurrentList.Count > 0)
{
e.Handled = true;
RequestInsertion(e);
}
break;
}
}
protected void OnDoubleTapped(object sender, RoutedEventArgs e)
{
//TODO TEST
if (((AvaloniaObject)e.Source).VisualAncestorsAndSelf()
.TakeWhile(obj => obj != this).Any(obj => obj is ListBoxItem))
{
e.Handled = true;
RequestInsertion(e);
}
}
/// <summary>
/// Gets/Sets the selected item.
/// </summary>
/// <remarks>
/// The setter of this property does not scroll to the selected item.
/// You might want to also call <see cref="ScrollIntoView"/>.
/// </remarks>
public ICompletionData SelectedItem
{
get => _listBox?.SelectedItem as ICompletionData;
set
{
if (_listBox == null && value != null)
ApplyTemplate();
if (_listBox != null) // may still be null if ApplyTemplate fails, or if listBox and value both are null
_listBox.SelectedItem = value;
}
}
/// <summary>
/// Scrolls the specified item into view.
/// </summary>
public void ScrollIntoView(ICompletionData item)
{
if (_listBox == null)
ApplyTemplate();
_listBox?.ScrollIntoView(item);
}
/// <summary>
/// Occurs when the SelectedItem property changes.
/// </summary>
public event EventHandler<SelectionChangedEventArgs> SelectionChanged
{
add => AddHandler(SelectingItemsControl.SelectionChangedEvent, value);
remove => RemoveHandler(SelectingItemsControl.SelectionChangedEvent, value);
}
// SelectItem gets called twice for every typed character (once from FormatLine), this helps execute SelectItem only once
private string _currentText;
private ObservableCollection<ICompletionData> _currentList;
public List<ICompletionData> CurrentList
{
get => ListBox.Items.Cast<ICompletionData>().ToList();
}
/// <summary>
/// Selects the best match, and filter the items if turned on using <see cref="IsFiltering" />.
/// </summary>
public void SelectItem(string text)
{
if (text == _currentText)
return;
if (_listBox == null)
ApplyTemplate();
if (IsFiltering)
{
SelectItemFiltering(text);
}
else
{
SelectItemWithStart(text);
}
_currentText = text;
}
/// <summary>
/// Filters CompletionList items to show only those matching given query, and selects the best match.
/// </summary>
private void SelectItemFiltering(string query)
{
// if the user just typed one more character, don't filter all data but just filter what we are already displaying
var listToFilter = _currentList != null && !string.IsNullOrEmpty(_currentText) && !string.IsNullOrEmpty(query) &&
query.StartsWith(_currentText, StringComparison.Ordinal) ?
_currentList : _completionData;
var matchingItems =
from item in listToFilter
let quality = GetMatchQuality(item.Text, query)
where quality > 0
select new { Item = item, Quality = quality };
// e.g. "DateTimeKind k = (*cc here suggests DateTimeKind*)"
var suggestedItem = _listBox.SelectedIndex != -1 ? (ICompletionData)_listBox.SelectedItem : null;
var listBoxItems = new ObservableCollection<ICompletionData>();
var bestIndex = -1;
var bestQuality = -1;
double bestPriority = 0;
var i = 0;
foreach (var matchingItem in matchingItems)
{
var priority = matchingItem.Item == suggestedItem ? double.PositiveInfinity : matchingItem.Item.Priority;
var quality = matchingItem.Quality;
}
_currentList = listBoxItems;
_listBox.Items = null;
_listBox.Items = listBoxItems;
SelectIndexCentered(bestIndex);
}
i++;
}
_currentList = listBoxItems;
//_listBox.Items = null; Makes no sense? Tooltip disappeared because of this
_listBox.Items = listBoxItems;
SelectIndexCentered(bestIndex);
}
/// <summary>
/// Selects the item that starts with the specified query.
/// </summary>
private void SelectItemWithStart(string query)
{
if (string.IsNullOrEmpty(query))
return;
var suggestedIndex = _listBox.SelectedIndex;
var bestIndex = -1;
var bestQuality = -1;
double bestPriority = 0;
for (var i = 0; i < _completionData.Count; ++i)
{
var quality = GetMatchQuality(_completionData[i].Text, query);
if (quality < 0)
continue;
var priority = _completionData[i].Priority;
bool useThisItem;
if (bestQuality < quality)
{
useThisItem = true;
}
else
{
if (bestIndex == suggestedIndex)
{
useThisItem = false;
}
else if (i == suggestedIndex)
{
// prefer recommendedItem, regardless of its priority
useThisItem = bestQuality == quality;
}
else
{
useThisItem = bestQuality == quality && bestPriority < priority;
}
}
if (useThisItem)
{
bestIndex = i;
bestPriority = priority;
bestQuality = quality;
}
}
SelectIndexCentered(bestIndex);
}
private void SelectIndexCentered(int bestIndex)
{
if (bestIndex < 0)
{
_listBox.ClearSelection();
}
else
{
var firstItem = _listBox.FirstVisibleItem;
if (bestIndex < firstItem || firstItem + _listBox.VisibleItemCount <= bestIndex)
{
// CenterViewOn does nothing as CompletionListBox.ScrollViewer is null
_listBox.CenterViewOn(bestIndex);
_listBox.SelectIndex(bestIndex);
}
else
{
_listBox.SelectIndex(bestIndex);
}
}
}
private int GetMatchQuality(string itemText, string query)
{
if (itemText == null)
throw new ArgumentNullException(nameof(itemText), "ICompletionData.Text returned null");
// Qualities:
// 8 = full match case sensitive
// 7 = full match
// 6 = match start case sensitive
// 5 = match start
// 4 = match CamelCase when length of query is 1 or 2 characters
// 3 = match substring case sensitive
// 2 = match substring
// 1 = match CamelCase
// -1 = no match
if (query == itemText)
return 8;
if (string.Equals(itemText, query, StringComparison.CurrentCultureIgnoreCase))
return 7;
if (itemText.StartsWith(query, StringComparison.CurrentCulture))
return 6;
if (itemText.StartsWith(query, StringComparison.CurrentCultureIgnoreCase))
return 5;
bool? camelCaseMatch = null;
if (query.Length <= 2)
{
camelCaseMatch = CamelCaseMatch(itemText, query);
if (camelCaseMatch == true) return 4;
}
// search by substring, if filtering (i.e. new behavior) turned on
if (IsFiltering)
{
if (itemText.IndexOf(query, StringComparison.CurrentCulture) >= 0)
return 3;
if (itemText.IndexOf(query, StringComparison.CurrentCultureIgnoreCase) >= 0)
return 2;
}
if (!camelCaseMatch.HasValue)
camelCaseMatch = CamelCaseMatch(itemText, query);
if (camelCaseMatch == true)
return 1;
return -1;
}
private static bool CamelCaseMatch(string text, string query)
{
// We take the first letter of the text regardless of whether or not it's upper case so we match
// against camelCase text as well as PascalCase text ("cct" matches "camelCaseText")
var theFirstLetterOfEachWord = text.AsEnumerable()
.Take(1)
.Concat(text.AsEnumerable().Skip(1).Where(char.IsUpper));
var i = 0;
foreach (var letter in theFirstLetterOfEachWord)
{
if (i > query.Length - 1)
return true; // return true here for CamelCase partial match ("CQ" matches "CodeQualityAnalysis")
if (char.ToUpperInvariant(query[i]) != char.ToUpperInvariant(letter))
return false;
i++;
}
if (i >= query.Length)
return true;
return false;
}
}
}
<MSG> Fix tooltip disappearing
<DFF> @@ -285,7 +285,7 @@ namespace AvaloniaEdit.CodeCompletion
}
_currentList = listBoxItems;
- _listBox.Items = null;
+ //_listBox.Items = null; Makes no sense? Tooltip disappeared because of this
_listBox.Items = listBoxItems;
SelectIndexCentered(bestIndex);
}
| 1 | Fix tooltip disappearing | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057733 | <NME> CompletionList.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.Collections.ObjectModel;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml.Templates;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.CodeCompletion
{
/// <summary>
/// The listbox used inside the CompletionWindow, contains CompletionListBox.
/// </summary>
public class CompletionList : TemplatedControl
{
public CompletionList()
{
DoubleTapped += OnDoubleTapped;
}
/// <summary>
/// If true, the CompletionList is filtered to show only matching items. Also enables search by substring.
/// If false, enables the old behavior: no filtering, search by string.StartsWith.
/// </summary>
public bool IsFiltering { get; set; } = true;
/// <summary>
/// Dependency property for <see cref="EmptyTemplate" />.
/// </summary>
public static readonly StyledProperty<ControlTemplate> EmptyTemplateProperty =
AvaloniaProperty.Register<CompletionList, ControlTemplate>(nameof(EmptyTemplate));
/// <summary>
/// Content of EmptyTemplate will be shown when CompletionList contains no items.
/// If EmptyTemplate is null, nothing will be shown.
/// </summary>
public ControlTemplate EmptyTemplate
{
get => GetValue(EmptyTemplateProperty);
set => SetValue(EmptyTemplateProperty, value);
}
/// <summary>
/// Is raised when the completion list indicates that the user has chosen
/// an entry to be completed.
/// </summary>
public event EventHandler InsertionRequested;
/// <summary>
/// Raises the InsertionRequested event.
/// </summary>
public void RequestInsertion(EventArgs e)
{
InsertionRequested?.Invoke(this, e);
}
private CompletionListBox _listBox;
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
_listBox = e.NameScope.Find("PART_ListBox") as CompletionListBox;
if (_listBox != null)
{
_listBox.Items = _completionData;
}
}
/// <summary>
/// Gets the list box.
/// </summary>
public CompletionListBox ListBox
{
get
{
if (_listBox == null)
ApplyTemplate();
return _listBox;
}
}
/// <summary>
/// Gets the scroll viewer used in this list box.
/// </summary>
public ScrollViewer ScrollViewer => _listBox?.ScrollViewer;
private readonly ObservableCollection<ICompletionData> _completionData = new ObservableCollection<ICompletionData>();
/// <summary>
/// Gets the list to which completion data can be added.
/// </summary>
public IList<ICompletionData> CompletionData => _completionData;
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (!e.Handled)
{
HandleKey(e);
}
}
/// <summary>
/// Handles a key press. Used to let the completion list handle key presses while the
/// focus is still on the text editor.
/// </summary>
public void HandleKey(KeyEventArgs e)
{
if (_listBox == null)
return;
// We have to do some key handling manually, because the default doesn't work with
// our simulated events.
// Also, the default PageUp/PageDown implementation changes the focus, so we avoid it.
switch (e.Key)
{
case Key.Down:
e.Handled = true;
_listBox.SelectIndex(_listBox.SelectedIndex + 1);
break;
case Key.Up:
e.Handled = true;
_listBox.SelectIndex(_listBox.SelectedIndex - 1);
break;
case Key.PageDown:
e.Handled = true;
_listBox.SelectIndex(_listBox.SelectedIndex + _listBox.VisibleItemCount);
break;
case Key.PageUp:
e.Handled = true;
_listBox.SelectIndex(_listBox.SelectedIndex - _listBox.VisibleItemCount);
break;
case Key.Home:
e.Handled = true;
_listBox.SelectIndex(0);
break;
case Key.End:
e.Handled = true;
_listBox.SelectIndex(_listBox.ItemCount - 1);
break;
case Key.Tab:
case Key.Enter:
if(CurrentList.Count > 0)
{
e.Handled = true;
RequestInsertion(e);
}
break;
}
}
protected void OnDoubleTapped(object sender, RoutedEventArgs e)
{
//TODO TEST
if (((AvaloniaObject)e.Source).VisualAncestorsAndSelf()
.TakeWhile(obj => obj != this).Any(obj => obj is ListBoxItem))
{
e.Handled = true;
RequestInsertion(e);
}
}
/// <summary>
/// Gets/Sets the selected item.
/// </summary>
/// <remarks>
/// The setter of this property does not scroll to the selected item.
/// You might want to also call <see cref="ScrollIntoView"/>.
/// </remarks>
public ICompletionData SelectedItem
{
get => _listBox?.SelectedItem as ICompletionData;
set
{
if (_listBox == null && value != null)
ApplyTemplate();
if (_listBox != null) // may still be null if ApplyTemplate fails, or if listBox and value both are null
_listBox.SelectedItem = value;
}
}
/// <summary>
/// Scrolls the specified item into view.
/// </summary>
public void ScrollIntoView(ICompletionData item)
{
if (_listBox == null)
ApplyTemplate();
_listBox?.ScrollIntoView(item);
}
/// <summary>
/// Occurs when the SelectedItem property changes.
/// </summary>
public event EventHandler<SelectionChangedEventArgs> SelectionChanged
{
add => AddHandler(SelectingItemsControl.SelectionChangedEvent, value);
remove => RemoveHandler(SelectingItemsControl.SelectionChangedEvent, value);
}
// SelectItem gets called twice for every typed character (once from FormatLine), this helps execute SelectItem only once
private string _currentText;
private ObservableCollection<ICompletionData> _currentList;
public List<ICompletionData> CurrentList
{
get => ListBox.Items.Cast<ICompletionData>().ToList();
}
/// <summary>
/// Selects the best match, and filter the items if turned on using <see cref="IsFiltering" />.
/// </summary>
public void SelectItem(string text)
{
if (text == _currentText)
return;
if (_listBox == null)
ApplyTemplate();
if (IsFiltering)
{
SelectItemFiltering(text);
}
else
{
SelectItemWithStart(text);
}
_currentText = text;
}
/// <summary>
/// Filters CompletionList items to show only those matching given query, and selects the best match.
/// </summary>
private void SelectItemFiltering(string query)
{
// if the user just typed one more character, don't filter all data but just filter what we are already displaying
var listToFilter = _currentList != null && !string.IsNullOrEmpty(_currentText) && !string.IsNullOrEmpty(query) &&
query.StartsWith(_currentText, StringComparison.Ordinal) ?
_currentList : _completionData;
var matchingItems =
from item in listToFilter
let quality = GetMatchQuality(item.Text, query)
where quality > 0
select new { Item = item, Quality = quality };
// e.g. "DateTimeKind k = (*cc here suggests DateTimeKind*)"
var suggestedItem = _listBox.SelectedIndex != -1 ? (ICompletionData)_listBox.SelectedItem : null;
var listBoxItems = new ObservableCollection<ICompletionData>();
var bestIndex = -1;
var bestQuality = -1;
double bestPriority = 0;
var i = 0;
foreach (var matchingItem in matchingItems)
{
var priority = matchingItem.Item == suggestedItem ? double.PositiveInfinity : matchingItem.Item.Priority;
var quality = matchingItem.Quality;
}
_currentList = listBoxItems;
_listBox.Items = null;
_listBox.Items = listBoxItems;
SelectIndexCentered(bestIndex);
}
i++;
}
_currentList = listBoxItems;
//_listBox.Items = null; Makes no sense? Tooltip disappeared because of this
_listBox.Items = listBoxItems;
SelectIndexCentered(bestIndex);
}
/// <summary>
/// Selects the item that starts with the specified query.
/// </summary>
private void SelectItemWithStart(string query)
{
if (string.IsNullOrEmpty(query))
return;
var suggestedIndex = _listBox.SelectedIndex;
var bestIndex = -1;
var bestQuality = -1;
double bestPriority = 0;
for (var i = 0; i < _completionData.Count; ++i)
{
var quality = GetMatchQuality(_completionData[i].Text, query);
if (quality < 0)
continue;
var priority = _completionData[i].Priority;
bool useThisItem;
if (bestQuality < quality)
{
useThisItem = true;
}
else
{
if (bestIndex == suggestedIndex)
{
useThisItem = false;
}
else if (i == suggestedIndex)
{
// prefer recommendedItem, regardless of its priority
useThisItem = bestQuality == quality;
}
else
{
useThisItem = bestQuality == quality && bestPriority < priority;
}
}
if (useThisItem)
{
bestIndex = i;
bestPriority = priority;
bestQuality = quality;
}
}
SelectIndexCentered(bestIndex);
}
private void SelectIndexCentered(int bestIndex)
{
if (bestIndex < 0)
{
_listBox.ClearSelection();
}
else
{
var firstItem = _listBox.FirstVisibleItem;
if (bestIndex < firstItem || firstItem + _listBox.VisibleItemCount <= bestIndex)
{
// CenterViewOn does nothing as CompletionListBox.ScrollViewer is null
_listBox.CenterViewOn(bestIndex);
_listBox.SelectIndex(bestIndex);
}
else
{
_listBox.SelectIndex(bestIndex);
}
}
}
private int GetMatchQuality(string itemText, string query)
{
if (itemText == null)
throw new ArgumentNullException(nameof(itemText), "ICompletionData.Text returned null");
// Qualities:
// 8 = full match case sensitive
// 7 = full match
// 6 = match start case sensitive
// 5 = match start
// 4 = match CamelCase when length of query is 1 or 2 characters
// 3 = match substring case sensitive
// 2 = match substring
// 1 = match CamelCase
// -1 = no match
if (query == itemText)
return 8;
if (string.Equals(itemText, query, StringComparison.CurrentCultureIgnoreCase))
return 7;
if (itemText.StartsWith(query, StringComparison.CurrentCulture))
return 6;
if (itemText.StartsWith(query, StringComparison.CurrentCultureIgnoreCase))
return 5;
bool? camelCaseMatch = null;
if (query.Length <= 2)
{
camelCaseMatch = CamelCaseMatch(itemText, query);
if (camelCaseMatch == true) return 4;
}
// search by substring, if filtering (i.e. new behavior) turned on
if (IsFiltering)
{
if (itemText.IndexOf(query, StringComparison.CurrentCulture) >= 0)
return 3;
if (itemText.IndexOf(query, StringComparison.CurrentCultureIgnoreCase) >= 0)
return 2;
}
if (!camelCaseMatch.HasValue)
camelCaseMatch = CamelCaseMatch(itemText, query);
if (camelCaseMatch == true)
return 1;
return -1;
}
private static bool CamelCaseMatch(string text, string query)
{
// We take the first letter of the text regardless of whether or not it's upper case so we match
// against camelCase text as well as PascalCase text ("cct" matches "camelCaseText")
var theFirstLetterOfEachWord = text.AsEnumerable()
.Take(1)
.Concat(text.AsEnumerable().Skip(1).Where(char.IsUpper));
var i = 0;
foreach (var letter in theFirstLetterOfEachWord)
{
if (i > query.Length - 1)
return true; // return true here for CamelCase partial match ("CQ" matches "CodeQualityAnalysis")
if (char.ToUpperInvariant(query[i]) != char.ToUpperInvariant(letter))
return false;
i++;
}
if (i >= query.Length)
return true;
return false;
}
}
}
<MSG> Fix tooltip disappearing
<DFF> @@ -285,7 +285,7 @@ namespace AvaloniaEdit.CodeCompletion
}
_currentList = listBoxItems;
- _listBox.Items = null;
+ //_listBox.Items = null; Makes no sense? Tooltip disappeared because of this
_listBox.Items = listBoxItems;
SelectIndexCentered(bestIndex);
}
| 1 | Fix tooltip disappearing | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057734 | <NME> CompletionList.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.Collections.ObjectModel;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml.Templates;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.CodeCompletion
{
/// <summary>
/// The listbox used inside the CompletionWindow, contains CompletionListBox.
/// </summary>
public class CompletionList : TemplatedControl
{
public CompletionList()
{
DoubleTapped += OnDoubleTapped;
}
/// <summary>
/// If true, the CompletionList is filtered to show only matching items. Also enables search by substring.
/// If false, enables the old behavior: no filtering, search by string.StartsWith.
/// </summary>
public bool IsFiltering { get; set; } = true;
/// <summary>
/// Dependency property for <see cref="EmptyTemplate" />.
/// </summary>
public static readonly StyledProperty<ControlTemplate> EmptyTemplateProperty =
AvaloniaProperty.Register<CompletionList, ControlTemplate>(nameof(EmptyTemplate));
/// <summary>
/// Content of EmptyTemplate will be shown when CompletionList contains no items.
/// If EmptyTemplate is null, nothing will be shown.
/// </summary>
public ControlTemplate EmptyTemplate
{
get => GetValue(EmptyTemplateProperty);
set => SetValue(EmptyTemplateProperty, value);
}
/// <summary>
/// Is raised when the completion list indicates that the user has chosen
/// an entry to be completed.
/// </summary>
public event EventHandler InsertionRequested;
/// <summary>
/// Raises the InsertionRequested event.
/// </summary>
public void RequestInsertion(EventArgs e)
{
InsertionRequested?.Invoke(this, e);
}
private CompletionListBox _listBox;
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
_listBox = e.NameScope.Find("PART_ListBox") as CompletionListBox;
if (_listBox != null)
{
_listBox.Items = _completionData;
}
}
/// <summary>
/// Gets the list box.
/// </summary>
public CompletionListBox ListBox
{
get
{
if (_listBox == null)
ApplyTemplate();
return _listBox;
}
}
/// <summary>
/// Gets the scroll viewer used in this list box.
/// </summary>
public ScrollViewer ScrollViewer => _listBox?.ScrollViewer;
private readonly ObservableCollection<ICompletionData> _completionData = new ObservableCollection<ICompletionData>();
/// <summary>
/// Gets the list to which completion data can be added.
/// </summary>
public IList<ICompletionData> CompletionData => _completionData;
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (!e.Handled)
{
HandleKey(e);
}
}
/// <summary>
/// Handles a key press. Used to let the completion list handle key presses while the
/// focus is still on the text editor.
/// </summary>
public void HandleKey(KeyEventArgs e)
{
if (_listBox == null)
return;
// We have to do some key handling manually, because the default doesn't work with
// our simulated events.
// Also, the default PageUp/PageDown implementation changes the focus, so we avoid it.
switch (e.Key)
{
case Key.Down:
e.Handled = true;
_listBox.SelectIndex(_listBox.SelectedIndex + 1);
break;
case Key.Up:
e.Handled = true;
_listBox.SelectIndex(_listBox.SelectedIndex - 1);
break;
case Key.PageDown:
e.Handled = true;
_listBox.SelectIndex(_listBox.SelectedIndex + _listBox.VisibleItemCount);
break;
case Key.PageUp:
e.Handled = true;
_listBox.SelectIndex(_listBox.SelectedIndex - _listBox.VisibleItemCount);
break;
case Key.Home:
e.Handled = true;
_listBox.SelectIndex(0);
break;
case Key.End:
e.Handled = true;
_listBox.SelectIndex(_listBox.ItemCount - 1);
break;
case Key.Tab:
case Key.Enter:
if(CurrentList.Count > 0)
{
e.Handled = true;
RequestInsertion(e);
}
break;
}
}
protected void OnDoubleTapped(object sender, RoutedEventArgs e)
{
//TODO TEST
if (((AvaloniaObject)e.Source).VisualAncestorsAndSelf()
.TakeWhile(obj => obj != this).Any(obj => obj is ListBoxItem))
{
e.Handled = true;
RequestInsertion(e);
}
}
/// <summary>
/// Gets/Sets the selected item.
/// </summary>
/// <remarks>
/// The setter of this property does not scroll to the selected item.
/// You might want to also call <see cref="ScrollIntoView"/>.
/// </remarks>
public ICompletionData SelectedItem
{
get => _listBox?.SelectedItem as ICompletionData;
set
{
if (_listBox == null && value != null)
ApplyTemplate();
if (_listBox != null) // may still be null if ApplyTemplate fails, or if listBox and value both are null
_listBox.SelectedItem = value;
}
}
/// <summary>
/// Scrolls the specified item into view.
/// </summary>
public void ScrollIntoView(ICompletionData item)
{
if (_listBox == null)
ApplyTemplate();
_listBox?.ScrollIntoView(item);
}
/// <summary>
/// Occurs when the SelectedItem property changes.
/// </summary>
public event EventHandler<SelectionChangedEventArgs> SelectionChanged
{
add => AddHandler(SelectingItemsControl.SelectionChangedEvent, value);
remove => RemoveHandler(SelectingItemsControl.SelectionChangedEvent, value);
}
// SelectItem gets called twice for every typed character (once from FormatLine), this helps execute SelectItem only once
private string _currentText;
private ObservableCollection<ICompletionData> _currentList;
public List<ICompletionData> CurrentList
{
get => ListBox.Items.Cast<ICompletionData>().ToList();
}
/// <summary>
/// Selects the best match, and filter the items if turned on using <see cref="IsFiltering" />.
/// </summary>
public void SelectItem(string text)
{
if (text == _currentText)
return;
if (_listBox == null)
ApplyTemplate();
if (IsFiltering)
{
SelectItemFiltering(text);
}
else
{
SelectItemWithStart(text);
}
_currentText = text;
}
/// <summary>
/// Filters CompletionList items to show only those matching given query, and selects the best match.
/// </summary>
private void SelectItemFiltering(string query)
{
// if the user just typed one more character, don't filter all data but just filter what we are already displaying
var listToFilter = _currentList != null && !string.IsNullOrEmpty(_currentText) && !string.IsNullOrEmpty(query) &&
query.StartsWith(_currentText, StringComparison.Ordinal) ?
_currentList : _completionData;
var matchingItems =
from item in listToFilter
let quality = GetMatchQuality(item.Text, query)
where quality > 0
select new { Item = item, Quality = quality };
// e.g. "DateTimeKind k = (*cc here suggests DateTimeKind*)"
var suggestedItem = _listBox.SelectedIndex != -1 ? (ICompletionData)_listBox.SelectedItem : null;
var listBoxItems = new ObservableCollection<ICompletionData>();
var bestIndex = -1;
var bestQuality = -1;
double bestPriority = 0;
var i = 0;
foreach (var matchingItem in matchingItems)
{
var priority = matchingItem.Item == suggestedItem ? double.PositiveInfinity : matchingItem.Item.Priority;
var quality = matchingItem.Quality;
}
_currentList = listBoxItems;
_listBox.Items = null;
_listBox.Items = listBoxItems;
SelectIndexCentered(bestIndex);
}
i++;
}
_currentList = listBoxItems;
//_listBox.Items = null; Makes no sense? Tooltip disappeared because of this
_listBox.Items = listBoxItems;
SelectIndexCentered(bestIndex);
}
/// <summary>
/// Selects the item that starts with the specified query.
/// </summary>
private void SelectItemWithStart(string query)
{
if (string.IsNullOrEmpty(query))
return;
var suggestedIndex = _listBox.SelectedIndex;
var bestIndex = -1;
var bestQuality = -1;
double bestPriority = 0;
for (var i = 0; i < _completionData.Count; ++i)
{
var quality = GetMatchQuality(_completionData[i].Text, query);
if (quality < 0)
continue;
var priority = _completionData[i].Priority;
bool useThisItem;
if (bestQuality < quality)
{
useThisItem = true;
}
else
{
if (bestIndex == suggestedIndex)
{
useThisItem = false;
}
else if (i == suggestedIndex)
{
// prefer recommendedItem, regardless of its priority
useThisItem = bestQuality == quality;
}
else
{
useThisItem = bestQuality == quality && bestPriority < priority;
}
}
if (useThisItem)
{
bestIndex = i;
bestPriority = priority;
bestQuality = quality;
}
}
SelectIndexCentered(bestIndex);
}
private void SelectIndexCentered(int bestIndex)
{
if (bestIndex < 0)
{
_listBox.ClearSelection();
}
else
{
var firstItem = _listBox.FirstVisibleItem;
if (bestIndex < firstItem || firstItem + _listBox.VisibleItemCount <= bestIndex)
{
// CenterViewOn does nothing as CompletionListBox.ScrollViewer is null
_listBox.CenterViewOn(bestIndex);
_listBox.SelectIndex(bestIndex);
}
else
{
_listBox.SelectIndex(bestIndex);
}
}
}
private int GetMatchQuality(string itemText, string query)
{
if (itemText == null)
throw new ArgumentNullException(nameof(itemText), "ICompletionData.Text returned null");
// Qualities:
// 8 = full match case sensitive
// 7 = full match
// 6 = match start case sensitive
// 5 = match start
// 4 = match CamelCase when length of query is 1 or 2 characters
// 3 = match substring case sensitive
// 2 = match substring
// 1 = match CamelCase
// -1 = no match
if (query == itemText)
return 8;
if (string.Equals(itemText, query, StringComparison.CurrentCultureIgnoreCase))
return 7;
if (itemText.StartsWith(query, StringComparison.CurrentCulture))
return 6;
if (itemText.StartsWith(query, StringComparison.CurrentCultureIgnoreCase))
return 5;
bool? camelCaseMatch = null;
if (query.Length <= 2)
{
camelCaseMatch = CamelCaseMatch(itemText, query);
if (camelCaseMatch == true) return 4;
}
// search by substring, if filtering (i.e. new behavior) turned on
if (IsFiltering)
{
if (itemText.IndexOf(query, StringComparison.CurrentCulture) >= 0)
return 3;
if (itemText.IndexOf(query, StringComparison.CurrentCultureIgnoreCase) >= 0)
return 2;
}
if (!camelCaseMatch.HasValue)
camelCaseMatch = CamelCaseMatch(itemText, query);
if (camelCaseMatch == true)
return 1;
return -1;
}
private static bool CamelCaseMatch(string text, string query)
{
// We take the first letter of the text regardless of whether or not it's upper case so we match
// against camelCase text as well as PascalCase text ("cct" matches "camelCaseText")
var theFirstLetterOfEachWord = text.AsEnumerable()
.Take(1)
.Concat(text.AsEnumerable().Skip(1).Where(char.IsUpper));
var i = 0;
foreach (var letter in theFirstLetterOfEachWord)
{
if (i > query.Length - 1)
return true; // return true here for CamelCase partial match ("CQ" matches "CodeQualityAnalysis")
if (char.ToUpperInvariant(query[i]) != char.ToUpperInvariant(letter))
return false;
i++;
}
if (i >= query.Length)
return true;
return false;
}
}
}
<MSG> Fix tooltip disappearing
<DFF> @@ -285,7 +285,7 @@ namespace AvaloniaEdit.CodeCompletion
}
_currentList = listBoxItems;
- _listBox.Items = null;
+ //_listBox.Items = null; Makes no sense? Tooltip disappeared because of this
_listBox.Items = listBoxItems;
SelectIndexCentered(bestIndex);
}
| 1 | Fix tooltip disappearing | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057735 | <NME> CompletionList.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.Collections.ObjectModel;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml.Templates;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.CodeCompletion
{
/// <summary>
/// The listbox used inside the CompletionWindow, contains CompletionListBox.
/// </summary>
public class CompletionList : TemplatedControl
{
public CompletionList()
{
DoubleTapped += OnDoubleTapped;
}
/// <summary>
/// If true, the CompletionList is filtered to show only matching items. Also enables search by substring.
/// If false, enables the old behavior: no filtering, search by string.StartsWith.
/// </summary>
public bool IsFiltering { get; set; } = true;
/// <summary>
/// Dependency property for <see cref="EmptyTemplate" />.
/// </summary>
public static readonly StyledProperty<ControlTemplate> EmptyTemplateProperty =
AvaloniaProperty.Register<CompletionList, ControlTemplate>(nameof(EmptyTemplate));
/// <summary>
/// Content of EmptyTemplate will be shown when CompletionList contains no items.
/// If EmptyTemplate is null, nothing will be shown.
/// </summary>
public ControlTemplate EmptyTemplate
{
get => GetValue(EmptyTemplateProperty);
set => SetValue(EmptyTemplateProperty, value);
}
/// <summary>
/// Is raised when the completion list indicates that the user has chosen
/// an entry to be completed.
/// </summary>
public event EventHandler InsertionRequested;
/// <summary>
/// Raises the InsertionRequested event.
/// </summary>
public void RequestInsertion(EventArgs e)
{
InsertionRequested?.Invoke(this, e);
}
private CompletionListBox _listBox;
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
_listBox = e.NameScope.Find("PART_ListBox") as CompletionListBox;
if (_listBox != null)
{
_listBox.Items = _completionData;
}
}
/// <summary>
/// Gets the list box.
/// </summary>
public CompletionListBox ListBox
{
get
{
if (_listBox == null)
ApplyTemplate();
return _listBox;
}
}
/// <summary>
/// Gets the scroll viewer used in this list box.
/// </summary>
public ScrollViewer ScrollViewer => _listBox?.ScrollViewer;
private readonly ObservableCollection<ICompletionData> _completionData = new ObservableCollection<ICompletionData>();
/// <summary>
/// Gets the list to which completion data can be added.
/// </summary>
public IList<ICompletionData> CompletionData => _completionData;
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (!e.Handled)
{
HandleKey(e);
}
}
/// <summary>
/// Handles a key press. Used to let the completion list handle key presses while the
/// focus is still on the text editor.
/// </summary>
public void HandleKey(KeyEventArgs e)
{
if (_listBox == null)
return;
// We have to do some key handling manually, because the default doesn't work with
// our simulated events.
// Also, the default PageUp/PageDown implementation changes the focus, so we avoid it.
switch (e.Key)
{
case Key.Down:
e.Handled = true;
_listBox.SelectIndex(_listBox.SelectedIndex + 1);
break;
case Key.Up:
e.Handled = true;
_listBox.SelectIndex(_listBox.SelectedIndex - 1);
break;
case Key.PageDown:
e.Handled = true;
_listBox.SelectIndex(_listBox.SelectedIndex + _listBox.VisibleItemCount);
break;
case Key.PageUp:
e.Handled = true;
_listBox.SelectIndex(_listBox.SelectedIndex - _listBox.VisibleItemCount);
break;
case Key.Home:
e.Handled = true;
_listBox.SelectIndex(0);
break;
case Key.End:
e.Handled = true;
_listBox.SelectIndex(_listBox.ItemCount - 1);
break;
case Key.Tab:
case Key.Enter:
if(CurrentList.Count > 0)
{
e.Handled = true;
RequestInsertion(e);
}
break;
}
}
protected void OnDoubleTapped(object sender, RoutedEventArgs e)
{
//TODO TEST
if (((AvaloniaObject)e.Source).VisualAncestorsAndSelf()
.TakeWhile(obj => obj != this).Any(obj => obj is ListBoxItem))
{
e.Handled = true;
RequestInsertion(e);
}
}
/// <summary>
/// Gets/Sets the selected item.
/// </summary>
/// <remarks>
/// The setter of this property does not scroll to the selected item.
/// You might want to also call <see cref="ScrollIntoView"/>.
/// </remarks>
public ICompletionData SelectedItem
{
get => _listBox?.SelectedItem as ICompletionData;
set
{
if (_listBox == null && value != null)
ApplyTemplate();
if (_listBox != null) // may still be null if ApplyTemplate fails, or if listBox and value both are null
_listBox.SelectedItem = value;
}
}
/// <summary>
/// Scrolls the specified item into view.
/// </summary>
public void ScrollIntoView(ICompletionData item)
{
if (_listBox == null)
ApplyTemplate();
_listBox?.ScrollIntoView(item);
}
/// <summary>
/// Occurs when the SelectedItem property changes.
/// </summary>
public event EventHandler<SelectionChangedEventArgs> SelectionChanged
{
add => AddHandler(SelectingItemsControl.SelectionChangedEvent, value);
remove => RemoveHandler(SelectingItemsControl.SelectionChangedEvent, value);
}
// SelectItem gets called twice for every typed character (once from FormatLine), this helps execute SelectItem only once
private string _currentText;
private ObservableCollection<ICompletionData> _currentList;
public List<ICompletionData> CurrentList
{
get => ListBox.Items.Cast<ICompletionData>().ToList();
}
/// <summary>
/// Selects the best match, and filter the items if turned on using <see cref="IsFiltering" />.
/// </summary>
public void SelectItem(string text)
{
if (text == _currentText)
return;
if (_listBox == null)
ApplyTemplate();
if (IsFiltering)
{
SelectItemFiltering(text);
}
else
{
SelectItemWithStart(text);
}
_currentText = text;
}
/// <summary>
/// Filters CompletionList items to show only those matching given query, and selects the best match.
/// </summary>
private void SelectItemFiltering(string query)
{
// if the user just typed one more character, don't filter all data but just filter what we are already displaying
var listToFilter = _currentList != null && !string.IsNullOrEmpty(_currentText) && !string.IsNullOrEmpty(query) &&
query.StartsWith(_currentText, StringComparison.Ordinal) ?
_currentList : _completionData;
var matchingItems =
from item in listToFilter
let quality = GetMatchQuality(item.Text, query)
where quality > 0
select new { Item = item, Quality = quality };
// e.g. "DateTimeKind k = (*cc here suggests DateTimeKind*)"
var suggestedItem = _listBox.SelectedIndex != -1 ? (ICompletionData)_listBox.SelectedItem : null;
var listBoxItems = new ObservableCollection<ICompletionData>();
var bestIndex = -1;
var bestQuality = -1;
double bestPriority = 0;
var i = 0;
foreach (var matchingItem in matchingItems)
{
var priority = matchingItem.Item == suggestedItem ? double.PositiveInfinity : matchingItem.Item.Priority;
var quality = matchingItem.Quality;
}
_currentList = listBoxItems;
_listBox.Items = null;
_listBox.Items = listBoxItems;
SelectIndexCentered(bestIndex);
}
i++;
}
_currentList = listBoxItems;
//_listBox.Items = null; Makes no sense? Tooltip disappeared because of this
_listBox.Items = listBoxItems;
SelectIndexCentered(bestIndex);
}
/// <summary>
/// Selects the item that starts with the specified query.
/// </summary>
private void SelectItemWithStart(string query)
{
if (string.IsNullOrEmpty(query))
return;
var suggestedIndex = _listBox.SelectedIndex;
var bestIndex = -1;
var bestQuality = -1;
double bestPriority = 0;
for (var i = 0; i < _completionData.Count; ++i)
{
var quality = GetMatchQuality(_completionData[i].Text, query);
if (quality < 0)
continue;
var priority = _completionData[i].Priority;
bool useThisItem;
if (bestQuality < quality)
{
useThisItem = true;
}
else
{
if (bestIndex == suggestedIndex)
{
useThisItem = false;
}
else if (i == suggestedIndex)
{
// prefer recommendedItem, regardless of its priority
useThisItem = bestQuality == quality;
}
else
{
useThisItem = bestQuality == quality && bestPriority < priority;
}
}
if (useThisItem)
{
bestIndex = i;
bestPriority = priority;
bestQuality = quality;
}
}
SelectIndexCentered(bestIndex);
}
private void SelectIndexCentered(int bestIndex)
{
if (bestIndex < 0)
{
_listBox.ClearSelection();
}
else
{
var firstItem = _listBox.FirstVisibleItem;
if (bestIndex < firstItem || firstItem + _listBox.VisibleItemCount <= bestIndex)
{
// CenterViewOn does nothing as CompletionListBox.ScrollViewer is null
_listBox.CenterViewOn(bestIndex);
_listBox.SelectIndex(bestIndex);
}
else
{
_listBox.SelectIndex(bestIndex);
}
}
}
private int GetMatchQuality(string itemText, string query)
{
if (itemText == null)
throw new ArgumentNullException(nameof(itemText), "ICompletionData.Text returned null");
// Qualities:
// 8 = full match case sensitive
// 7 = full match
// 6 = match start case sensitive
// 5 = match start
// 4 = match CamelCase when length of query is 1 or 2 characters
// 3 = match substring case sensitive
// 2 = match substring
// 1 = match CamelCase
// -1 = no match
if (query == itemText)
return 8;
if (string.Equals(itemText, query, StringComparison.CurrentCultureIgnoreCase))
return 7;
if (itemText.StartsWith(query, StringComparison.CurrentCulture))
return 6;
if (itemText.StartsWith(query, StringComparison.CurrentCultureIgnoreCase))
return 5;
bool? camelCaseMatch = null;
if (query.Length <= 2)
{
camelCaseMatch = CamelCaseMatch(itemText, query);
if (camelCaseMatch == true) return 4;
}
// search by substring, if filtering (i.e. new behavior) turned on
if (IsFiltering)
{
if (itemText.IndexOf(query, StringComparison.CurrentCulture) >= 0)
return 3;
if (itemText.IndexOf(query, StringComparison.CurrentCultureIgnoreCase) >= 0)
return 2;
}
if (!camelCaseMatch.HasValue)
camelCaseMatch = CamelCaseMatch(itemText, query);
if (camelCaseMatch == true)
return 1;
return -1;
}
private static bool CamelCaseMatch(string text, string query)
{
// We take the first letter of the text regardless of whether or not it's upper case so we match
// against camelCase text as well as PascalCase text ("cct" matches "camelCaseText")
var theFirstLetterOfEachWord = text.AsEnumerable()
.Take(1)
.Concat(text.AsEnumerable().Skip(1).Where(char.IsUpper));
var i = 0;
foreach (var letter in theFirstLetterOfEachWord)
{
if (i > query.Length - 1)
return true; // return true here for CamelCase partial match ("CQ" matches "CodeQualityAnalysis")
if (char.ToUpperInvariant(query[i]) != char.ToUpperInvariant(letter))
return false;
i++;
}
if (i >= query.Length)
return true;
return false;
}
}
}
<MSG> Fix tooltip disappearing
<DFF> @@ -285,7 +285,7 @@ namespace AvaloniaEdit.CodeCompletion
}
_currentList = listBoxItems;
- _listBox.Items = null;
+ //_listBox.Items = null; Makes no sense? Tooltip disappeared because of this
_listBox.Items = listBoxItems;
SelectIndexCentered(bestIndex);
}
| 1 | Fix tooltip disappearing | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057736 | <NME> CompletionList.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.Collections.ObjectModel;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml.Templates;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.CodeCompletion
{
/// <summary>
/// The listbox used inside the CompletionWindow, contains CompletionListBox.
/// </summary>
public class CompletionList : TemplatedControl
{
public CompletionList()
{
DoubleTapped += OnDoubleTapped;
}
/// <summary>
/// If true, the CompletionList is filtered to show only matching items. Also enables search by substring.
/// If false, enables the old behavior: no filtering, search by string.StartsWith.
/// </summary>
public bool IsFiltering { get; set; } = true;
/// <summary>
/// Dependency property for <see cref="EmptyTemplate" />.
/// </summary>
public static readonly StyledProperty<ControlTemplate> EmptyTemplateProperty =
AvaloniaProperty.Register<CompletionList, ControlTemplate>(nameof(EmptyTemplate));
/// <summary>
/// Content of EmptyTemplate will be shown when CompletionList contains no items.
/// If EmptyTemplate is null, nothing will be shown.
/// </summary>
public ControlTemplate EmptyTemplate
{
get => GetValue(EmptyTemplateProperty);
set => SetValue(EmptyTemplateProperty, value);
}
/// <summary>
/// Is raised when the completion list indicates that the user has chosen
/// an entry to be completed.
/// </summary>
public event EventHandler InsertionRequested;
/// <summary>
/// Raises the InsertionRequested event.
/// </summary>
public void RequestInsertion(EventArgs e)
{
InsertionRequested?.Invoke(this, e);
}
private CompletionListBox _listBox;
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
_listBox = e.NameScope.Find("PART_ListBox") as CompletionListBox;
if (_listBox != null)
{
_listBox.Items = _completionData;
}
}
/// <summary>
/// Gets the list box.
/// </summary>
public CompletionListBox ListBox
{
get
{
if (_listBox == null)
ApplyTemplate();
return _listBox;
}
}
/// <summary>
/// Gets the scroll viewer used in this list box.
/// </summary>
public ScrollViewer ScrollViewer => _listBox?.ScrollViewer;
private readonly ObservableCollection<ICompletionData> _completionData = new ObservableCollection<ICompletionData>();
/// <summary>
/// Gets the list to which completion data can be added.
/// </summary>
public IList<ICompletionData> CompletionData => _completionData;
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (!e.Handled)
{
HandleKey(e);
}
}
/// <summary>
/// Handles a key press. Used to let the completion list handle key presses while the
/// focus is still on the text editor.
/// </summary>
public void HandleKey(KeyEventArgs e)
{
if (_listBox == null)
return;
// We have to do some key handling manually, because the default doesn't work with
// our simulated events.
// Also, the default PageUp/PageDown implementation changes the focus, so we avoid it.
switch (e.Key)
{
case Key.Down:
e.Handled = true;
_listBox.SelectIndex(_listBox.SelectedIndex + 1);
break;
case Key.Up:
e.Handled = true;
_listBox.SelectIndex(_listBox.SelectedIndex - 1);
break;
case Key.PageDown:
e.Handled = true;
_listBox.SelectIndex(_listBox.SelectedIndex + _listBox.VisibleItemCount);
break;
case Key.PageUp:
e.Handled = true;
_listBox.SelectIndex(_listBox.SelectedIndex - _listBox.VisibleItemCount);
break;
case Key.Home:
e.Handled = true;
_listBox.SelectIndex(0);
break;
case Key.End:
e.Handled = true;
_listBox.SelectIndex(_listBox.ItemCount - 1);
break;
case Key.Tab:
case Key.Enter:
if(CurrentList.Count > 0)
{
e.Handled = true;
RequestInsertion(e);
}
break;
}
}
protected void OnDoubleTapped(object sender, RoutedEventArgs e)
{
//TODO TEST
if (((AvaloniaObject)e.Source).VisualAncestorsAndSelf()
.TakeWhile(obj => obj != this).Any(obj => obj is ListBoxItem))
{
e.Handled = true;
RequestInsertion(e);
}
}
/// <summary>
/// Gets/Sets the selected item.
/// </summary>
/// <remarks>
/// The setter of this property does not scroll to the selected item.
/// You might want to also call <see cref="ScrollIntoView"/>.
/// </remarks>
public ICompletionData SelectedItem
{
get => _listBox?.SelectedItem as ICompletionData;
set
{
if (_listBox == null && value != null)
ApplyTemplate();
if (_listBox != null) // may still be null if ApplyTemplate fails, or if listBox and value both are null
_listBox.SelectedItem = value;
}
}
/// <summary>
/// Scrolls the specified item into view.
/// </summary>
public void ScrollIntoView(ICompletionData item)
{
if (_listBox == null)
ApplyTemplate();
_listBox?.ScrollIntoView(item);
}
/// <summary>
/// Occurs when the SelectedItem property changes.
/// </summary>
public event EventHandler<SelectionChangedEventArgs> SelectionChanged
{
add => AddHandler(SelectingItemsControl.SelectionChangedEvent, value);
remove => RemoveHandler(SelectingItemsControl.SelectionChangedEvent, value);
}
// SelectItem gets called twice for every typed character (once from FormatLine), this helps execute SelectItem only once
private string _currentText;
private ObservableCollection<ICompletionData> _currentList;
public List<ICompletionData> CurrentList
{
get => ListBox.Items.Cast<ICompletionData>().ToList();
}
/// <summary>
/// Selects the best match, and filter the items if turned on using <see cref="IsFiltering" />.
/// </summary>
public void SelectItem(string text)
{
if (text == _currentText)
return;
if (_listBox == null)
ApplyTemplate();
if (IsFiltering)
{
SelectItemFiltering(text);
}
else
{
SelectItemWithStart(text);
}
_currentText = text;
}
/// <summary>
/// Filters CompletionList items to show only those matching given query, and selects the best match.
/// </summary>
private void SelectItemFiltering(string query)
{
// if the user just typed one more character, don't filter all data but just filter what we are already displaying
var listToFilter = _currentList != null && !string.IsNullOrEmpty(_currentText) && !string.IsNullOrEmpty(query) &&
query.StartsWith(_currentText, StringComparison.Ordinal) ?
_currentList : _completionData;
var matchingItems =
from item in listToFilter
let quality = GetMatchQuality(item.Text, query)
where quality > 0
select new { Item = item, Quality = quality };
// e.g. "DateTimeKind k = (*cc here suggests DateTimeKind*)"
var suggestedItem = _listBox.SelectedIndex != -1 ? (ICompletionData)_listBox.SelectedItem : null;
var listBoxItems = new ObservableCollection<ICompletionData>();
var bestIndex = -1;
var bestQuality = -1;
double bestPriority = 0;
var i = 0;
foreach (var matchingItem in matchingItems)
{
var priority = matchingItem.Item == suggestedItem ? double.PositiveInfinity : matchingItem.Item.Priority;
var quality = matchingItem.Quality;
}
_currentList = listBoxItems;
_listBox.Items = null;
_listBox.Items = listBoxItems;
SelectIndexCentered(bestIndex);
}
i++;
}
_currentList = listBoxItems;
//_listBox.Items = null; Makes no sense? Tooltip disappeared because of this
_listBox.Items = listBoxItems;
SelectIndexCentered(bestIndex);
}
/// <summary>
/// Selects the item that starts with the specified query.
/// </summary>
private void SelectItemWithStart(string query)
{
if (string.IsNullOrEmpty(query))
return;
var suggestedIndex = _listBox.SelectedIndex;
var bestIndex = -1;
var bestQuality = -1;
double bestPriority = 0;
for (var i = 0; i < _completionData.Count; ++i)
{
var quality = GetMatchQuality(_completionData[i].Text, query);
if (quality < 0)
continue;
var priority = _completionData[i].Priority;
bool useThisItem;
if (bestQuality < quality)
{
useThisItem = true;
}
else
{
if (bestIndex == suggestedIndex)
{
useThisItem = false;
}
else if (i == suggestedIndex)
{
// prefer recommendedItem, regardless of its priority
useThisItem = bestQuality == quality;
}
else
{
useThisItem = bestQuality == quality && bestPriority < priority;
}
}
if (useThisItem)
{
bestIndex = i;
bestPriority = priority;
bestQuality = quality;
}
}
SelectIndexCentered(bestIndex);
}
private void SelectIndexCentered(int bestIndex)
{
if (bestIndex < 0)
{
_listBox.ClearSelection();
}
else
{
var firstItem = _listBox.FirstVisibleItem;
if (bestIndex < firstItem || firstItem + _listBox.VisibleItemCount <= bestIndex)
{
// CenterViewOn does nothing as CompletionListBox.ScrollViewer is null
_listBox.CenterViewOn(bestIndex);
_listBox.SelectIndex(bestIndex);
}
else
{
_listBox.SelectIndex(bestIndex);
}
}
}
private int GetMatchQuality(string itemText, string query)
{
if (itemText == null)
throw new ArgumentNullException(nameof(itemText), "ICompletionData.Text returned null");
// Qualities:
// 8 = full match case sensitive
// 7 = full match
// 6 = match start case sensitive
// 5 = match start
// 4 = match CamelCase when length of query is 1 or 2 characters
// 3 = match substring case sensitive
// 2 = match substring
// 1 = match CamelCase
// -1 = no match
if (query == itemText)
return 8;
if (string.Equals(itemText, query, StringComparison.CurrentCultureIgnoreCase))
return 7;
if (itemText.StartsWith(query, StringComparison.CurrentCulture))
return 6;
if (itemText.StartsWith(query, StringComparison.CurrentCultureIgnoreCase))
return 5;
bool? camelCaseMatch = null;
if (query.Length <= 2)
{
camelCaseMatch = CamelCaseMatch(itemText, query);
if (camelCaseMatch == true) return 4;
}
// search by substring, if filtering (i.e. new behavior) turned on
if (IsFiltering)
{
if (itemText.IndexOf(query, StringComparison.CurrentCulture) >= 0)
return 3;
if (itemText.IndexOf(query, StringComparison.CurrentCultureIgnoreCase) >= 0)
return 2;
}
if (!camelCaseMatch.HasValue)
camelCaseMatch = CamelCaseMatch(itemText, query);
if (camelCaseMatch == true)
return 1;
return -1;
}
private static bool CamelCaseMatch(string text, string query)
{
// We take the first letter of the text regardless of whether or not it's upper case so we match
// against camelCase text as well as PascalCase text ("cct" matches "camelCaseText")
var theFirstLetterOfEachWord = text.AsEnumerable()
.Take(1)
.Concat(text.AsEnumerable().Skip(1).Where(char.IsUpper));
var i = 0;
foreach (var letter in theFirstLetterOfEachWord)
{
if (i > query.Length - 1)
return true; // return true here for CamelCase partial match ("CQ" matches "CodeQualityAnalysis")
if (char.ToUpperInvariant(query[i]) != char.ToUpperInvariant(letter))
return false;
i++;
}
if (i >= query.Length)
return true;
return false;
}
}
}
<MSG> Fix tooltip disappearing
<DFF> @@ -285,7 +285,7 @@ namespace AvaloniaEdit.CodeCompletion
}
_currentList = listBoxItems;
- _listBox.Items = null;
+ //_listBox.Items = null; Makes no sense? Tooltip disappeared because of this
_listBox.Items = listBoxItems;
SelectIndexCentered(bestIndex);
}
| 1 | Fix tooltip disappearing | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057737 | <NME> CompletionList.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.Collections.ObjectModel;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml.Templates;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.CodeCompletion
{
/// <summary>
/// The listbox used inside the CompletionWindow, contains CompletionListBox.
/// </summary>
public class CompletionList : TemplatedControl
{
public CompletionList()
{
DoubleTapped += OnDoubleTapped;
}
/// <summary>
/// If true, the CompletionList is filtered to show only matching items. Also enables search by substring.
/// If false, enables the old behavior: no filtering, search by string.StartsWith.
/// </summary>
public bool IsFiltering { get; set; } = true;
/// <summary>
/// Dependency property for <see cref="EmptyTemplate" />.
/// </summary>
public static readonly StyledProperty<ControlTemplate> EmptyTemplateProperty =
AvaloniaProperty.Register<CompletionList, ControlTemplate>(nameof(EmptyTemplate));
/// <summary>
/// Content of EmptyTemplate will be shown when CompletionList contains no items.
/// If EmptyTemplate is null, nothing will be shown.
/// </summary>
public ControlTemplate EmptyTemplate
{
get => GetValue(EmptyTemplateProperty);
set => SetValue(EmptyTemplateProperty, value);
}
/// <summary>
/// Is raised when the completion list indicates that the user has chosen
/// an entry to be completed.
/// </summary>
public event EventHandler InsertionRequested;
/// <summary>
/// Raises the InsertionRequested event.
/// </summary>
public void RequestInsertion(EventArgs e)
{
InsertionRequested?.Invoke(this, e);
}
private CompletionListBox _listBox;
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
_listBox = e.NameScope.Find("PART_ListBox") as CompletionListBox;
if (_listBox != null)
{
_listBox.Items = _completionData;
}
}
/// <summary>
/// Gets the list box.
/// </summary>
public CompletionListBox ListBox
{
get
{
if (_listBox == null)
ApplyTemplate();
return _listBox;
}
}
/// <summary>
/// Gets the scroll viewer used in this list box.
/// </summary>
public ScrollViewer ScrollViewer => _listBox?.ScrollViewer;
private readonly ObservableCollection<ICompletionData> _completionData = new ObservableCollection<ICompletionData>();
/// <summary>
/// Gets the list to which completion data can be added.
/// </summary>
public IList<ICompletionData> CompletionData => _completionData;
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (!e.Handled)
{
HandleKey(e);
}
}
/// <summary>
/// Handles a key press. Used to let the completion list handle key presses while the
/// focus is still on the text editor.
/// </summary>
public void HandleKey(KeyEventArgs e)
{
if (_listBox == null)
return;
// We have to do some key handling manually, because the default doesn't work with
// our simulated events.
// Also, the default PageUp/PageDown implementation changes the focus, so we avoid it.
switch (e.Key)
{
case Key.Down:
e.Handled = true;
_listBox.SelectIndex(_listBox.SelectedIndex + 1);
break;
case Key.Up:
e.Handled = true;
_listBox.SelectIndex(_listBox.SelectedIndex - 1);
break;
case Key.PageDown:
e.Handled = true;
_listBox.SelectIndex(_listBox.SelectedIndex + _listBox.VisibleItemCount);
break;
case Key.PageUp:
e.Handled = true;
_listBox.SelectIndex(_listBox.SelectedIndex - _listBox.VisibleItemCount);
break;
case Key.Home:
e.Handled = true;
_listBox.SelectIndex(0);
break;
case Key.End:
e.Handled = true;
_listBox.SelectIndex(_listBox.ItemCount - 1);
break;
case Key.Tab:
case Key.Enter:
if(CurrentList.Count > 0)
{
e.Handled = true;
RequestInsertion(e);
}
break;
}
}
protected void OnDoubleTapped(object sender, RoutedEventArgs e)
{
//TODO TEST
if (((AvaloniaObject)e.Source).VisualAncestorsAndSelf()
.TakeWhile(obj => obj != this).Any(obj => obj is ListBoxItem))
{
e.Handled = true;
RequestInsertion(e);
}
}
/// <summary>
/// Gets/Sets the selected item.
/// </summary>
/// <remarks>
/// The setter of this property does not scroll to the selected item.
/// You might want to also call <see cref="ScrollIntoView"/>.
/// </remarks>
public ICompletionData SelectedItem
{
get => _listBox?.SelectedItem as ICompletionData;
set
{
if (_listBox == null && value != null)
ApplyTemplate();
if (_listBox != null) // may still be null if ApplyTemplate fails, or if listBox and value both are null
_listBox.SelectedItem = value;
}
}
/// <summary>
/// Scrolls the specified item into view.
/// </summary>
public void ScrollIntoView(ICompletionData item)
{
if (_listBox == null)
ApplyTemplate();
_listBox?.ScrollIntoView(item);
}
/// <summary>
/// Occurs when the SelectedItem property changes.
/// </summary>
public event EventHandler<SelectionChangedEventArgs> SelectionChanged
{
add => AddHandler(SelectingItemsControl.SelectionChangedEvent, value);
remove => RemoveHandler(SelectingItemsControl.SelectionChangedEvent, value);
}
// SelectItem gets called twice for every typed character (once from FormatLine), this helps execute SelectItem only once
private string _currentText;
private ObservableCollection<ICompletionData> _currentList;
public List<ICompletionData> CurrentList
{
get => ListBox.Items.Cast<ICompletionData>().ToList();
}
/// <summary>
/// Selects the best match, and filter the items if turned on using <see cref="IsFiltering" />.
/// </summary>
public void SelectItem(string text)
{
if (text == _currentText)
return;
if (_listBox == null)
ApplyTemplate();
if (IsFiltering)
{
SelectItemFiltering(text);
}
else
{
SelectItemWithStart(text);
}
_currentText = text;
}
/// <summary>
/// Filters CompletionList items to show only those matching given query, and selects the best match.
/// </summary>
private void SelectItemFiltering(string query)
{
// if the user just typed one more character, don't filter all data but just filter what we are already displaying
var listToFilter = _currentList != null && !string.IsNullOrEmpty(_currentText) && !string.IsNullOrEmpty(query) &&
query.StartsWith(_currentText, StringComparison.Ordinal) ?
_currentList : _completionData;
var matchingItems =
from item in listToFilter
let quality = GetMatchQuality(item.Text, query)
where quality > 0
select new { Item = item, Quality = quality };
// e.g. "DateTimeKind k = (*cc here suggests DateTimeKind*)"
var suggestedItem = _listBox.SelectedIndex != -1 ? (ICompletionData)_listBox.SelectedItem : null;
var listBoxItems = new ObservableCollection<ICompletionData>();
var bestIndex = -1;
var bestQuality = -1;
double bestPriority = 0;
var i = 0;
foreach (var matchingItem in matchingItems)
{
var priority = matchingItem.Item == suggestedItem ? double.PositiveInfinity : matchingItem.Item.Priority;
var quality = matchingItem.Quality;
}
_currentList = listBoxItems;
_listBox.Items = null;
_listBox.Items = listBoxItems;
SelectIndexCentered(bestIndex);
}
i++;
}
_currentList = listBoxItems;
//_listBox.Items = null; Makes no sense? Tooltip disappeared because of this
_listBox.Items = listBoxItems;
SelectIndexCentered(bestIndex);
}
/// <summary>
/// Selects the item that starts with the specified query.
/// </summary>
private void SelectItemWithStart(string query)
{
if (string.IsNullOrEmpty(query))
return;
var suggestedIndex = _listBox.SelectedIndex;
var bestIndex = -1;
var bestQuality = -1;
double bestPriority = 0;
for (var i = 0; i < _completionData.Count; ++i)
{
var quality = GetMatchQuality(_completionData[i].Text, query);
if (quality < 0)
continue;
var priority = _completionData[i].Priority;
bool useThisItem;
if (bestQuality < quality)
{
useThisItem = true;
}
else
{
if (bestIndex == suggestedIndex)
{
useThisItem = false;
}
else if (i == suggestedIndex)
{
// prefer recommendedItem, regardless of its priority
useThisItem = bestQuality == quality;
}
else
{
useThisItem = bestQuality == quality && bestPriority < priority;
}
}
if (useThisItem)
{
bestIndex = i;
bestPriority = priority;
bestQuality = quality;
}
}
SelectIndexCentered(bestIndex);
}
private void SelectIndexCentered(int bestIndex)
{
if (bestIndex < 0)
{
_listBox.ClearSelection();
}
else
{
var firstItem = _listBox.FirstVisibleItem;
if (bestIndex < firstItem || firstItem + _listBox.VisibleItemCount <= bestIndex)
{
// CenterViewOn does nothing as CompletionListBox.ScrollViewer is null
_listBox.CenterViewOn(bestIndex);
_listBox.SelectIndex(bestIndex);
}
else
{
_listBox.SelectIndex(bestIndex);
}
}
}
private int GetMatchQuality(string itemText, string query)
{
if (itemText == null)
throw new ArgumentNullException(nameof(itemText), "ICompletionData.Text returned null");
// Qualities:
// 8 = full match case sensitive
// 7 = full match
// 6 = match start case sensitive
// 5 = match start
// 4 = match CamelCase when length of query is 1 or 2 characters
// 3 = match substring case sensitive
// 2 = match substring
// 1 = match CamelCase
// -1 = no match
if (query == itemText)
return 8;
if (string.Equals(itemText, query, StringComparison.CurrentCultureIgnoreCase))
return 7;
if (itemText.StartsWith(query, StringComparison.CurrentCulture))
return 6;
if (itemText.StartsWith(query, StringComparison.CurrentCultureIgnoreCase))
return 5;
bool? camelCaseMatch = null;
if (query.Length <= 2)
{
camelCaseMatch = CamelCaseMatch(itemText, query);
if (camelCaseMatch == true) return 4;
}
// search by substring, if filtering (i.e. new behavior) turned on
if (IsFiltering)
{
if (itemText.IndexOf(query, StringComparison.CurrentCulture) >= 0)
return 3;
if (itemText.IndexOf(query, StringComparison.CurrentCultureIgnoreCase) >= 0)
return 2;
}
if (!camelCaseMatch.HasValue)
camelCaseMatch = CamelCaseMatch(itemText, query);
if (camelCaseMatch == true)
return 1;
return -1;
}
private static bool CamelCaseMatch(string text, string query)
{
// We take the first letter of the text regardless of whether or not it's upper case so we match
// against camelCase text as well as PascalCase text ("cct" matches "camelCaseText")
var theFirstLetterOfEachWord = text.AsEnumerable()
.Take(1)
.Concat(text.AsEnumerable().Skip(1).Where(char.IsUpper));
var i = 0;
foreach (var letter in theFirstLetterOfEachWord)
{
if (i > query.Length - 1)
return true; // return true here for CamelCase partial match ("CQ" matches "CodeQualityAnalysis")
if (char.ToUpperInvariant(query[i]) != char.ToUpperInvariant(letter))
return false;
i++;
}
if (i >= query.Length)
return true;
return false;
}
}
}
<MSG> Fix tooltip disappearing
<DFF> @@ -285,7 +285,7 @@ namespace AvaloniaEdit.CodeCompletion
}
_currentList = listBoxItems;
- _listBox.Items = null;
+ //_listBox.Items = null; Makes no sense? Tooltip disappeared because of this
_listBox.Items = listBoxItems;
SelectIndexCentered(bestIndex);
}
| 1 | Fix tooltip disappearing | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057738 | <NME> CompletionList.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.Collections.ObjectModel;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml.Templates;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.CodeCompletion
{
/// <summary>
/// The listbox used inside the CompletionWindow, contains CompletionListBox.
/// </summary>
public class CompletionList : TemplatedControl
{
public CompletionList()
{
DoubleTapped += OnDoubleTapped;
}
/// <summary>
/// If true, the CompletionList is filtered to show only matching items. Also enables search by substring.
/// If false, enables the old behavior: no filtering, search by string.StartsWith.
/// </summary>
public bool IsFiltering { get; set; } = true;
/// <summary>
/// Dependency property for <see cref="EmptyTemplate" />.
/// </summary>
public static readonly StyledProperty<ControlTemplate> EmptyTemplateProperty =
AvaloniaProperty.Register<CompletionList, ControlTemplate>(nameof(EmptyTemplate));
/// <summary>
/// Content of EmptyTemplate will be shown when CompletionList contains no items.
/// If EmptyTemplate is null, nothing will be shown.
/// </summary>
public ControlTemplate EmptyTemplate
{
get => GetValue(EmptyTemplateProperty);
set => SetValue(EmptyTemplateProperty, value);
}
/// <summary>
/// Is raised when the completion list indicates that the user has chosen
/// an entry to be completed.
/// </summary>
public event EventHandler InsertionRequested;
/// <summary>
/// Raises the InsertionRequested event.
/// </summary>
public void RequestInsertion(EventArgs e)
{
InsertionRequested?.Invoke(this, e);
}
private CompletionListBox _listBox;
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
_listBox = e.NameScope.Find("PART_ListBox") as CompletionListBox;
if (_listBox != null)
{
_listBox.Items = _completionData;
}
}
/// <summary>
/// Gets the list box.
/// </summary>
public CompletionListBox ListBox
{
get
{
if (_listBox == null)
ApplyTemplate();
return _listBox;
}
}
/// <summary>
/// Gets the scroll viewer used in this list box.
/// </summary>
public ScrollViewer ScrollViewer => _listBox?.ScrollViewer;
private readonly ObservableCollection<ICompletionData> _completionData = new ObservableCollection<ICompletionData>();
/// <summary>
/// Gets the list to which completion data can be added.
/// </summary>
public IList<ICompletionData> CompletionData => _completionData;
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (!e.Handled)
{
HandleKey(e);
}
}
/// <summary>
/// Handles a key press. Used to let the completion list handle key presses while the
/// focus is still on the text editor.
/// </summary>
public void HandleKey(KeyEventArgs e)
{
if (_listBox == null)
return;
// We have to do some key handling manually, because the default doesn't work with
// our simulated events.
// Also, the default PageUp/PageDown implementation changes the focus, so we avoid it.
switch (e.Key)
{
case Key.Down:
e.Handled = true;
_listBox.SelectIndex(_listBox.SelectedIndex + 1);
break;
case Key.Up:
e.Handled = true;
_listBox.SelectIndex(_listBox.SelectedIndex - 1);
break;
case Key.PageDown:
e.Handled = true;
_listBox.SelectIndex(_listBox.SelectedIndex + _listBox.VisibleItemCount);
break;
case Key.PageUp:
e.Handled = true;
_listBox.SelectIndex(_listBox.SelectedIndex - _listBox.VisibleItemCount);
break;
case Key.Home:
e.Handled = true;
_listBox.SelectIndex(0);
break;
case Key.End:
e.Handled = true;
_listBox.SelectIndex(_listBox.ItemCount - 1);
break;
case Key.Tab:
case Key.Enter:
if(CurrentList.Count > 0)
{
e.Handled = true;
RequestInsertion(e);
}
break;
}
}
protected void OnDoubleTapped(object sender, RoutedEventArgs e)
{
//TODO TEST
if (((AvaloniaObject)e.Source).VisualAncestorsAndSelf()
.TakeWhile(obj => obj != this).Any(obj => obj is ListBoxItem))
{
e.Handled = true;
RequestInsertion(e);
}
}
/// <summary>
/// Gets/Sets the selected item.
/// </summary>
/// <remarks>
/// The setter of this property does not scroll to the selected item.
/// You might want to also call <see cref="ScrollIntoView"/>.
/// </remarks>
public ICompletionData SelectedItem
{
get => _listBox?.SelectedItem as ICompletionData;
set
{
if (_listBox == null && value != null)
ApplyTemplate();
if (_listBox != null) // may still be null if ApplyTemplate fails, or if listBox and value both are null
_listBox.SelectedItem = value;
}
}
/// <summary>
/// Scrolls the specified item into view.
/// </summary>
public void ScrollIntoView(ICompletionData item)
{
if (_listBox == null)
ApplyTemplate();
_listBox?.ScrollIntoView(item);
}
/// <summary>
/// Occurs when the SelectedItem property changes.
/// </summary>
public event EventHandler<SelectionChangedEventArgs> SelectionChanged
{
add => AddHandler(SelectingItemsControl.SelectionChangedEvent, value);
remove => RemoveHandler(SelectingItemsControl.SelectionChangedEvent, value);
}
// SelectItem gets called twice for every typed character (once from FormatLine), this helps execute SelectItem only once
private string _currentText;
private ObservableCollection<ICompletionData> _currentList;
public List<ICompletionData> CurrentList
{
get => ListBox.Items.Cast<ICompletionData>().ToList();
}
/// <summary>
/// Selects the best match, and filter the items if turned on using <see cref="IsFiltering" />.
/// </summary>
public void SelectItem(string text)
{
if (text == _currentText)
return;
if (_listBox == null)
ApplyTemplate();
if (IsFiltering)
{
SelectItemFiltering(text);
}
else
{
SelectItemWithStart(text);
}
_currentText = text;
}
/// <summary>
/// Filters CompletionList items to show only those matching given query, and selects the best match.
/// </summary>
private void SelectItemFiltering(string query)
{
// if the user just typed one more character, don't filter all data but just filter what we are already displaying
var listToFilter = _currentList != null && !string.IsNullOrEmpty(_currentText) && !string.IsNullOrEmpty(query) &&
query.StartsWith(_currentText, StringComparison.Ordinal) ?
_currentList : _completionData;
var matchingItems =
from item in listToFilter
let quality = GetMatchQuality(item.Text, query)
where quality > 0
select new { Item = item, Quality = quality };
// e.g. "DateTimeKind k = (*cc here suggests DateTimeKind*)"
var suggestedItem = _listBox.SelectedIndex != -1 ? (ICompletionData)_listBox.SelectedItem : null;
var listBoxItems = new ObservableCollection<ICompletionData>();
var bestIndex = -1;
var bestQuality = -1;
double bestPriority = 0;
var i = 0;
foreach (var matchingItem in matchingItems)
{
var priority = matchingItem.Item == suggestedItem ? double.PositiveInfinity : matchingItem.Item.Priority;
var quality = matchingItem.Quality;
}
_currentList = listBoxItems;
_listBox.Items = null;
_listBox.Items = listBoxItems;
SelectIndexCentered(bestIndex);
}
i++;
}
_currentList = listBoxItems;
//_listBox.Items = null; Makes no sense? Tooltip disappeared because of this
_listBox.Items = listBoxItems;
SelectIndexCentered(bestIndex);
}
/// <summary>
/// Selects the item that starts with the specified query.
/// </summary>
private void SelectItemWithStart(string query)
{
if (string.IsNullOrEmpty(query))
return;
var suggestedIndex = _listBox.SelectedIndex;
var bestIndex = -1;
var bestQuality = -1;
double bestPriority = 0;
for (var i = 0; i < _completionData.Count; ++i)
{
var quality = GetMatchQuality(_completionData[i].Text, query);
if (quality < 0)
continue;
var priority = _completionData[i].Priority;
bool useThisItem;
if (bestQuality < quality)
{
useThisItem = true;
}
else
{
if (bestIndex == suggestedIndex)
{
useThisItem = false;
}
else if (i == suggestedIndex)
{
// prefer recommendedItem, regardless of its priority
useThisItem = bestQuality == quality;
}
else
{
useThisItem = bestQuality == quality && bestPriority < priority;
}
}
if (useThisItem)
{
bestIndex = i;
bestPriority = priority;
bestQuality = quality;
}
}
SelectIndexCentered(bestIndex);
}
private void SelectIndexCentered(int bestIndex)
{
if (bestIndex < 0)
{
_listBox.ClearSelection();
}
else
{
var firstItem = _listBox.FirstVisibleItem;
if (bestIndex < firstItem || firstItem + _listBox.VisibleItemCount <= bestIndex)
{
// CenterViewOn does nothing as CompletionListBox.ScrollViewer is null
_listBox.CenterViewOn(bestIndex);
_listBox.SelectIndex(bestIndex);
}
else
{
_listBox.SelectIndex(bestIndex);
}
}
}
private int GetMatchQuality(string itemText, string query)
{
if (itemText == null)
throw new ArgumentNullException(nameof(itemText), "ICompletionData.Text returned null");
// Qualities:
// 8 = full match case sensitive
// 7 = full match
// 6 = match start case sensitive
// 5 = match start
// 4 = match CamelCase when length of query is 1 or 2 characters
// 3 = match substring case sensitive
// 2 = match substring
// 1 = match CamelCase
// -1 = no match
if (query == itemText)
return 8;
if (string.Equals(itemText, query, StringComparison.CurrentCultureIgnoreCase))
return 7;
if (itemText.StartsWith(query, StringComparison.CurrentCulture))
return 6;
if (itemText.StartsWith(query, StringComparison.CurrentCultureIgnoreCase))
return 5;
bool? camelCaseMatch = null;
if (query.Length <= 2)
{
camelCaseMatch = CamelCaseMatch(itemText, query);
if (camelCaseMatch == true) return 4;
}
// search by substring, if filtering (i.e. new behavior) turned on
if (IsFiltering)
{
if (itemText.IndexOf(query, StringComparison.CurrentCulture) >= 0)
return 3;
if (itemText.IndexOf(query, StringComparison.CurrentCultureIgnoreCase) >= 0)
return 2;
}
if (!camelCaseMatch.HasValue)
camelCaseMatch = CamelCaseMatch(itemText, query);
if (camelCaseMatch == true)
return 1;
return -1;
}
private static bool CamelCaseMatch(string text, string query)
{
// We take the first letter of the text regardless of whether or not it's upper case so we match
// against camelCase text as well as PascalCase text ("cct" matches "camelCaseText")
var theFirstLetterOfEachWord = text.AsEnumerable()
.Take(1)
.Concat(text.AsEnumerable().Skip(1).Where(char.IsUpper));
var i = 0;
foreach (var letter in theFirstLetterOfEachWord)
{
if (i > query.Length - 1)
return true; // return true here for CamelCase partial match ("CQ" matches "CodeQualityAnalysis")
if (char.ToUpperInvariant(query[i]) != char.ToUpperInvariant(letter))
return false;
i++;
}
if (i >= query.Length)
return true;
return false;
}
}
}
<MSG> Fix tooltip disappearing
<DFF> @@ -285,7 +285,7 @@ namespace AvaloniaEdit.CodeCompletion
}
_currentList = listBoxItems;
- _listBox.Items = null;
+ //_listBox.Items = null; Makes no sense? Tooltip disappeared because of this
_listBox.Items = listBoxItems;
SelectIndexCentered(bestIndex);
}
| 1 | Fix tooltip disappearing | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057739 | <NME> TextEditor.xaml
<BEF> <Styles xmlns="https://github.com/avaloniaui"
xmlns:AvalonEdit="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:Editing="clr-namespace:AvaloniaEdit.Editing;assembly=AvaloniaEdit">
<Style Selector="AvalonEdit|TextEditor">
<Setter Property="Template">
<ControlTemplate>
<Border BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<ScrollViewer Focusable="False"
Name="PART_ScrollViewer"
VerticalScrollBarVisibility="{TemplateBinding VerticalScrollBarVisibility}"
HorizontalScrollBarVisibility="{TemplateBinding HorizontalScrollBarVisibility}"
VerticalContentAlignment="Top"
HorizontalContentAlignment="Left"
Padding="{TemplateBinding Padding}" />
</Border>
</ControlTemplate>
</Setter>
</Style>
</Styles>
<MSG> Fix background color in template
<DFF> @@ -4,7 +4,8 @@
<Style Selector="AvalonEdit|TextEditor">
<Setter Property="Template">
<ControlTemplate>
- <Border BorderBrush="{TemplateBinding BorderBrush}"
+ <Border Background="{TemplateBinding Background}"
+ BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<ScrollViewer Focusable="False"
Name="PART_ScrollViewer"
| 2 | Fix background color in template | 1 | .xaml | xaml | mit | AvaloniaUI/AvaloniaEdit |
10057740 | <NME> TextEditor.xaml
<BEF> <Styles xmlns="https://github.com/avaloniaui"
xmlns:AvalonEdit="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:Editing="clr-namespace:AvaloniaEdit.Editing;assembly=AvaloniaEdit">
<Style Selector="AvalonEdit|TextEditor">
<Setter Property="Template">
<ControlTemplate>
<Border BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<ScrollViewer Focusable="False"
Name="PART_ScrollViewer"
VerticalScrollBarVisibility="{TemplateBinding VerticalScrollBarVisibility}"
HorizontalScrollBarVisibility="{TemplateBinding HorizontalScrollBarVisibility}"
VerticalContentAlignment="Top"
HorizontalContentAlignment="Left"
Padding="{TemplateBinding Padding}" />
</Border>
</ControlTemplate>
</Setter>
</Style>
</Styles>
<MSG> Fix background color in template
<DFF> @@ -4,7 +4,8 @@
<Style Selector="AvalonEdit|TextEditor">
<Setter Property="Template">
<ControlTemplate>
- <Border BorderBrush="{TemplateBinding BorderBrush}"
+ <Border Background="{TemplateBinding Background}"
+ BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<ScrollViewer Focusable="False"
Name="PART_ScrollViewer"
| 2 | Fix background color in template | 1 | .xaml | xaml | mit | AvaloniaUI/AvaloniaEdit |
10057741 | <NME> TextEditor.xaml
<BEF> <Styles xmlns="https://github.com/avaloniaui"
xmlns:AvalonEdit="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:Editing="clr-namespace:AvaloniaEdit.Editing;assembly=AvaloniaEdit">
<Style Selector="AvalonEdit|TextEditor">
<Setter Property="Template">
<ControlTemplate>
<Border BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<ScrollViewer Focusable="False"
Name="PART_ScrollViewer"
VerticalScrollBarVisibility="{TemplateBinding VerticalScrollBarVisibility}"
HorizontalScrollBarVisibility="{TemplateBinding HorizontalScrollBarVisibility}"
VerticalContentAlignment="Top"
HorizontalContentAlignment="Left"
Padding="{TemplateBinding Padding}" />
</Border>
</ControlTemplate>
</Setter>
</Style>
</Styles>
<MSG> Fix background color in template
<DFF> @@ -4,7 +4,8 @@
<Style Selector="AvalonEdit|TextEditor">
<Setter Property="Template">
<ControlTemplate>
- <Border BorderBrush="{TemplateBinding BorderBrush}"
+ <Border Background="{TemplateBinding Background}"
+ BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<ScrollViewer Focusable="False"
Name="PART_ScrollViewer"
| 2 | Fix background color in template | 1 | .xaml | xaml | mit | AvaloniaUI/AvaloniaEdit |
10057742 | <NME> TextEditor.xaml
<BEF> <Styles xmlns="https://github.com/avaloniaui"
xmlns:AvalonEdit="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:Editing="clr-namespace:AvaloniaEdit.Editing;assembly=AvaloniaEdit">
<Style Selector="AvalonEdit|TextEditor">
<Setter Property="Template">
<ControlTemplate>
<Border BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<ScrollViewer Focusable="False"
Name="PART_ScrollViewer"
VerticalScrollBarVisibility="{TemplateBinding VerticalScrollBarVisibility}"
HorizontalScrollBarVisibility="{TemplateBinding HorizontalScrollBarVisibility}"
VerticalContentAlignment="Top"
HorizontalContentAlignment="Left"
Padding="{TemplateBinding Padding}" />
</Border>
</ControlTemplate>
</Setter>
</Style>
</Styles>
<MSG> Fix background color in template
<DFF> @@ -4,7 +4,8 @@
<Style Selector="AvalonEdit|TextEditor">
<Setter Property="Template">
<ControlTemplate>
- <Border BorderBrush="{TemplateBinding BorderBrush}"
+ <Border Background="{TemplateBinding Background}"
+ BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<ScrollViewer Focusable="False"
Name="PART_ScrollViewer"
| 2 | Fix background color in template | 1 | .xaml | xaml | mit | AvaloniaUI/AvaloniaEdit |
10057743 | <NME> TextEditor.xaml
<BEF> <Styles xmlns="https://github.com/avaloniaui"
xmlns:AvalonEdit="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:Editing="clr-namespace:AvaloniaEdit.Editing;assembly=AvaloniaEdit">
<Style Selector="AvalonEdit|TextEditor">
<Setter Property="Template">
<ControlTemplate>
<Border BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<ScrollViewer Focusable="False"
Name="PART_ScrollViewer"
VerticalScrollBarVisibility="{TemplateBinding VerticalScrollBarVisibility}"
HorizontalScrollBarVisibility="{TemplateBinding HorizontalScrollBarVisibility}"
VerticalContentAlignment="Top"
HorizontalContentAlignment="Left"
Padding="{TemplateBinding Padding}" />
</Border>
</ControlTemplate>
</Setter>
</Style>
</Styles>
<MSG> Fix background color in template
<DFF> @@ -4,7 +4,8 @@
<Style Selector="AvalonEdit|TextEditor">
<Setter Property="Template">
<ControlTemplate>
- <Border BorderBrush="{TemplateBinding BorderBrush}"
+ <Border Background="{TemplateBinding Background}"
+ BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<ScrollViewer Focusable="False"
Name="PART_ScrollViewer"
| 2 | Fix background color in template | 1 | .xaml | xaml | mit | AvaloniaUI/AvaloniaEdit |
10057744 | <NME> TextEditor.xaml
<BEF> <Styles xmlns="https://github.com/avaloniaui"
xmlns:AvalonEdit="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:Editing="clr-namespace:AvaloniaEdit.Editing;assembly=AvaloniaEdit">
<Style Selector="AvalonEdit|TextEditor">
<Setter Property="Template">
<ControlTemplate>
<Border BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<ScrollViewer Focusable="False"
Name="PART_ScrollViewer"
VerticalScrollBarVisibility="{TemplateBinding VerticalScrollBarVisibility}"
HorizontalScrollBarVisibility="{TemplateBinding HorizontalScrollBarVisibility}"
VerticalContentAlignment="Top"
HorizontalContentAlignment="Left"
Padding="{TemplateBinding Padding}" />
</Border>
</ControlTemplate>
</Setter>
</Style>
</Styles>
<MSG> Fix background color in template
<DFF> @@ -4,7 +4,8 @@
<Style Selector="AvalonEdit|TextEditor">
<Setter Property="Template">
<ControlTemplate>
- <Border BorderBrush="{TemplateBinding BorderBrush}"
+ <Border Background="{TemplateBinding Background}"
+ BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<ScrollViewer Focusable="False"
Name="PART_ScrollViewer"
| 2 | Fix background color in template | 1 | .xaml | xaml | mit | AvaloniaUI/AvaloniaEdit |
10057745 | <NME> TextEditor.xaml
<BEF> <Styles xmlns="https://github.com/avaloniaui"
xmlns:AvalonEdit="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:Editing="clr-namespace:AvaloniaEdit.Editing;assembly=AvaloniaEdit">
<Style Selector="AvalonEdit|TextEditor">
<Setter Property="Template">
<ControlTemplate>
<Border BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<ScrollViewer Focusable="False"
Name="PART_ScrollViewer"
VerticalScrollBarVisibility="{TemplateBinding VerticalScrollBarVisibility}"
HorizontalScrollBarVisibility="{TemplateBinding HorizontalScrollBarVisibility}"
VerticalContentAlignment="Top"
HorizontalContentAlignment="Left"
Padding="{TemplateBinding Padding}" />
</Border>
</ControlTemplate>
</Setter>
</Style>
</Styles>
<MSG> Fix background color in template
<DFF> @@ -4,7 +4,8 @@
<Style Selector="AvalonEdit|TextEditor">
<Setter Property="Template">
<ControlTemplate>
- <Border BorderBrush="{TemplateBinding BorderBrush}"
+ <Border Background="{TemplateBinding Background}"
+ BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<ScrollViewer Focusable="False"
Name="PART_ScrollViewer"
| 2 | Fix background color in template | 1 | .xaml | xaml | mit | AvaloniaUI/AvaloniaEdit |
10057746 | <NME> TextEditor.xaml
<BEF> <Styles xmlns="https://github.com/avaloniaui"
xmlns:AvalonEdit="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:Editing="clr-namespace:AvaloniaEdit.Editing;assembly=AvaloniaEdit">
<Style Selector="AvalonEdit|TextEditor">
<Setter Property="Template">
<ControlTemplate>
<Border BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<ScrollViewer Focusable="False"
Name="PART_ScrollViewer"
VerticalScrollBarVisibility="{TemplateBinding VerticalScrollBarVisibility}"
HorizontalScrollBarVisibility="{TemplateBinding HorizontalScrollBarVisibility}"
VerticalContentAlignment="Top"
HorizontalContentAlignment="Left"
Padding="{TemplateBinding Padding}" />
</Border>
</ControlTemplate>
</Setter>
</Style>
</Styles>
<MSG> Fix background color in template
<DFF> @@ -4,7 +4,8 @@
<Style Selector="AvalonEdit|TextEditor">
<Setter Property="Template">
<ControlTemplate>
- <Border BorderBrush="{TemplateBinding BorderBrush}"
+ <Border Background="{TemplateBinding Background}"
+ BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<ScrollViewer Focusable="False"
Name="PART_ScrollViewer"
| 2 | Fix background color in template | 1 | .xaml | xaml | mit | AvaloniaUI/AvaloniaEdit |
10057747 | <NME> TextEditor.xaml
<BEF> <Styles xmlns="https://github.com/avaloniaui"
xmlns:AvalonEdit="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:Editing="clr-namespace:AvaloniaEdit.Editing;assembly=AvaloniaEdit">
<Style Selector="AvalonEdit|TextEditor">
<Setter Property="Template">
<ControlTemplate>
<Border BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<ScrollViewer Focusable="False"
Name="PART_ScrollViewer"
VerticalScrollBarVisibility="{TemplateBinding VerticalScrollBarVisibility}"
HorizontalScrollBarVisibility="{TemplateBinding HorizontalScrollBarVisibility}"
VerticalContentAlignment="Top"
HorizontalContentAlignment="Left"
Padding="{TemplateBinding Padding}" />
</Border>
</ControlTemplate>
</Setter>
</Style>
</Styles>
<MSG> Fix background color in template
<DFF> @@ -4,7 +4,8 @@
<Style Selector="AvalonEdit|TextEditor">
<Setter Property="Template">
<ControlTemplate>
- <Border BorderBrush="{TemplateBinding BorderBrush}"
+ <Border Background="{TemplateBinding Background}"
+ BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<ScrollViewer Focusable="False"
Name="PART_ScrollViewer"
| 2 | Fix background color in template | 1 | .xaml | xaml | mit | AvaloniaUI/AvaloniaEdit |
10057748 | <NME> TextEditor.xaml
<BEF> <Styles xmlns="https://github.com/avaloniaui"
xmlns:AvalonEdit="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:Editing="clr-namespace:AvaloniaEdit.Editing;assembly=AvaloniaEdit">
<Style Selector="AvalonEdit|TextEditor">
<Setter Property="Template">
<ControlTemplate>
<Border BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<ScrollViewer Focusable="False"
Name="PART_ScrollViewer"
VerticalScrollBarVisibility="{TemplateBinding VerticalScrollBarVisibility}"
HorizontalScrollBarVisibility="{TemplateBinding HorizontalScrollBarVisibility}"
VerticalContentAlignment="Top"
HorizontalContentAlignment="Left"
Padding="{TemplateBinding Padding}" />
</Border>
</ControlTemplate>
</Setter>
</Style>
</Styles>
<MSG> Fix background color in template
<DFF> @@ -4,7 +4,8 @@
<Style Selector="AvalonEdit|TextEditor">
<Setter Property="Template">
<ControlTemplate>
- <Border BorderBrush="{TemplateBinding BorderBrush}"
+ <Border Background="{TemplateBinding Background}"
+ BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<ScrollViewer Focusable="False"
Name="PART_ScrollViewer"
| 2 | Fix background color in template | 1 | .xaml | xaml | mit | AvaloniaUI/AvaloniaEdit |
10057749 | <NME> TextEditor.xaml
<BEF> <Styles xmlns="https://github.com/avaloniaui"
xmlns:AvalonEdit="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:Editing="clr-namespace:AvaloniaEdit.Editing;assembly=AvaloniaEdit">
<Style Selector="AvalonEdit|TextEditor">
<Setter Property="Template">
<ControlTemplate>
<Border BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<ScrollViewer Focusable="False"
Name="PART_ScrollViewer"
VerticalScrollBarVisibility="{TemplateBinding VerticalScrollBarVisibility}"
HorizontalScrollBarVisibility="{TemplateBinding HorizontalScrollBarVisibility}"
VerticalContentAlignment="Top"
HorizontalContentAlignment="Left"
Padding="{TemplateBinding Padding}" />
</Border>
</ControlTemplate>
</Setter>
</Style>
</Styles>
<MSG> Fix background color in template
<DFF> @@ -4,7 +4,8 @@
<Style Selector="AvalonEdit|TextEditor">
<Setter Property="Template">
<ControlTemplate>
- <Border BorderBrush="{TemplateBinding BorderBrush}"
+ <Border Background="{TemplateBinding Background}"
+ BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<ScrollViewer Focusable="False"
Name="PART_ScrollViewer"
| 2 | Fix background color in template | 1 | .xaml | xaml | mit | AvaloniaUI/AvaloniaEdit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.