This commit is contained in:
2026-11-24 15:51:02 +01:00
parent cca4d73e41
commit f4aa17114a
22092 changed files with 5042406 additions and 0 deletions
@@ -0,0 +1,149 @@
// 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 Unity.CodeEditor.Document;
using Unity.CodeEditor.Rendering;
using Unity.CodeEditor.Utils;
using UnityEngine;
using UnityEngine.UIElements;
using Debug = System.Diagnostics.Debug;
namespace Unity.CodeEditor.Editing
{
/// <summary>
/// Base class for margins.
/// Margins don't have to derive from this class, it just helps maintaining a reference to the TextView
/// and the TextDocument.
/// </summary>
internal abstract class AbstractMargin : VisualElement, ITextViewConnect
{
protected TextView _textView;
internal AbstractMargin()
{
style.flexShrink = 0;
}
/// <summary>
/// Gets/sets the text view for which line numbers are displayed.
/// </summary>
/// <remarks>Adding a margin to <see cref="TextArea.LeftMargins"/> will automatically set this property to the text area's TextView.</remarks>
internal TextView TextView
{
get { return _textView; }
set
{
if (_textView != value)
{
TextView oldValue = _textView;
_textView = value;
_wasAutoAddedToTextView = false;
OnTextViewChanged(oldValue, value);
}
}
}
private bool _wasAutoAddedToTextView;
void ITextViewConnect.AddToTextView(TextView textView)
{
if (TextView == null)
{
TextView = textView;
_wasAutoAddedToTextView = true;
}
else if (TextView != textView)
{
throw new InvalidOperationException("This margin belongs to a different TextView.");
}
}
void ITextViewConnect.RemoveFromTextView(TextView textView)
{
if (_wasAutoAddedToTextView && TextView == textView)
{
TextView = null;
Debug.Assert(!_wasAutoAddedToTextView);
}
}
/// <summary>
/// Gets the document associated with the margin.
/// </summary>
internal TextDocument Document { get; private set; }
protected TextArea TextArea { get; set; }
/// <summary>
/// Called when the <see cref="TextView"/> is changing.
/// </summary>
protected virtual void OnTextViewChanged(TextView oldTextView, TextView newTextView)
{
if (oldTextView != null)
{
oldTextView.DocumentChanged -= TextViewDocumentChanged;
}
if (newTextView != null)
{
newTextView.DocumentChanged += TextViewDocumentChanged;
}
TextViewDocumentChanged(null, null);
if (oldTextView != null)
{
oldTextView.VisualLinesChanged -= TextViewVisualLinesChanged;
}
if (newTextView != null)
{
newTextView.VisualLinesChanged += TextViewVisualLinesChanged;
TextArea = newTextView.GetService(typeof(TextArea)) as TextArea;
}
else
{
TextArea = null;
}
}
protected virtual void OnTextViewVisualLinesChanged()
{
MarkDirtyRepaint();
}
private void TextViewVisualLinesChanged(object sender, EventArgs e)
{
OnTextViewVisualLinesChanged();
}
private void TextViewDocumentChanged(object sender, EventArgs e)
{
OnDocumentChanged(Document, TextView?.Document);
}
/// <summary>
/// Called when the <see cref="Document"/> is changing.
/// </summary>
protected virtual void OnDocumentChanged(TextDocument oldDocument, TextDocument newDocument)
{
Document = newDocument;
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: a5b0cf5fb60d4f159d80936799b33e55
timeCreated: 1711883633
@@ -0,0 +1,538 @@
// 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.Diagnostics;
using Unity.CodeEditor.Document;
using Unity.CodeEditor.Rendering;
using Unity.CodeEditor.Utils;
using Unity.CodeEditor.Text;
using UnityEngine;
using Debug = UnityEngine.Debug;
namespace Unity.CodeEditor.Editing
{
/// <summary>
/// Helper class with caret-related methods.
/// </summary>
internal sealed class Caret
{
private const float CaretWidth = 0.5f;
private readonly TextArea _textArea;
private readonly TextView _textView;
private readonly CaretLayer _caretAdorner;
private bool _visible;
internal Caret(TextArea textArea)
{
_textArea = textArea;
_textView = textArea.TextView;
_position = new TextViewPosition(1, 1, 0);
_caretAdorner = new CaretLayer(textArea);
_textView.InsertLayer(_caretAdorner, KnownLayer.Caret, LayerInsertionPosition.Replace);
_textView.VisualLinesChanged += TextView_VisualLinesChanged;
_textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged;
}
internal void UpdateIfVisible()
{
if (_visible)
{
Show();
}
}
private void TextView_VisualLinesChanged(object sender, EventArgs e)
{
if (_visible)
{
Show();
}
// required because the visual columns might have changed if the
// element generators did something differently than on the last run
// (e.g. a FoldingSection was collapsed)
InvalidateVisualColumn();
}
private void TextView_ScrollOffsetChanged(object sender, EventArgs e)
{
//_caretAdorner?.InvalidateVisual();
}
private TextViewPosition _position;
/// <summary>
/// Gets/Sets the position of the caret.
/// Retrieving this property will validate the visual column (which can be expensive).
/// Use the <see cref="Location"/> property instead if you don't need the visual column.
/// </summary>
internal TextViewPosition Position
{
get
{
ValidateVisualColumn();
return _position;
}
set
{
if (_position != value)
{
_position = value;
_storedCaretOffset = -1;
ValidatePosition();
InvalidateVisualColumn();
RaisePositionChanged();
CalculateCaretRectangle();
//Debug.Log("Caret position changed to " + value);
if (_visible)
Show();
}
}
}
/// <summary>
/// Gets the caret position without validating it.
/// </summary>
internal TextViewPosition NonValidatedPosition => _position;
/// <summary>
/// Gets/Sets the location of the caret.
/// The getter of this property is faster than <see cref="Position"/> because it doesn't have
/// to validate the visual column.
/// </summary>
internal TextLocation Location
{
get => _position.Location;
set => Position = new TextViewPosition(value);
}
/// <summary>
/// Gets/Sets the caret line.
/// </summary>
internal int Line
{
get => _position.Line;
set => Position = new TextViewPosition(value, _position.Column);
}
/// <summary>
/// Gets/Sets the caret column.
/// </summary>
internal int Column
{
get => _position.Column;
set => Position = new TextViewPosition(_position.Line, value);
}
/// <summary>
/// Gets/Sets the caret visual column.
/// </summary>
internal int VisualColumn
{
get
{
ValidateVisualColumn();
return _position.VisualColumn;
}
set => Position = new TextViewPosition(_position.Line, _position.Column, value);
}
private bool _isInVirtualSpace;
/// <summary>
/// Gets whether the caret is in virtual space.
/// </summary>
internal bool IsInVirtualSpace
{
get
{
ValidateVisualColumn();
return _isInVirtualSpace;
}
}
private int _storedCaretOffset;
internal void OnDocumentChanging()
{
_storedCaretOffset = Offset;
InvalidateVisualColumn();
}
internal void OnDocumentChanged(DocumentChangeEventArgs e)
{
InvalidateVisualColumn();
if (_storedCaretOffset >= 0)
{
// If the caret is at the end of a selection, we don't expand the selection if something
// is inserted at the end. Thus we also need to keep the caret in front of the insertion.
AnchorMovementType caretMovementType;
if (!_textArea.Selection.IsEmpty && _storedCaretOffset == _textArea.Selection.SurroundingSegment.EndOffset)
caretMovementType = AnchorMovementType.BeforeInsertion;
else
caretMovementType = AnchorMovementType.Default;
var newCaretOffset = e.GetNewOffset(_storedCaretOffset, caretMovementType);
var document = _textArea.Document;
if (document != null)
{
// keep visual column
Position = new TextViewPosition(document.GetLocation(newCaretOffset), _position.VisualColumn);
}
}
_storedCaretOffset = -1;
}
/// <summary>
/// Gets/Sets the caret offset.
/// Setting the caret offset has the side effect of setting the <see cref="DesiredXPos"/> to NaN.
/// </summary>
internal int Offset
{
get
{
var document = _textArea.Document;
if (document == null)
{
return 0;
}
return document.GetOffset(_position.Location);
}
set
{
var document = _textArea.Document;
if (document != null)
{
Position = new TextViewPosition(document.GetLocation(value));
DesiredXPos = float.NaN;
}
}
}
/// <summary>
/// Gets/Sets the desired x-position of the caret, in device-independent pixels.
/// This property is NaN if the caret has no desired position.
/// </summary>
internal float DesiredXPos { get; set; } = float.NaN;
private void ValidatePosition()
{
if (_position.Line < 1)
_position.Line = 1;
if (_position.Column < 1)
_position.Column = 1;
if (_position.VisualColumn < -1)
_position.VisualColumn = -1;
var document = _textArea.Document;
if (document != null)
{
if (_position.Line > document.LineCount)
{
_position.Line = document.LineCount;
_position.Column = document.GetLineByNumber(_position.Line).Length + 1;
_position.VisualColumn = -1;
}
else
{
var line = document.GetLineByNumber(_position.Line);
if (_position.Column > line.Length + 1)
{
_position.Column = line.Length + 1;
_position.VisualColumn = -1;
}
}
}
}
/// <summary>
/// Event raised when the caret position has changed.
/// If the caret position is changed inside a document update (between BeginUpdate/EndUpdate calls),
/// the PositionChanged event is raised only once at the end of the document update.
/// </summary>
internal event EventHandler PositionChanged;
private bool _raisePositionChangedOnUpdateFinished;
private void RaisePositionChanged()
{
if (_textArea.Document != null && _textArea.Document.IsInUpdate)
{
_raisePositionChangedOnUpdateFinished = true;
}
else
{
PositionChanged?.Invoke(this, EventArgs.Empty);
}
}
internal void OnDocumentUpdateFinished()
{
if (_raisePositionChangedOnUpdateFinished)
{
_raisePositionChangedOnUpdateFinished = false;
PositionChanged?.Invoke(this, EventArgs.Empty);
}
}
private bool _visualColumnValid;
private void ValidateVisualColumn()
{
if (!_visualColumnValid)
{
var document = _textArea.Document;
if (document != null)
{
// Debug.WriteLine("Explicit validation of caret column");
var documentLine = document.GetLineByNumber(_position.Line);
RevalidateVisualColumn(_textView.GetOrConstructVisualLine(documentLine));
}
}
}
private void InvalidateVisualColumn()
{
_visualColumnValid = false;
}
/// <summary>
/// Validates the visual column of the caret using the specified visual line.
/// The visual line must contain the caret offset.
/// </summary>
private void RevalidateVisualColumn(VisualLine visualLine)
{
if (visualLine == null)
throw new ArgumentNullException(nameof(visualLine));
// mark column as validated
_visualColumnValid = true;
var caretOffset = _textView.Document.GetOffset(_position.Location);
var firstDocumentLineOffset = visualLine.FirstDocumentLine.Offset;
_position.VisualColumn = visualLine.ValidateVisualColumn(_position, _textArea.Selection.EnableVirtualSpace);
// search possible caret positions
var newVisualColumnForwards = visualLine.GetNextCaretPosition(_position.VisualColumn - 1, LogicalDirection.Forward, CaretPositioningMode.Normal, _textArea.Selection.EnableVirtualSpace);
// If position.VisualColumn was valid, we're done with validation.
if (newVisualColumnForwards != _position.VisualColumn)
{
// also search backwards so that we can pick the better match
var newVisualColumnBackwards = visualLine.GetNextCaretPosition(_position.VisualColumn + 1, LogicalDirection.Backward, CaretPositioningMode.Normal, _textArea.Selection.EnableVirtualSpace);
if (newVisualColumnForwards < 0 && newVisualColumnBackwards < 0)
throw ThrowUtil.NoValidCaretPosition();
// determine offsets for new visual column positions
int newOffsetForwards;
if (newVisualColumnForwards >= 0)
newOffsetForwards = visualLine.GetRelativeOffset(newVisualColumnForwards) + firstDocumentLineOffset;
else
newOffsetForwards = -1;
int newOffsetBackwards;
if (newVisualColumnBackwards >= 0)
newOffsetBackwards = visualLine.GetRelativeOffset(newVisualColumnBackwards) + firstDocumentLineOffset;
else
newOffsetBackwards = -1;
int newVisualColumn, newOffset;
// if there's only one valid position, use it
if (newVisualColumnForwards < 0)
{
newVisualColumn = newVisualColumnBackwards;
newOffset = newOffsetBackwards;
}
else if (newVisualColumnBackwards < 0)
{
newVisualColumn = newVisualColumnForwards;
newOffset = newOffsetForwards;
}
else
{
// two valid positions: find the better match
if (Math.Abs(newOffsetBackwards - caretOffset) < Math.Abs(newOffsetForwards - caretOffset))
{
// backwards is better
newVisualColumn = newVisualColumnBackwards;
newOffset = newOffsetBackwards;
}
else
{
// forwards is better
newVisualColumn = newVisualColumnForwards;
newOffset = newOffsetForwards;
}
}
Position = new TextViewPosition(_textView.Document.GetLocation(newOffset), newVisualColumn);
}
_isInVirtualSpace = (_position.VisualColumn > visualLine.VisualLength);
}
private Rect CalcCaretRectangle(VisualLine visualLine)
{
if (!_visualColumnValid)
{
RevalidateVisualColumn(visualLine);
}
var textLine = visualLine.GetTextLine(_position.VisualColumn, _position.IsAtEndOfLine);
var xPos = visualLine.GetTextLineVisualXPosition(textLine, _position.VisualColumn);
var lineTop = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.LineTop);
var lineBottom = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.LineBottom);
return new Rect(xPos,
lineTop,
CaretWidth,
lineBottom - lineTop);
}
Rect CalcCaretOverstrikeRectangle(VisualLine visualLine)
{
if (!_visualColumnValid) {
RevalidateVisualColumn(visualLine);
}
int currentPos = _position.VisualColumn;
// The text being overwritten in overstrike mode is everything up to the next normal caret stop
int nextPos = visualLine.GetNextCaretPosition(currentPos, LogicalDirection.Forward, CaretPositioningMode.Normal, true);
var textLine = visualLine.GetTextLine(currentPos);
Rect r;
if (currentPos < visualLine.VisualLength) {
// If the caret is within the text, use GetTextBounds() for the text being overwritten.
// This is necessary to ensure the rectangle is calculated correctly in bidirectional text.
var textBounds = textLine.GetTextBounds(currentPos, nextPos - currentPos)[0];
r = textBounds;
var y = r.y + visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.LineTop);
r = r.WithY(y);
} else {
// If the caret is at the end of the line (or in virtual space),
// use the visual X position of currentPos and nextPos (one or more of which will be in virtual space)
float xPos = visualLine.GetTextLineVisualXPosition(textLine, currentPos);
float xPos2 = visualLine.GetTextLineVisualXPosition(textLine, nextPos);
float lineTop = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.TextTop);
float lineBottom = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.TextBottom);
r = new Rect(xPos, lineTop, xPos2 - xPos, lineBottom - lineTop);
}
// If the caret is too small (e.g. in front of zero-width character), ensure it's still visible
if (r.width < CaretWidth)
r = r.WithWidth(CaretWidth);
return r;
}
/// <summary>
/// Returns the caret rectangle. The coordinate system is in device-independent pixels from the top of the document.
/// </summary>
internal Rect CalculateCaretRectangle()
{
if (_textView?.Document != null)
{
var visualLine = _textView.GetOrConstructVisualLine(_textView.Document.GetLineByNumber(_position.Line));
return /*_textArea.OverstrikeMode ? CalcCaretOverstrikeRectangle(visualLine); : */CalcCaretRectangle(visualLine);
}
return default;
}
/// <summary>
/// Minimum distance of the caret to the view border.
/// </summary>
internal const double MinimumDistanceToViewBorder = 0;
/// <summary>
/// Scrolls the text view so that the caret is visible.
/// </summary>
internal void BringCaretToView()
{
BringCaretToView(0);
}
internal void BringCaretToView(float border)
{
var caretRectangle = CalculateCaretRectangle();
if (caretRectangle != default)
{
caretRectangle = caretRectangle.Inflate(border);
_textView.MakeVisible(caretRectangle);
}
}
/// <summary>
/// Makes the caret visible and updates its on-screen position.
/// </summary>
internal void Show()
{
_visible = true;
ShowInternal();
}
private bool _hasWin32Caret;
private void ShowInternal()
{
if (_caretAdorner != null && _textView != null)
{
var visualLine = _textView.GetVisualLine(_position.Line);
if (visualLine != null)
{
var caretRect = /*_textArea.OverstrikeMode ? CalcCaretOverstrikeRectangle(visualLine); :*/ CalcCaretRectangle(visualLine);
// TODO: win32 caret
// Create Win32 caret so that Windows knows where our managed caret is. This is necessary for
// features like 'Follow text editing' in the Windows Magnifier.
//if (!hasWin32Caret) {
// hasWin32Caret = Win32.CreateCaret(textView, caretRect.Size);
//}
//if (hasWin32Caret) {
// Win32.SetCaretPosition(textView, caretRect.Location - textView.ScrollOffset);
//}
_caretAdorner.Show(caretRect);
//textArea.ime.UpdateCompositionWindow();
}
else
{
_caretAdorner.Hide();
}
}
}
/// <summary>
/// Makes the caret invisible.
/// </summary>
internal void Hide()
{
_visible = false;
if (_hasWin32Caret)
{
// TODO: win32 caret
//Win32.DestroyCaret();
_hasWin32Caret = false;
}
_caretAdorner?.Hide();
}
/// <summary>
/// Gets/Sets the color of the caret.
/// </summary>
internal Color? CaretBrush
{
get => _caretAdorner.CaretBrush;
set => _caretAdorner.CaretBrush = value;
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 45287be3ac9444c08ec6fa91021df881
timeCreated: 1710765992
@@ -0,0 +1,111 @@
// 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 Unity.CodeEditor.Rendering;
using Unity.CodeEditor.Utils;
using UnityEngine;
using UnityEngine.UIElements;
namespace Unity.CodeEditor.Editing
{
internal sealed class CaretLayer : Layer
{
private readonly TextArea _textArea;
private readonly VisualElement _caretElement;
private bool _isVisible;
private Rect _caretRectangle;
private IVisualElementScheduledItem _blinkSchedule;
private bool _blink;
internal CaretLayer(TextArea textArea) : base(textArea.TextView, KnownLayer.Caret)
{
_textArea = textArea;
_caretElement = new VisualElement();
_caretElement.pickingMode = PickingMode.Ignore;
_caretElement.style.position = Position.Absolute;
_caretElement.visible = false;
Add(_caretElement);
}
private void UpdateCaretVisual()
{
if (!_isVisible || !_blink)
{
_caretElement.visible = false;
return;
}
var caretBrush = CaretBrush ?? TextView.ForegroundColor;
var r = new Rect(_caretRectangle.x - TextView.HorizontalOffset,
_caretRectangle.y - TextView.VerticalOffset,
_caretRectangle.width,
_caretRectangle.height);
r = PixelSnapHelpers.Round(r, PixelSnapHelpers.GetPixelSize(this));
_caretElement.style.left = r.x;
_caretElement.style.top = r.y;
_caretElement.style.width = r.width;
_caretElement.style.height = r.height;
_caretElement.style.backgroundColor = caretBrush;
_caretElement.visible = true;
}
internal void Show(Rect caretRectangle)
{
_caretRectangle = caretRectangle;
_isVisible = true;
StartBlinkAnimation();
UpdateCaretVisual();
}
internal void Hide()
{
if (_isVisible)
{
_isVisible = false;
StopBlinkAnimation();
UpdateCaretVisual();
}
}
private void StartBlinkAnimation()
{
_blink = true;
StopBlinkAnimation();
_blinkSchedule = schedule.Execute(() =>
{
_blink = !_blink;
UpdateCaretVisual();
}).StartingIn(500).Every(500);
}
private void StopBlinkAnimation()
{
_blinkSchedule?.Pause();
_blinkSchedule = null;
}
internal Color? CaretBrush;
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 0c13d6a1dbd74659becd6e9d0d519282
timeCreated: 1710863931
@@ -0,0 +1,706 @@
// 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 Unity.CodeEditor.Document;
using Unity.CodeEditor.Platform;
using Unity.CodeEditor.Rendering;
using Unity.CodeEditor.Text;
using Unity.CodeEditor.Utils;
using UnityEngine;
using UnityEngine.UIElements;
using LogicalDirection = Unity.CodeEditor.Document.LogicalDirection;
namespace Unity.CodeEditor.Editing
{
internal enum CaretMovementType
{
None,
CharLeft,
CharRight,
Backspace,
WordLeft,
WordRight,
LineUp,
LineDown,
PageUp,
PageDown,
LineStart,
LineEnd,
DocumentStart,
DocumentEnd
}
internal class CaretNavigationCommandHandler
{
Dictionary<KeyGesture, CaretNavigationCommand> _navigationCommands = new Dictionary<KeyGesture, CaretNavigationCommand>();
internal CaretNavigationCommandHandler(TextArea textArea)
{
TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea));
var keymap = PlatformHotkeyConfiguration.Current;
_navigationCommands.Add(new KeyGesture(KeyCode.LeftArrow), CaretNavigationCommand.MoveLeftByCharacter);
_navigationCommands.Add(new KeyGesture(KeyCode.LeftArrow, keymap.SelectionModifiers), CaretNavigationCommand.SelectLeftByCharacter);
_navigationCommands.Add(new KeyGesture(KeyCode.LeftArrow, keymap.BoxSelectionModifiers | keymap.SelectionModifiers), CaretNavigationCommand.BoxSelectLeftByCharacter);
_navigationCommands.Add(new KeyGesture(KeyCode.RightArrow), CaretNavigationCommand.MoveRightByCharacter);
_navigationCommands.Add(new KeyGesture(KeyCode.RightArrow, keymap.SelectionModifiers), CaretNavigationCommand.SelectRightByCharacter);
_navigationCommands.Add(new KeyGesture(KeyCode.RightArrow, keymap.BoxSelectionModifiers | keymap.SelectionModifiers), CaretNavigationCommand.BoxSelectRightByCharacter);
_navigationCommands.Add(new KeyGesture(KeyCode.LeftArrow, keymap.WholeWordTextActionModifiers), CaretNavigationCommand.MoveLeftByWord);
_navigationCommands.Add(new KeyGesture(KeyCode.LeftArrow, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers), CaretNavigationCommand.SelectLeftByWord);
_navigationCommands.Add(new KeyGesture(KeyCode.LeftArrow, keymap.WholeWordTextActionModifiers | keymap.BoxSelectionModifiers | keymap.SelectionModifiers), CaretNavigationCommand.BoxSelectLeftByWord);
_navigationCommands.Add(new KeyGesture(KeyCode.RightArrow, keymap.WholeWordTextActionModifiers), CaretNavigationCommand.MoveRightByWord);
_navigationCommands.Add(new KeyGesture(KeyCode.RightArrow, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers), CaretNavigationCommand.SelectRightByWord);
_navigationCommands.Add(new KeyGesture(KeyCode.RightArrow, keymap.WholeWordTextActionModifiers | keymap.BoxSelectionModifiers | keymap.SelectionModifiers), CaretNavigationCommand.BoxSelectRightByWord);
_navigationCommands.Add(new KeyGesture(KeyCode.UpArrow), CaretNavigationCommand.MoveUpByLine);
_navigationCommands.Add(new KeyGesture(KeyCode.UpArrow, keymap.SelectionModifiers), CaretNavigationCommand.SelectUpByLine);
_navigationCommands.Add(new KeyGesture(KeyCode.UpArrow, keymap.BoxSelectionModifiers | keymap.SelectionModifiers), CaretNavigationCommand.BoxSelectUpByLine);
_navigationCommands.Add(new KeyGesture(KeyCode.DownArrow), CaretNavigationCommand.MoveDownByLine);
_navigationCommands.Add(new KeyGesture(KeyCode.DownArrow, keymap.SelectionModifiers), CaretNavigationCommand.SelectDownByLine);
_navigationCommands.Add(new KeyGesture(KeyCode.DownArrow, keymap.BoxSelectionModifiers | keymap.SelectionModifiers), CaretNavigationCommand.BoxSelectDownByLine);
_navigationCommands.Add(new KeyGesture(KeyCode.PageDown), CaretNavigationCommand.MoveDownByPage);
_navigationCommands.Add(new KeyGesture(KeyCode.PageDown, keymap.SelectionModifiers), CaretNavigationCommand.SelectDownByPage);
_navigationCommands.Add(new KeyGesture(KeyCode.PageUp), CaretNavigationCommand.MoveUpByPage);
_navigationCommands.Add(new KeyGesture(KeyCode.PageUp, keymap.SelectionModifiers), CaretNavigationCommand.SelectUpByPage);
keymap.MoveCursorToTheStartOfLine.ForEach(g => _navigationCommands.Add(g, CaretNavigationCommand.MoveToLineStart));
keymap.MoveCursorToTheStartOfLineWithSelection.ForEach(g => _navigationCommands.Add(g, CaretNavigationCommand.SelectToLineStart));
keymap.MoveCursorToTheEndOfLine.ForEach(g => _navigationCommands.Add(g, CaretNavigationCommand.MoveToLineEnd));
keymap.MoveCursorToTheEndOfLineWithSelection.ForEach(g => _navigationCommands.Add(g, CaretNavigationCommand.SelectToLineEnd));
_navigationCommands.Add(new KeyGesture(KeyCode.Home, keymap.BoxSelectionModifiers | keymap.SelectionModifiers), CaretNavigationCommand.BoxSelectToLineStart);
_navigationCommands.Add(new KeyGesture(KeyCode.End, keymap.BoxSelectionModifiers | keymap.SelectionModifiers), CaretNavigationCommand.BoxSelectToLineEnd);
keymap.MoveCursorToTheStartOfDocument.ForEach(g => _navigationCommands.Add(g, CaretNavigationCommand.MoveToDocumentStart));
keymap.MoveCursorToTheStartOfDocumentWithSelection.ForEach(g => _navigationCommands.Add(g, CaretNavigationCommand.SelectToDocumentStart));
keymap.MoveCursorToTheEndOfDocument.ForEach(g => _navigationCommands.Add(g, CaretNavigationCommand.MoveToDocumentEnd));
keymap.MoveCursorToTheEndOfDocumentWithSelection.ForEach(g => _navigationCommands.Add(g, CaretNavigationCommand.SelectToDocumentEnd));
keymap.SelectAll.ForEach(g => _navigationCommands.Add(g, CaretNavigationCommand.SelectAll));
}
internal TextArea TextArea { get; }
internal void OnKeyDown(KeyDownEvent e)
{
if (TextArea?.Document == null)
return;
CaretNavigationCommand command = GetEditingCommand(e);
switch (command)
{
case CaretNavigationCommand.MoveLeftByCharacter:
MoveLeftByCharacter();
e.StopPropagation();
break;
case CaretNavigationCommand.SelectLeftByCharacter:
SelectLeftByCharacter();
e.StopPropagation();
break;
case CaretNavigationCommand.BoxSelectLeftByCharacter:
BoxSelectLeftByCharacter();
e.StopPropagation();
break;
case CaretNavigationCommand.MoveRightByCharacter:
MoveRightByCharacter();
e.StopPropagation();
break;
case CaretNavigationCommand.SelectRightByCharacter:
SelectRightByCharacter();
e.StopPropagation();
break;
case CaretNavigationCommand.BoxSelectRightByCharacter:
BoxSelectRightByCharacter();
e.StopPropagation();
break;
case CaretNavigationCommand.MoveLeftByWord:
MoveLeftByWord();
e.StopPropagation();
break;
case CaretNavigationCommand.SelectLeftByWord:
SelectLeftByWord();
e.StopPropagation();
break;
case CaretNavigationCommand.BoxSelectLeftByWord:
BoxSelectLeftByWord();
e.StopPropagation();
break;
case CaretNavigationCommand.MoveRightByWord:
MoveRightByWord();
e.StopPropagation();
break;
case CaretNavigationCommand.SelectRightByWord:
SelectRightByWord();
e.StopPropagation();
break;
case CaretNavigationCommand.BoxSelectRightByWord:
BoxSelectRightByWord();
e.StopPropagation();
break;
case CaretNavigationCommand.MoveUpByLine:
MoveUpByLine();
e.StopPropagation();
break;
case CaretNavigationCommand.SelectUpByLine:
SelectUpByLine();
e.StopPropagation();
break;
case CaretNavigationCommand.BoxSelectUpByLine:
BoxSelectUpByLine();
e.StopPropagation();
break;
case CaretNavigationCommand.MoveDownByLine:
MoveDownByLine();
e.StopPropagation();
break;
case CaretNavigationCommand.SelectDownByLine:
SelectDownByLine();
e.StopPropagation();
break;
case CaretNavigationCommand.BoxSelectDownByLine:
BoxSelectDownByLine();
e.StopPropagation();
break;
case CaretNavigationCommand.MoveDownByPage:
MoveDownByPage();
e.StopPropagation();
break;
case CaretNavigationCommand.SelectDownByPage:
SelectDownByPage();
e.StopPropagation();
break;
case CaretNavigationCommand.MoveUpByPage:
MoveUpByPage();
e.StopPropagation();
break;
case CaretNavigationCommand.SelectUpByPage:
SelectUpByPage();
e.StopPropagation();
break;
case CaretNavigationCommand.MoveToLineStart:
MoveToLineStart();
e.StopPropagation();
break;
case CaretNavigationCommand.SelectToLineStart:
SelectToLineStart();
e.StopPropagation();
break;
case CaretNavigationCommand.MoveToLineEnd:
MoveToLineEnd();
e.StopPropagation();
break;
case CaretNavigationCommand.SelectToLineEnd:
SelectToLineEnd();
e.StopPropagation();
break;
case CaretNavigationCommand.BoxSelectToLineStart:
BoxSelectToLineStart();
e.StopPropagation();
break;
case CaretNavigationCommand.BoxSelectToLineEnd:
BoxSelectToLineEnd();
e.StopPropagation();
break;
case CaretNavigationCommand.MoveToDocumentStart:
MoveToDocumentStart();
e.StopPropagation();
break;
case CaretNavigationCommand.SelectToDocumentStart:
SelectToDocumentStart();
e.StopPropagation();
break;
case CaretNavigationCommand.MoveToDocumentEnd:
MoveToDocumentEnd();
e.StopPropagation();
break;
case CaretNavigationCommand.SelectToDocumentEnd:
SelectToDocumentEnd();
e.StopPropagation();
break;
case CaretNavigationCommand.SelectAll:
SelectAll();
e.StopPropagation();
break;
}
}
CaretNavigationCommand GetEditingCommand(KeyDownEvent e)
{
KeyGesture keyGesture = new KeyGesture(e.keyCode, e.GetKeyModifiers());
if (_navigationCommands.TryGetValue(keyGesture, out CaretNavigationCommand command))
return command;
return CaretNavigationCommand.None;
}
void MoveLeftByCharacter()
{
OnMoveCaret(TextArea, CaretMovementType.CharLeft);
}
void SelectLeftByCharacter()
{
OnMoveCaretExtendSelection(TextArea, CaretMovementType.CharLeft);
}
void BoxSelectLeftByCharacter()
{
OnMoveCaretBoxSelection(TextArea, CaretMovementType.CharLeft);
}
void MoveRightByCharacter()
{
OnMoveCaret(TextArea, CaretMovementType.CharRight);
}
void SelectRightByCharacter()
{
OnMoveCaretExtendSelection(TextArea, CaretMovementType.CharRight);
}
void BoxSelectRightByCharacter()
{
OnMoveCaretBoxSelection(TextArea, CaretMovementType.CharRight);
}
void MoveLeftByWord()
{
OnMoveCaret(TextArea, CaretMovementType.WordLeft);
}
void SelectLeftByWord()
{
OnMoveCaretExtendSelection(TextArea, CaretMovementType.WordLeft);
}
void BoxSelectLeftByWord()
{
OnMoveCaretBoxSelection(TextArea, CaretMovementType.WordLeft);
}
void MoveRightByWord()
{
OnMoveCaret(TextArea, CaretMovementType.WordRight);
}
void SelectRightByWord()
{
OnMoveCaretExtendSelection(TextArea, CaretMovementType.WordRight);
}
void BoxSelectRightByWord()
{
OnMoveCaretBoxSelection(TextArea, CaretMovementType.WordRight);
}
void MoveUpByLine()
{
OnMoveCaret(TextArea, CaretMovementType.LineUp);
}
void SelectUpByLine()
{
OnMoveCaretExtendSelection(TextArea, CaretMovementType.LineUp);
}
void BoxSelectUpByLine()
{
OnMoveCaretBoxSelection(TextArea, CaretMovementType.LineUp);
}
void MoveDownByLine()
{
OnMoveCaret(TextArea, CaretMovementType.LineDown);
}
void SelectDownByLine()
{
OnMoveCaretExtendSelection(TextArea, CaretMovementType.LineDown);
}
void BoxSelectDownByLine()
{
OnMoveCaretBoxSelection(TextArea, CaretMovementType.LineDown);
}
void MoveDownByPage()
{
OnMoveCaret(TextArea, CaretMovementType.PageDown);
}
void SelectDownByPage()
{
OnMoveCaretExtendSelection(TextArea, CaretMovementType.PageDown);
}
void MoveUpByPage()
{
OnMoveCaret(TextArea, CaretMovementType.PageUp);
}
void SelectUpByPage()
{
OnMoveCaretExtendSelection(TextArea, CaretMovementType.PageUp);
}
void MoveToLineStart()
{
OnMoveCaret(TextArea, CaretMovementType.LineStart);
}
void SelectToLineStart()
{
OnMoveCaretExtendSelection(TextArea, CaretMovementType.LineStart);
}
void MoveToLineEnd()
{
OnMoveCaret(TextArea, CaretMovementType.LineEnd);
}
void SelectToLineEnd()
{
OnMoveCaretExtendSelection(TextArea, CaretMovementType.LineEnd);
}
void BoxSelectToLineStart()
{
OnMoveCaretBoxSelection(TextArea, CaretMovementType.LineStart);
}
void BoxSelectToLineEnd()
{
OnMoveCaretBoxSelection(TextArea, CaretMovementType.LineEnd);
}
void MoveToDocumentStart()
{
OnMoveCaret(TextArea, CaretMovementType.DocumentStart);
}
void SelectToDocumentStart()
{
OnMoveCaretExtendSelection(TextArea, CaretMovementType.DocumentStart);
}
void MoveToDocumentEnd()
{
OnMoveCaret(TextArea, CaretMovementType.DocumentEnd);
}
void SelectToDocumentEnd()
{
OnMoveCaretExtendSelection(TextArea, CaretMovementType.DocumentEnd);
}
void SelectAll()
{
OnSelectAll(TextArea);
}
static void OnSelectAll(TextArea textArea)
{
textArea.Caret.Offset = textArea.Document.TextLength;
textArea.Selection = Selection.Create(textArea, 0, textArea.Document.TextLength);
}
static void OnMoveCaret(TextArea textArea, CaretMovementType direction)
{
textArea.ClearSelection();
MoveCaret(textArea, direction);
float borderSize = direction == CaretMovementType.CharRight ||
direction == CaretMovementType.WordRight ||
direction == CaretMovementType.CharLeft ||
direction == CaretMovementType.WordLeft ||
direction == CaretMovementType.Backspace
? textArea.TextView.WideSpaceWidth * 2 : 0;
textArea.Caret.BringCaretToView(borderSize);
}
static void OnMoveCaretExtendSelection(TextArea textArea, CaretMovementType direction)
{
var oldPosition = textArea.Caret.Position;
MoveCaret(textArea, direction);
textArea.Selection = textArea.Selection.StartSelectionOrSetEndpoint(oldPosition, textArea.Caret.Position);
textArea.Caret.BringCaretToView();
}
static void OnMoveCaretBoxSelection(TextArea textArea, CaretMovementType direction)
{
// First, convert the selection into a rectangle selection
// (this is required so that virtual space gets enabled for the caret movement)
if (textArea.Options.EnableRectangularSelection && !(textArea.Selection is RectangleSelection))
{
textArea.Selection = textArea.Selection.IsEmpty
? new RectangleSelection(textArea, textArea.Caret.Position, textArea.Caret.Position)
: new RectangleSelection(textArea, textArea.Selection.StartPosition,
textArea.Caret.Position);
}
// Now move the caret and extend the selection
var oldPosition = textArea.Caret.Position;
MoveCaret(textArea, direction);
textArea.Selection = textArea.Selection.StartSelectionOrSetEndpoint(oldPosition, textArea.Caret.Position);
textArea.Caret.BringCaretToView();
}
#region Caret movement
internal static void MoveCaret(TextArea textArea, CaretMovementType direction)
{
var desiredXPos = textArea.Caret.DesiredXPos;
textArea.Caret.Position = GetNewCaretPosition(textArea.TextView, textArea.Caret.Position, direction, textArea.Selection.EnableVirtualSpace, ref desiredXPos);
textArea.Caret.DesiredXPos = desiredXPos;
}
internal static TextViewPosition GetNewCaretPosition(TextView textView, TextViewPosition caretPosition, CaretMovementType direction, bool enableVirtualSpace, ref float desiredXPos)
{
switch (direction)
{
case CaretMovementType.None:
return caretPosition;
case CaretMovementType.DocumentStart:
desiredXPos = float.NaN;
return new TextViewPosition(0, 0);
case CaretMovementType.DocumentEnd:
desiredXPos = float.NaN;
return new TextViewPosition(textView.Document.GetLocation(textView.Document.TextLength));
}
var caretLine = textView.Document.GetLineByNumber(caretPosition.Line);
var visualLine = textView.GetOrConstructVisualLine(caretLine);
var textLine = visualLine.GetTextLine(caretPosition.VisualColumn, caretPosition.IsAtEndOfLine);
switch (direction)
{
case CaretMovementType.CharLeft:
desiredXPos = float.NaN;
// do not move caret to previous line in virtual space
if (caretPosition.VisualColumn == 0 && enableVirtualSpace)
return caretPosition;
return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.Normal, enableVirtualSpace);
case CaretMovementType.Backspace:
desiredXPos = float.NaN;
return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.EveryCodepoint, enableVirtualSpace);
case CaretMovementType.CharRight:
desiredXPos = float.NaN;
return GetNextCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.Normal, enableVirtualSpace);
case CaretMovementType.WordLeft:
desiredXPos = float.NaN;
return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.WordStart, enableVirtualSpace);
case CaretMovementType.WordRight:
desiredXPos = float.NaN;
return GetNextCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.WordStart, enableVirtualSpace);
case CaretMovementType.LineUp:
case CaretMovementType.LineDown:
case CaretMovementType.PageUp:
case CaretMovementType.PageDown:
return GetUpDownCaretPosition(textView, caretPosition, direction, visualLine, textLine, enableVirtualSpace, ref desiredXPos);
case CaretMovementType.LineStart:
desiredXPos = float.NaN;
return GetStartOfLineCaretPosition(caretPosition.VisualColumn, visualLine, textLine, enableVirtualSpace);
case CaretMovementType.LineEnd:
desiredXPos = float.NaN;
return GetEndOfLineCaretPosition(visualLine, textLine);
default:
throw new NotSupportedException(direction.ToString());
}
}
#endregion
#region Home/End
static TextViewPosition GetStartOfLineCaretPosition(int oldVisualColumn, VisualLine visualLine, TextLine textLine, bool enableVirtualSpace)
{
var newVisualCol = visualLine.GetTextLineVisualStartColumn(textLine);
if (newVisualCol == 0)
newVisualCol = visualLine.GetNextCaretPosition(newVisualCol - 1, LogicalDirection.Forward, CaretPositioningMode.WordStart, enableVirtualSpace);
if (newVisualCol < 0)
throw ThrowUtil.NoValidCaretPosition();
// when the caret is already at the start of the text, jump to start before whitespace
if (newVisualCol == oldVisualColumn)
newVisualCol = 0;
return visualLine.GetTextViewPosition(newVisualCol);
}
static TextViewPosition GetEndOfLineCaretPosition(VisualLine visualLine, TextLine textLine)
{
var newVisualCol = visualLine.GetTextLineVisualStartColumn(textLine) + textLine.Length - textLine.TrailingWhitespaceLength;
var pos = visualLine.GetTextViewPosition(newVisualCol);
pos.IsAtEndOfLine = true;
return pos;
}
#endregion
#region By-character / By-word movement
static TextViewPosition GetNextCaretPosition(TextView textView, TextViewPosition caretPosition, VisualLine visualLine, CaretPositioningMode mode, bool enableVirtualSpace)
{
var pos = visualLine.GetNextCaretPosition(caretPosition.VisualColumn, LogicalDirection.Forward, mode, enableVirtualSpace);
if (pos >= 0)
{
return visualLine.GetTextViewPosition(pos);
}
else
{
// move to start of next line
var nextDocumentLine = visualLine.LastDocumentLine.NextLine;
if (nextDocumentLine != null)
{
var nextLine = textView.GetOrConstructVisualLine(nextDocumentLine);
pos = nextLine.GetNextCaretPosition(-1, LogicalDirection.Forward, mode, enableVirtualSpace);
if (pos < 0)
throw ThrowUtil.NoValidCaretPosition();
return nextLine.GetTextViewPosition(pos);
}
else
{
// at end of document
System.Diagnostics.Debug.Assert(visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength == textView.Document.TextLength);
return new TextViewPosition(textView.Document.GetLocation(textView.Document.TextLength));
}
}
}
static TextViewPosition GetPrevCaretPosition(TextView textView, TextViewPosition caretPosition, VisualLine visualLine, CaretPositioningMode mode, bool enableVirtualSpace)
{
var pos = visualLine.GetNextCaretPosition(caretPosition.VisualColumn, LogicalDirection.Backward, mode, enableVirtualSpace);
if (pos >= 0)
{
return visualLine.GetTextViewPosition(pos);
}
else
{
// move to end of previous line
var previousDocumentLine = visualLine.FirstDocumentLine.PreviousLine;
if (previousDocumentLine != null)
{
var previousLine = textView.GetOrConstructVisualLine(previousDocumentLine);
pos = previousLine.GetNextCaretPosition(previousLine.VisualLength + 1, LogicalDirection.Backward, mode, enableVirtualSpace);
if (pos < 0)
throw ThrowUtil.NoValidCaretPosition();
return previousLine.GetTextViewPosition(pos);
}
else
{
// at start of document
System.Diagnostics.Debug.Assert(visualLine.FirstDocumentLine.Offset == 0);
return new TextViewPosition(0, 0);
}
}
}
#endregion
#region Line+Page up/down
static TextViewPosition GetUpDownCaretPosition(TextView textView, TextViewPosition caretPosition, CaretMovementType direction, VisualLine visualLine, TextLine textLine, bool enableVirtualSpace, ref float xPos)
{
// moving up/down happens using the desired visual X position
if (float.IsNaN(xPos))
xPos = visualLine.GetTextLineVisualXPosition(textLine, caretPosition.VisualColumn);
// now find the TextLine+VisualLine where the caret will end up in
var targetVisualLine = visualLine;
TextLine targetLine;
var textLineIndex = visualLine.TextLines.IndexOf(textLine);
switch (direction)
{
case CaretMovementType.LineUp:
{
// Move up: move to the previous TextLine in the same visual line
// or move to the last TextLine of the previous visual line
var prevLineNumber = visualLine.FirstDocumentLine.LineNumber - 1;
if (textLineIndex > 0)
{
targetLine = visualLine.TextLines[textLineIndex - 1];
}
else if (prevLineNumber >= 1)
{
var prevLine = textView.Document.GetLineByNumber(prevLineNumber);
targetVisualLine = textView.GetOrConstructVisualLine(prevLine);
targetLine = targetVisualLine.TextLines[targetVisualLine.TextLines.Count - 1];
}
else
{
targetLine = null;
}
break;
}
case CaretMovementType.LineDown:
{
// Move down: move to the next TextLine in the same visual line
// or move to the first TextLine of the next visual line
var nextLineNumber = visualLine.LastDocumentLine.LineNumber + 1;
if (textLineIndex < visualLine.TextLines.Count - 1)
{
targetLine = visualLine.TextLines[textLineIndex + 1];
}
else if (nextLineNumber <= textView.Document.LineCount)
{
var nextLine = textView.Document.GetLineByNumber(nextLineNumber);
targetVisualLine = textView.GetOrConstructVisualLine(nextLine);
targetLine = targetVisualLine.TextLines[0];
}
else
{
targetLine = null;
}
break;
}
case CaretMovementType.PageUp:
case CaretMovementType.PageDown:
{
// Page up/down: find the target line using its visual position
var yPos = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.LineMiddle);
if (direction == CaretMovementType.PageUp)
yPos -= textView.Bounds.height;
else
yPos += textView.Bounds.height;
var newLine = textView.GetDocumentLineByVisualTop(yPos);
targetVisualLine = textView.GetOrConstructVisualLine(newLine);
targetLine = targetVisualLine.GetTextLineByVisualYPosition(yPos);
break;
}
default:
throw new NotSupportedException(direction.ToString());
}
if (targetLine != null)
{
var yPos = targetVisualLine.GetTextLineVisualYPosition(targetLine, VisualYPosition.LineMiddle);
var newVisualColumn = targetVisualLine.GetVisualColumn(new Vector2(xPos, yPos), enableVirtualSpace);
// prevent wrapping to the next line; TODO: could 'IsAtEnd' help here?
var targetLineStartCol = targetVisualLine.GetTextLineVisualStartColumn(targetLine);
if (newVisualColumn >= targetLineStartCol + targetLine.Length)
{
if (newVisualColumn <= targetVisualLine.VisualLength)
newVisualColumn = targetLineStartCol + targetLine.Length - 1;
}
return targetVisualLine.GetTextViewPosition(newVisualColumn);
}
else
{
return caretPosition;
}
}
#endregion
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 5f7e5d5ce5c2fd6418dddab8e9586141
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,40 @@
// 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 Unity.CodeEditor.Utils;
namespace Unity.CodeEditor.Editing
{
/// <summary>
/// Contains classes for handling weak events on the Caret class.
/// </summary>
internal static class CaretWeakEventManager
{
/// <summary>
/// Handles the Caret.PositionChanged event.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")]
internal sealed class PositionChanged : WeakEventManagerBase<PositionChanged, Caret, EventHandler, EventArgs>
{
protected override void StartListening(Caret source) => source.PositionChanged += DeliverEvent;
protected override void StopListening(Caret source) => source.PositionChanged -= DeliverEvent;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: e76f45abe6dcffe438b00d78c0aca721
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,52 @@
// 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;
namespace Unity.CodeEditor.Editing
{
/// <summary>
/// Wraps exceptions that occur during drag'n'drop.
/// Exceptions during drag'n'drop might
/// get swallowed, so AvaloniaEdit catches them and re-throws them later
/// wrapped in a DragDropException.
/// </summary>
internal class DragDropException : Exception
{
/// <summary>
/// Creates a new DragDropException.
/// </summary>
internal DragDropException()
{
}
/// <summary>
/// Creates a new DragDropException.
/// </summary>
internal DragDropException(string message) : base(message)
{
}
/// <summary>
/// Creates a new DragDropException.
/// </summary>
internal DragDropException(string message, Exception innerException) : base(message, innerException)
{
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 4809ab5cb1988e5449f9e1911e77d7ef
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,931 @@
// 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 Unity.CodeEditor.Document;
using Unity.CodeEditor.Platform;
using UnityEngine;
using UnityEngine.UIElements;
namespace Unity.CodeEditor.Editing
{
/// <summary>
/// We re-use the CommandBinding and InputBinding instances between multiple text areas,
/// so this class is static.
/// </summary>
internal class EditingCommandHandler
{
Dictionary<KeyGesture, EditingCommand> _editingCommands = new Dictionary<KeyGesture, EditingCommand>();
internal EditingCommandHandler(TextArea textArea)
{
TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea));
var keymap = PlatformHotkeyConfiguration.Current;
_editingCommands.Add(new KeyGesture(KeyCode.Delete), EditingCommand.Delete);
_editingCommands.Add(new KeyGesture(KeyCode.Delete, KeyModifiers.Control), EditingCommand.DeleteNextWord);
_editingCommands.Add(new KeyGesture(KeyCode.Backspace), EditingCommand.Backspace);
_editingCommands.Add(new KeyGesture(KeyCode.Backspace, KeyModifiers.Shift), EditingCommand.Backspace); // make Shift-Backspace do the same as plain backspace
_editingCommands.Add(new KeyGesture(KeyCode.Backspace, KeyModifiers.Control), EditingCommand.DeletePreviousWord);
_editingCommands.Add(new KeyGesture(KeyCode.KeypadEnter), EditingCommand.EnterParagraphBreak);
_editingCommands.Add(new KeyGesture(KeyCode.Return), EditingCommand.EnterParagraphBreak);
_editingCommands.Add(new KeyGesture(KeyCode.Return, KeyModifiers.Shift), EditingCommand.EnterLineBreak);
_editingCommands.Add(new KeyGesture(KeyCode.Tab), EditingCommand.TabForward);
_editingCommands.Add(new KeyGesture(KeyCode.Tab, KeyModifiers.Shift), EditingCommand.TabBackward);
keymap.Copy.ForEach(g => _editingCommands.Add(g, EditingCommand.Copy));
keymap.Cut.ForEach(g => _editingCommands.Add(g, EditingCommand.Cut));
keymap.Paste.ForEach(g => _editingCommands.Add(g, EditingCommand.Paste));
_editingCommands.Add(new KeyGesture(KeyCode.Insert), EditingCommand.ToggleOverstrike);
keymap.DeleteWholeLine.ForEach(g => _editingCommands.Add(g, EditingCommand.DeleteLine));
_editingCommands.Add(new KeyGesture(KeyCode.I, keymap.CommandModifiers), EditingCommand.IndentSelection);
keymap.Undo.ForEach(g => _editingCommands.Add(g, EditingCommand.Undo));
keymap.Redo.ForEach(g => _editingCommands.Add(g, EditingCommand.Redo));
}
internal TextArea TextArea { get; }
internal void OnKeyDown(KeyDownEvent e)
{
if (TextArea?.Document == null)
return;
EditingCommand command = GetEditingCommand(e);
switch (command)
{
case EditingCommand.Delete:
Delete();
e.StopPropagation();
break;
case EditingCommand.Copy:
Copy();
e.StopPropagation();
break;
case EditingCommand.Cut:
Cut();
e.StopPropagation();
break;
case EditingCommand.Paste:
Paste();
e.StopPropagation();
break;
case EditingCommand.DeleteNextWord:
DeleteNextWord();
e.StopPropagation();
break;
case EditingCommand.Backspace:
Backspace();
e.StopPropagation();
break;
case EditingCommand.DeletePreviousWord:
DeletePreviousWord();
e.StopPropagation();
break;
case EditingCommand.EnterParagraphBreak:
EnterParagraphBreak();
e.StopPropagation();
break;
case EditingCommand.EnterLineBreak:
EnterLineBreak();
e.StopPropagation();
break;
case EditingCommand.TabForward:
TabForward();
e.StopPropagation();
break;
case EditingCommand.TabBackward:
TabBackward();
e.StopPropagation();
break;
case EditingCommand.ToggleOverstrike:
ToggleOverstrike();
e.StopPropagation();
break;
case EditingCommand.DeleteLine:
DeleteLine();
e.StopPropagation();
break;
case EditingCommand.IndentSelection:
IndentSelection();
e.StopPropagation();
break;
case EditingCommand.Undo:
ExecuteUndo();
e.StopPropagation();
break;
case EditingCommand.Redo:
ExecuteRedo();
e.StopPropagation();
break;
}
}
EditingCommand GetEditingCommand(KeyDownEvent e)
{
KeyGesture keyGesture = new KeyGesture(e.keyCode, e.GetKeyModifiers());
if (_editingCommands.TryGetValue(keyGesture, out EditingCommand command))
return command;
return EditingCommand.None;
}
void Paste()
{
OnPaste(TextArea);
}
void Cut()
{
OnCut(TextArea);
}
void IndentSelection()
{
OnIndentSelection(TextArea);
}
void DeleteLine()
{
OnDeleteLine(TextArea);
}
void ToggleOverstrike()
{
OnToggleOverstrike(TextArea);
}
void TabBackward()
{
OnShiftTab(TextArea);
}
void TabForward()
{
OnTab(TextArea);
}
void EnterLineBreak()
{
OnEnter(TextArea);
}
void EnterParagraphBreak()
{
OnEnter(TextArea);
}
void DeletePreviousWord()
{
OnDelete(TextArea, CaretMovementType.WordLeft);
}
void Backspace()
{
OnDelete(TextArea, CaretMovementType.Backspace);
}
void Copy()
{
OnCopy(TextArea);
}
void Delete()
{
OnDelete(TextArea, CaretMovementType.CharRight);
}
void DeleteNextWord()
{
OnDelete(TextArea, CaretMovementType.WordRight);
}
#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, TextArea textArea,
DefaultSegmentType defaultSegmentType)
{
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();
}
}
/// <summary>
/// Calls transformLine on all writable segment in the selected range.
/// </summary>
private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, TextArea textArea,
DefaultSegmentType defaultSegmentType)
{
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();
}
}
#endregion
#region EnterLineBreak
private static void OnEnter(TextArea textArea)
{
if (textArea != null && textArea.IsFocused)
{
textArea.PerformTextInput("\n");
}
}
#endregion
#region Tab
private static void OnTab(TextArea textArea)
{
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();
}
}
private static void OnShiftTab(TextArea textArea)
{
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);
}
}
}, textArea, DefaultSegmentType.CurrentLine);
}
#endregion
#region Delete
static void OnDelete(TextArea textArea, CaretMovementType caretMovement)
{
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();
}
}
internal static bool CanDelete(TextArea textArea)
{
if (textArea?.Document != null)
{
return true;
}
return false;
}
#endregion
#region Clipboard commands
internal static bool CanCut(TextArea textArea)
{
// HasSomethingSelected for copy and cut commands
if (textArea?.Document != null)
{
return (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly;
}
return false;
}
internal static bool CanCopy(TextArea textArea)
{
// HasSomethingSelected for copy and cut commands
if (textArea?.Document != null)
{
return textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty;
}
return false;
}
internal static void OnCopy(TextArea textArea)
{
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);
}
}
}
internal static void OnCut(TextArea textArea)
{
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();
}
}
private static bool CopySelectedText(TextArea textArea)
{
var text = textArea.Selection.GetText();
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
SetClipboardText(text);
textArea.OnTextCopied(new TextArea.TextEventArgs(text));
return true;
}
private static void SetClipboardText(string text)
{
try
{
GUIUtility.systemCopyBuffer = text;
}
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 TextArea.TextEventArgs(text));
return true;
}
internal static bool CanPaste(TextArea textArea)
{
if (textArea?.Document != null)
{
return textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset);
}
return false;
}
internal static void OnPaste(TextArea textArea)
{
if (textArea?.Document != null)
{
textArea.Document.BeginUpdate();
string text = null;
try
{
text = GUIUtility.systemCopyBuffer;
}
catch (Exception)
{
textArea.Document.EndUpdate();
return;
}
if (text == null)
{
textArea.Document.EndUpdate();
return;
}
text = GetTextToPaste(text, textArea);
if (!string.IsNullOrEmpty(text))
{
textArea.ReplaceSelectionWithText(text);
}
textArea.Caret.BringCaretToView();
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(TextArea textArea)
{
if (textArea != null && textArea.Options.AllowToggleOverstrikeMode)
{
//textArea.OverstrikeMode = !textArea.OverstrikeMode;
}
}
#endregion
#region DeleteLine
private static void OnDeleteLine(TextArea textArea)
{
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();
}
}
#endregion
#region Remove..Whitespace / Convert Tabs-Spaces
private static void OnRemoveLeadingWhitespace(TextArea textArea)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, textArea, DefaultSegmentType.WholeDocument);
}
private static void OnRemoveTrailingWhitespace(TextArea textArea)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line));
}, textArea, DefaultSegmentType.WholeDocument);
}
private static void OnConvertTabsToSpaces(TextArea textArea)
{
TransformSelectedSegments(ConvertTabsToSpaces, textArea, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingTabsToSpaces(TextArea textArea)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, textArea, 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(TextArea textArea)
{
TransformSelectedSegments(ConvertSpacesToTabs, textArea, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingSpacesToTabs(TextArea textArea)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, textArea, 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, TextArea textArea)
{
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);
}, textArea, DefaultSegmentType.WholeDocument);
}
private static void OnConvertToUpperCase(TextArea textArea)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, textArea);
}
private static void OnConvertToLowerCase(object target, TextArea textArea)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, textArea);
}
private static void OnConvertToTitleCase(object target, TextArea textArea)
{
throw new NotSupportedException();
//ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args);
}
private static void OnInvertCase(object target, TextArea textArea)
{
ConvertCase(InvertCase, textArea);
}
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
#region Undo / Redo
private UndoStack GetUndoStack()
{
var document = TextArea.Document;
return document?.UndoStack;
}
internal void ExecuteUndo()
{
var undoStack = GetUndoStack();
if (undoStack != null)
{
if (undoStack.CanUndo)
{
undoStack.Undo();
TextArea.Caret.BringCaretToView();
}
}
}
internal bool CanExecuteUndo()
{
var undoStack = GetUndoStack();
if (undoStack != null)
{
return undoStack.CanUndo;
}
return false;
}
internal void ExecuteRedo()
{
var undoStack = GetUndoStack();
if (undoStack != null)
{
if (undoStack.CanRedo)
{
undoStack.Redo();
TextArea.Caret.BringCaretToView();
}
}
}
internal bool CanExecuteRedo()
{
var undoStack = GetUndoStack();
if (undoStack != null)
{
return undoStack.CanRedo;
}
return false;
}
#endregion
private static void OnIndentSelection(TextArea textArea)
{
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();
}
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 6c67e63daeb772a4ca7887f421833c0c
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,61 @@
namespace Unity.CodeEditor.Editing
{
internal enum EditingCommand
{
None,
Delete,
Copy,
Cut,
Paste,
DeleteNextWord,
Backspace,
DeletePreviousWord,
EnterParagraphBreak,
EnterLineBreak,
TabForward,
TabBackward,
ToggleOverstrike,
DeleteLine,
IndentSelection,
Undo,
Redo,
}
internal enum CaretNavigationCommand
{
None,
MoveLeftByCharacter,
SelectLeftByCharacter,
MoveRightByCharacter,
SelectRightByCharacter,
MoveLeftByWord,
SelectLeftByWord,
MoveRightByWord,
SelectRightByWord,
MoveUpByLine,
SelectUpByLine,
MoveDownByLine,
SelectDownByLine,
MoveDownByPage,
SelectDownByPage,
MoveUpByPage,
SelectUpByPage,
MoveToLineStart,
SelectToLineStart,
MoveToLineEnd,
SelectToLineEnd,
MoveToDocumentStart,
SelectToDocumentStart,
MoveToDocumentEnd,
SelectToDocumentEnd,
BoxSelectLeftByCharacter,
BoxSelectRightByCharacter,
BoxSelectLeftByWord,
BoxSelectRightByWord,
BoxSelectUpByLine,
BoxSelectDownByLine,
BoxSelectToLineStart,
BoxSelectToLineEnd,
SelectAll,
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 2c0888ba8c8e4b2889752ee1eb9b3e9e
timeCreated: 1711364373
@@ -0,0 +1,92 @@
// 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.Runtime.CompilerServices;
using Unity.CodeEditor.Document;
using Unity.CodeEditor.Utils;
namespace Unity.CodeEditor.Editing
{
sealed class EmptySelection : Selection
{
internal EmptySelection(TextArea textArea) : base(textArea)
{
}
internal override Selection UpdateOnDocumentChange(DocumentChangeEventArgs e)
{
return this;
}
internal override TextViewPosition StartPosition => new TextViewPosition(TextLocation.Empty);
internal override TextViewPosition EndPosition => new TextViewPosition(TextLocation.Empty);
internal override ISegment SurroundingSegment => null;
internal override Selection SetEndpoint(TextViewPosition endPosition)
{
throw new NotSupportedException();
}
internal override Selection StartSelectionOrSetEndpoint(TextViewPosition startPosition, TextViewPosition endPosition)
{
var document = TextArea.Document;
if (document == null)
throw ThrowUtil.NoDocumentAssigned();
return Create(TextArea, startPosition, endPosition);
}
internal override IEnumerable<SelectionSegment> Segments => Empty<SelectionSegment>.Array;
internal override string GetText()
{
return string.Empty;
}
internal override void ReplaceSelectionWithText(string newText)
{
if (newText == null)
throw new ArgumentNullException(nameof(newText));
newText = AddSpacesIfRequired(newText, TextArea.Caret.Position, TextArea.Caret.Position);
if (newText.Length > 0)
{
if (TextArea.ReadOnlySectionProvider.CanInsert(TextArea.Caret.Offset))
{
TextArea.Document.Insert(TextArea.Caret.Offset, newText);
}
}
TextArea.Caret.VisualColumn = -1;
}
internal override int Length => 0;
// Use reference equality because there's only one EmptySelection per text area.
public override int GetHashCode()
{
return RuntimeHelpers.GetHashCode(this);
}
public override bool Equals(object obj)
{
return this == obj;
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: d6b614bb8cf04cbe9ffd8626c062bd78
timeCreated: 1710866978
@@ -0,0 +1,46 @@
// 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.Collections.Generic;
using Unity.CodeEditor.Document;
namespace Unity.CodeEditor.Editing
{
/// <summary>
/// Determines whether the document can be modified.
/// </summary>
internal interface IReadOnlySectionProvider
{
/// <summary>
/// Gets whether insertion is possible at the specified offset.
/// </summary>
bool CanInsert(int offset);
/// <summary>
/// Gets the deletable segments inside the given segment.
/// </summary>
/// <remarks>
/// All segments in the result must be within the given segment, and they must be returned in order
/// (e.g. if two segments are returned, EndOffset of first segment must be less than StartOffset of second segment).
///
/// For replacements, the last segment being returned will be replaced with the new text. If an empty list is returned,
/// no replacement will be done.
/// </remarks>
IEnumerable<ISegment> GetDeletableSegments(ISegment segment);
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: bf56682e6df72134b81925661287a663
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,208 @@
// 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 Unity.CodeEditor.Document;
using Unity.CodeEditor.Rendering;
using Unity.CodeEditor.Text;
using Unity.CodeEditor.Utils;
using UnityEngine;
using UnityEngine.UIElements;
namespace Unity.CodeEditor.Editing
{
/// <summary>
/// Margin showing line numbers.
/// </summary>
internal class LineNumberMargin : AbstractMargin
{
private AnchorSegment _selectionStart;
private bool _selecting;
internal float LeftHorizontalMargin { get; set; } = 5;
internal float RightHorizontalMargin { get; set; } = 15;
private readonly IMGUIContainer _imguiContainer;
private readonly VisualElement _separator;
private float _textAreaWidth;
private readonly List<LineNumberEntry> _lineEntries = new List<LineNumberEntry>();
private struct LineNumberEntry
{
internal GUIContent Content;
internal float Y;
}
internal LineNumberMargin() : base()
{
style.position = Position.Relative;
style.overflow = Overflow.Hidden;
_imguiContainer = new IMGUIContainer(OnGUI);
_imguiContainer.pickingMode = PickingMode.Ignore;
_imguiContainer.focusable = false;
_imguiContainer.style.position = Position.Absolute;
_imguiContainer.style.left = 0;
_imguiContainer.style.top = 0;
_imguiContainer.style.right = 0;
_imguiContainer.style.bottom = 0;
Add(_imguiContainer);
_separator = new VisualElement();
_separator.style.position = Position.Absolute;
_separator.style.right = 7;
_separator.style.top = 0;
_separator.style.bottom = 0;
_separator.style.width = 1;
Add(_separator);
}
private void OnGUI()
{
if (Event.current.type != EventType.Repaint)
return;
var textView = TextView;
if (textView == null)
return;
var paragraphProperties = CreateTextParagraphProperties();
var guiStyle = paragraphProperties.GUIStyle;
foreach (var entry in _lineEntries)
{
var rect = new Rect(0, entry.Y, _textAreaWidth, guiStyle.lineHeight);
guiStyle.Draw(rect, entry.Content, false, false, false, false);
}
}
private void UpdateLineNumbers()
{
var textView = TextView;
if (textView == null || !textView.VisualLinesValid)
return;
UpdateWidth();
_separator.style.backgroundColor = new StyleColor(textView.LineNumbersSeparatorColor);
_lineEntries.Clear();
foreach (var line in textView.VisualLines)
{
var lineNumber = line.FirstDocumentLine.LineNumber;
var y = line.GetTextLineVisualYPosition(line.TextLines[0], VisualYPosition.TextTop);
_lineEntries.Add(new LineNumberEntry
{
Content = new GUIContent(lineNumber.ToString(CultureInfo.CurrentCulture)),
Y = Mathf.Round(y - textView.VerticalOffset),
});
}
_imguiContainer.MarkDirtyRepaint();
}
private void UpdateWidth()
{
var textView = TextView;
if (textView == null) return;
TextFormatter textFormatter = new TextFormatter();
var paragraphProperties = CreateTextParagraphProperties();
var size = textFormatter.CalcSize(
new string('9', MaxLineNumberLength),
paragraphProperties
);
_textAreaWidth = size.x + LeftHorizontalMargin;
style.width = _textAreaWidth + RightHorizontalMargin;
}
/// <inheritdoc/>
protected override void OnTextViewChanged(TextView oldTextView, TextView newTextView)
{
if (oldTextView != null)
{
oldTextView.VisualLinesChanged -= TextViewVisualLinesChanged;
}
base.OnTextViewChanged(oldTextView, newTextView);
if (newTextView != null)
{
newTextView.VisualLinesChanged += TextViewVisualLinesChanged;
}
UpdateLineNumbers();
}
/// <inheritdoc/>
protected override void OnDocumentChanged(TextDocument oldDocument, TextDocument newDocument)
{
if (oldDocument != null)
{
TextDocumentWeakEventManager.LineCountChanged.RemoveHandler(oldDocument, OnDocumentLineCountChanged);
}
base.OnDocumentChanged(oldDocument, newDocument);
if (newDocument != null)
{
TextDocumentWeakEventManager.LineCountChanged.AddHandler(newDocument, OnDocumentLineCountChanged);
}
OnDocumentLineCountChanged();
}
private void OnDocumentLineCountChanged(object sender, EventArgs e)
{
OnDocumentLineCountChanged();
}
void TextViewVisualLinesChanged(object sender, EventArgs e)
{
UpdateLineNumbers();
}
protected int MaxLineNumberLength = 1;
private void OnDocumentLineCountChanged()
{
var documentLineCount = Document?.LineCount ?? 1;
var newLength = documentLineCount.ToString(CultureInfo.CurrentCulture).Length;
if (newLength < 2)
newLength = 2;
if (newLength != MaxLineNumberLength)
{
MaxLineNumberLength = newLength;
UpdateLineNumbers();
}
}
private TextParagraphProperties CreateTextParagraphProperties()
{
TextParagraphProperties result = new TextParagraphProperties(
false,
0,
_textView.Font,
_textView.FontSize,
_textView.LineNumbersForegroundColor);
result.GUIStyle.alignment = UnityEngine.TextAnchor.MiddleRight;
return result;
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: dac86db891f44e408597165f056cd0a4
timeCreated: 1711883592
@@ -0,0 +1,65 @@
// 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.Linq;
using Unity.CodeEditor.Document;
using Unity.CodeEditor.Utils;
namespace Unity.CodeEditor.Editing
{
/// <summary>
/// <see cref="IReadOnlySectionProvider"/> that has no read-only sections; all text is editable.
/// </summary>
sealed class NoReadOnlySections : IReadOnlySectionProvider
{
internal static readonly NoReadOnlySections Instance = new NoReadOnlySections();
public bool CanInsert(int offset)
{
return true;
}
public IEnumerable<ISegment> GetDeletableSegments(ISegment segment)
{
if (segment == null)
throw new ArgumentNullException(nameof(segment));
// the segment is always deletable
return ExtensionMethods.Sequence(segment);
}
}
/// <summary>
/// <see cref="IReadOnlySectionProvider"/> that completely disables editing.
/// </summary>
sealed class ReadOnlySectionDocument : IReadOnlySectionProvider
{
internal static readonly ReadOnlySectionDocument Instance = new ReadOnlySectionDocument();
public bool CanInsert(int offset)
{
return false;
}
public IEnumerable<ISegment> GetDeletableSegments(ISegment segment)
{
return Enumerable.Empty<ISegment>();
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 078b750ce38ab92439fffe8192aa866f
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,415 @@
// 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.Linq;
using System.Text;
using Unity.CodeEditor.Document;
using Unity.CodeEditor.Utils;
using UnityEngine;
namespace Unity.CodeEditor.Editing
{
/// <summary>
/// Rectangular selection ("box selection").
/// </summary>
internal sealed class RectangleSelection : Selection
{
/*
#region Commands
/// <summary>
/// Expands the selection left by one character, creating a rectangular selection.
/// Key gesture: Alt+Shift+Left
/// </summary>
internal static readonly RoutedCommand BoxSelectLeftByCharacter = new RoutedCommand(nameof(BoxSelectLeftByCharacter));
/// <summary>
/// Expands the selection right by one character, creating a rectangular selection.
/// Key gesture: Alt+Shift+Right
/// </summary>
internal static readonly RoutedCommand BoxSelectRightByCharacter = new RoutedCommand(nameof(BoxSelectRightByCharacter));
/// <summary>
/// Expands the selection left by one word, creating a rectangular selection.
/// Key gesture: Ctrl+Alt+Shift+Left
/// </summary>
internal static readonly RoutedCommand BoxSelectLeftByWord = new RoutedCommand(nameof(BoxSelectLeftByWord));
/// <summary>
/// Expands the selection right by one word, creating a rectangular selection.
/// Key gesture: Ctrl+Alt+Shift+Right
/// </summary>
internal static readonly RoutedCommand BoxSelectRightByWord = new RoutedCommand(nameof(BoxSelectRightByWord));
/// <summary>
/// Expands the selection up by one line, creating a rectangular selection.
/// Key gesture: Alt+Shift+Up
/// </summary>
internal static readonly RoutedCommand BoxSelectUpByLine = new RoutedCommand(nameof(BoxSelectUpByLine));
/// <summary>
/// Expands the selection down by one line, creating a rectangular selection.
/// Key gesture: Alt+Shift+Down
/// </summary>
internal static readonly RoutedCommand BoxSelectDownByLine = new RoutedCommand(nameof(BoxSelectDownByLine));
/// <summary>
/// Expands the selection to the start of the line, creating a rectangular selection.
/// Key gesture: Alt+Shift+Home
/// </summary>
internal static readonly RoutedCommand BoxSelectToLineStart = new RoutedCommand(nameof(BoxSelectToLineStart));
/// <summary>
/// Expands the selection to the end of the line, creating a rectangular selection.
/// Key gesture: Alt+Shift+End
/// </summary>
internal static readonly RoutedCommand BoxSelectToLineEnd = new RoutedCommand(nameof(BoxSelectToLineEnd));
#endregion
*/
private TextDocument _document;
private readonly int _startLine;
private readonly int _endLine;
private readonly float _startXPos;
private readonly float _endXPos;
private readonly int _topLeftOffset;
private readonly int _bottomRightOffset;
private readonly List<SelectionSegment> _segments = new List<SelectionSegment>();
#region Constructors
/// <summary>
/// Creates a new rectangular selection.
/// </summary>
internal RectangleSelection(TextArea textArea, TextViewPosition start, TextViewPosition end)
: base(textArea)
{
InitDocument();
_startLine = start.Line;
_endLine = end.Line;
_startXPos = GetXPos(textArea, start);
_endXPos = GetXPos(textArea, end);
CalculateSegments();
_topLeftOffset = _segments.First().StartOffset;
_bottomRightOffset = _segments.Last().EndOffset;
StartPosition = start;
EndPosition = end;
}
private RectangleSelection(TextArea textArea, int startLine, float startXPos, TextViewPosition end)
: base(textArea)
{
InitDocument();
_startLine = startLine;
_endLine = end.Line;
_startXPos = startXPos;
_endXPos = GetXPos(textArea, end);
CalculateSegments();
_topLeftOffset = _segments.First().StartOffset;
_bottomRightOffset = _segments.Last().EndOffset;
StartPosition = GetStart();
EndPosition = end;
}
private RectangleSelection(TextArea textArea, TextViewPosition start, int endLine, float endXPos)
: base(textArea)
{
InitDocument();
_startLine = start.Line;
_endLine = endLine;
_startXPos = GetXPos(textArea, start);
_endXPos = endXPos;
CalculateSegments();
_topLeftOffset = _segments.First().StartOffset;
_bottomRightOffset = _segments.Last().EndOffset;
StartPosition = start;
EndPosition = GetEnd();
}
private void InitDocument()
{
_document = TextArea.Document;
if (_document == null)
throw ThrowUtil.NoDocumentAssigned();
}
private static float GetXPos(TextArea textArea, TextViewPosition pos)
{
var documentLine = textArea.Document.GetLineByNumber(pos.Line);
var visualLine = textArea.TextView.GetOrConstructVisualLine(documentLine);
var vc = visualLine.ValidateVisualColumn(pos, true);
var textLine = visualLine.GetTextLine(vc, pos.IsAtEndOfLine);
return visualLine.GetTextLineVisualXPosition(textLine, vc);
}
private void CalculateSegments()
{
var nextLine = _document.GetLineByNumber(Math.Min(_startLine, _endLine));
do
{
var vl = TextArea.TextView.GetOrConstructVisualLine(nextLine);
var startVc = vl.GetVisualColumn(new Vector2(_startXPos, 0), true);
var endVc = vl.GetVisualColumn(new Vector2(_endXPos, 0), true);
var baseOffset = vl.FirstDocumentLine.Offset;
var startOffset = baseOffset + vl.GetRelativeOffset(startVc);
var endOffset = baseOffset + vl.GetRelativeOffset(endVc);
_segments.Add(new SelectionSegment(startOffset, startVc, endOffset, endVc));
nextLine = vl.LastDocumentLine.NextLine;
} while (nextLine != null && nextLine.LineNumber <= Math.Max(_startLine, _endLine));
}
private TextViewPosition GetStart()
{
var segment = (_startLine < _endLine ? _segments.First() : _segments.Last());
if (_startXPos < _endXPos)
{
return new TextViewPosition(_document.GetLocation(segment.StartOffset), segment.StartVisualColumn);
}
return new TextViewPosition(_document.GetLocation(segment.EndOffset), segment.EndVisualColumn);
}
private TextViewPosition GetEnd()
{
var segment = (_startLine < _endLine ? _segments.Last() : _segments.First());
if (_startXPos < _endXPos)
{
return new TextViewPosition(_document.GetLocation(segment.EndOffset), segment.EndVisualColumn);
}
return new TextViewPosition(_document.GetLocation(segment.StartOffset), segment.StartVisualColumn);
}
#endregion
/// <inheritdoc/>
internal override string GetText()
{
var b = new StringBuilder();
foreach (var s in Segments)
{
if (b.Length > 0)
b.AppendLine();
b.Append(_document.GetText(s));
}
return b.ToString();
}
/// <inheritdoc/>
internal override Selection StartSelectionOrSetEndpoint(TextViewPosition startPosition, TextViewPosition endPosition)
{
return SetEndpoint(endPosition);
}
/// <inheritdoc/>
internal override int Length
{
get
{
return Segments.Sum(s => s.Length);
}
}
/// <inheritdoc/>
internal override bool EnableVirtualSpace => true;
/// <inheritdoc/>
internal override ISegment SurroundingSegment => new SimpleSegment(_topLeftOffset, _bottomRightOffset - _topLeftOffset);
/// <inheritdoc/>
internal override IEnumerable<SelectionSegment> Segments => _segments;
/// <inheritdoc/>
internal override TextViewPosition StartPosition { get; }
/// <inheritdoc/>
internal override TextViewPosition EndPosition { get; }
/// <inheritdoc/>
public override bool Equals(object obj)
{
var r = obj as RectangleSelection;
// ReSharper disable CompareOfFloatsByEqualityOperator
return r != null && r.TextArea == TextArea
&& r._topLeftOffset == _topLeftOffset && r._bottomRightOffset == _bottomRightOffset
&& r._startLine == _startLine && r._endLine == _endLine
&& r._startXPos == _startXPos && r._endXPos == _endXPos;
// ReSharper restore CompareOfFloatsByEqualityOperator
}
/// <inheritdoc/>
public override int GetHashCode()
{
return _topLeftOffset ^ _bottomRightOffset;
}
/// <inheritdoc/>
internal override Selection SetEndpoint(TextViewPosition endPosition)
{
return new RectangleSelection(TextArea, _startLine, _startXPos, endPosition);
}
private int GetVisualColumnFromXPos(int line, float xPos)
{
var vl = TextArea.TextView.GetOrConstructVisualLine(TextArea.Document.GetLineByNumber(line));
return vl.GetVisualColumn(new Vector2(xPos, 0), true);
}
/// <inheritdoc/>
internal override Selection UpdateOnDocumentChange(DocumentChangeEventArgs e)
{
var newStartLocation = TextArea.Document.GetLocation(e.GetNewOffset(_topLeftOffset, AnchorMovementType.AfterInsertion));
var newEndLocation = TextArea.Document.GetLocation(e.GetNewOffset(_bottomRightOffset, AnchorMovementType.BeforeInsertion));
return new RectangleSelection(TextArea,
new TextViewPosition(newStartLocation, GetVisualColumnFromXPos(newStartLocation.Line, _startXPos)),
new TextViewPosition(newEndLocation, GetVisualColumnFromXPos(newEndLocation.Line, _endXPos)));
}
/// <inheritdoc/>
internal override void ReplaceSelectionWithText(string newText)
{
if (newText == null)
throw new ArgumentNullException(nameof(newText));
using (TextArea.Document.RunUpdate())
{
int insertionLength;
var firstInsertionLength = 0;
var editOffset = Math.Min(_topLeftOffset, _bottomRightOffset);
TextViewPosition pos;
if (NewLineFinder.NextNewLine(newText, 0) == SimpleSegment.Invalid)
{
// insert same text into every line
foreach (var lineSegment in Segments.Reverse())
{
ReplaceSingleLineText(TextArea, lineSegment, newText, out insertionLength);
firstInsertionLength = insertionLength;
}
pos = new TextViewPosition(_document.GetLocation(editOffset + firstInsertionLength));
TextArea.Selection = new RectangleSelection(TextArea, pos, Math.Max(_startLine, _endLine), GetXPos(TextArea, pos));
}
else
{
var lines = newText.Split(NewLineFinder.NewlineStrings, _segments.Count, StringSplitOptions.None);
for (var i = lines.Length - 1; i >= 0; i--)
{
ReplaceSingleLineText(TextArea, _segments[i], lines[i], out insertionLength);
firstInsertionLength = insertionLength;
}
pos = new TextViewPosition(_document.GetLocation(editOffset + firstInsertionLength));
TextArea.ClearSelection();
}
TextArea.Caret.Position = new TextViewPosition(Math.Max(_startLine, _endLine), pos.Column);
}
}
private void ReplaceSingleLineText(TextArea textArea, SelectionSegment lineSegment, string newText, out int insertionLength)
{
if (lineSegment.Length == 0)
{
if (newText.Length > 0 && textArea.ReadOnlySectionProvider.CanInsert(lineSegment.StartOffset))
{
newText = AddSpacesIfRequired(newText, new TextViewPosition(_document.GetLocation(lineSegment.StartOffset), lineSegment.StartVisualColumn), new TextViewPosition(_document.GetLocation(lineSegment.EndOffset), lineSegment.EndVisualColumn));
textArea.Document.Insert(lineSegment.StartOffset, newText);
}
}
else
{
var segmentsToDelete = textArea.GetDeletableSegments(lineSegment);
for (var i = segmentsToDelete.Length - 1; i >= 0; i--)
{
if (i == segmentsToDelete.Length - 1)
{
if (segmentsToDelete[i].Offset == SurroundingSegment.Offset && segmentsToDelete[i].Length == SurroundingSegment.Length)
{
newText = AddSpacesIfRequired(newText, new TextViewPosition(_document.GetLocation(lineSegment.StartOffset), lineSegment.StartVisualColumn), new TextViewPosition(_document.GetLocation(lineSegment.EndOffset), lineSegment.EndVisualColumn));
}
textArea.Document.Replace(segmentsToDelete[i], newText);
}
else
{
textArea.Document.Remove(segmentsToDelete[i]);
}
}
}
insertionLength = newText.Length;
}
/// <summary>
/// Performs a rectangular paste operation.
/// </summary>
internal static bool PerformRectangularPaste(TextArea textArea, TextViewPosition startPosition, string text, bool selectInsertedText)
{
if (textArea == null)
throw new ArgumentNullException(nameof(textArea));
if (text == null)
throw new ArgumentNullException(nameof(text));
var newLineCount = text.AsEnumerable().Count(c => c == '\n'); // TODO might not work in all cases, but single \r line endings are really rare today.
var endLocation = new TextLocation(startPosition.Line + newLineCount, startPosition.Column);
if (endLocation.Line <= textArea.Document.LineCount)
{
var endOffset = textArea.Document.GetOffset(endLocation);
if (textArea.Selection.EnableVirtualSpace || textArea.Document.GetLocation(endOffset) == endLocation)
{
var rsel = new RectangleSelection(textArea, startPosition, endLocation.Line, GetXPos(textArea, startPosition));
rsel.ReplaceSelectionWithText(text);
if (selectInsertedText && textArea.Selection is RectangleSelection)
{
var sel = (RectangleSelection)textArea.Selection;
textArea.Selection = new RectangleSelection(textArea, startPosition, sel._endLine, sel._endXPos);
}
return true;
}
}
return false;
}
// TODO: clipboard
///// <summary>
///// Gets the name of the entry in the DataObject that signals rectangle selections.
///// </summary>
//public const string RectangularSelectionDataType = "AvalonEditRectangularSelection";
//public override System.Windows.DataObject CreateDataObject(TextArea textArea)
//{
// var data = base.CreateDataObject(textArea);
// if (EditingCommandHandler.ConfirmDataFormat(textArea, data, RectangularSelectionDataType)) {
// MemoryStream isRectangle = new MemoryStream(1);
// isRectangle.WriteByte(1);
// data.SetData(RectangularSelectionDataType, isRectangle, false);
// }
// return data;
//}
/// <inheritdoc/>
public override string ToString()
{
// It's possible that ToString() gets called on old (invalid) selections, e.g. for "change from... to..." debug message
// make sure we don't crash even when the desired locations don't exist anymore.
return $"[RectangleSelection {_startLine} {_topLeftOffset} {_startXPos} to {_endLine} {_bottomRightOffset} {_endXPos}]";
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: d7f4b39ab0334bd38d1a9f3ec0f60625
timeCreated: 1710927572
@@ -0,0 +1,298 @@
// 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.Linq;
using System.Text;
using Unity.CodeEditor.Document;
using Unity.CodeEditor.Utils;
namespace Unity.CodeEditor.Editing
{
/// <summary>
/// Base class for selections.
/// </summary>
internal abstract class Selection
{
/// <summary>
/// Creates a new simple selection that selects the text from startOffset to endOffset.
/// </summary>
internal static Selection Create(TextArea textArea, int startOffset, int endOffset)
{
if (textArea == null)
throw new ArgumentNullException(nameof(textArea));
if (startOffset == endOffset)
return textArea.EmptySelection;
return new SimpleSelection(textArea,
new TextViewPosition(textArea.Document.GetLocation(startOffset)),
new TextViewPosition(textArea.Document.GetLocation(endOffset)));
}
internal static Selection Create(TextArea textArea, TextViewPosition start, TextViewPosition end)
{
if (textArea == null)
throw new ArgumentNullException(nameof(textArea));
if (textArea.Document.GetOffset(start.Location) == textArea.Document.GetOffset(end.Location) && start.VisualColumn == end.VisualColumn)
return textArea.EmptySelection;
return new SimpleSelection(textArea, start, end);
}
/// <summary>
/// Creates a new simple selection that selects the text in the specified segment.
/// </summary>
internal static Selection Create(TextArea textArea, ISegment segment)
{
if (segment == null)
throw new ArgumentNullException(nameof(segment));
return Create(textArea, segment.Offset, segment.EndOffset);
}
internal TextArea TextArea { get; }
/// <summary>
/// Constructor for Selection.
/// </summary>
protected Selection(TextArea textArea)
{
TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea));
}
/// <summary>
/// Gets the start position of the selection.
/// </summary>
internal abstract TextViewPosition StartPosition { get; }
/// <summary>
/// Gets the end position of the selection.
/// </summary>
internal abstract TextViewPosition EndPosition { get; }
/// <summary>
/// Gets the selected text segments.
/// </summary>
internal abstract IEnumerable<SelectionSegment> Segments { get; }
/// <summary>
/// Gets the smallest segment that contains all segments in this selection.
/// May return null if the selection is empty.
/// </summary>
internal abstract ISegment SurroundingSegment { get; }
/// <summary>
/// Replaces the selection with the specified text.
/// </summary>
internal abstract void ReplaceSelectionWithText(string newText);
internal string AddSpacesIfRequired(string newText, TextViewPosition start, TextViewPosition end)
{
if (EnableVirtualSpace && InsertVirtualSpaces(newText, start, end))
{
var line = TextArea.Document.GetLineByNumber(start.Line);
var lineText = TextArea.Document.GetText(line);
var vLine = TextArea.TextView.GetOrConstructVisualLine(line);
var colDiff = start.VisualColumn - vLine.VisualLengthWithEndOfLineMarker;
if (colDiff > 0)
{
var additionalSpaces = "";
if (!TextArea.Options.ConvertTabsToSpaces && lineText.Trim('\t').Length == 0)
{
var tabCount = colDiff / TextArea.Options.IndentationSize;
additionalSpaces = new string('\t', tabCount);
colDiff -= tabCount * TextArea.Options.IndentationSize;
}
additionalSpaces += new string(' ', colDiff);
return additionalSpaces + newText;
}
}
return newText;
}
private bool InsertVirtualSpaces(string newText, TextViewPosition start, TextViewPosition end)
{
return (!string.IsNullOrEmpty(newText) || !(IsInVirtualSpace(start) && IsInVirtualSpace(end)))
&& newText != "\r\n"
&& newText != "\n"
&& newText != "\r";
}
private bool IsInVirtualSpace(TextViewPosition pos)
{
return pos.VisualColumn > TextArea.TextView.GetOrConstructVisualLine(TextArea.Document.GetLineByNumber(pos.Line)).VisualLength;
}
/// <summary>
/// Updates the selection when the document changes.
/// </summary>
internal abstract Selection UpdateOnDocumentChange(DocumentChangeEventArgs e);
/// <summary>
/// Gets whether the selection is empty.
/// </summary>
internal virtual bool IsEmpty => Length == 0;
/// <summary>
/// Gets whether virtual space is enabled for this selection.
/// </summary>
internal virtual bool EnableVirtualSpace => TextArea.Options.EnableVirtualSpace;
/// <summary>
/// Gets the selection length.
/// </summary>
internal abstract int Length { get; }
/// <summary>
/// Returns a new selection with the changed end point.
/// </summary>
/// <exception cref="NotSupportedException">Cannot set endpoint for empty selection</exception>
internal abstract Selection SetEndpoint(TextViewPosition endPosition);
/// <summary>
/// If this selection is empty, starts a new selection from <paramref name="startPosition"/> to
/// <paramref name="endPosition"/>, otherwise, changes the endpoint of this selection.
/// </summary>
internal abstract Selection StartSelectionOrSetEndpoint(TextViewPosition startPosition, TextViewPosition endPosition);
/// <summary>
/// Gets whether the selection is multi-line.
/// </summary>
internal virtual bool IsMultiline
{
get
{
var surroundingSegment = SurroundingSegment;
if (surroundingSegment == null)
return false;
var start = surroundingSegment.Offset;
var end = start + surroundingSegment.Length;
var document = TextArea.Document;
if (document == null)
throw ThrowUtil.NoDocumentAssigned();
return document.GetLineByOffset(start) != document.GetLineByOffset(end);
}
}
/// <summary>
/// Gets the selected text.
/// </summary>
internal virtual string GetText()
{
var document = TextArea.Document;
if (document == null)
throw ThrowUtil.NoDocumentAssigned();
StringBuilder b = null;
string text = null;
foreach (var s in Segments)
{
if (text != null)
{
if (b == null)
b = new StringBuilder(text);
else
b.Append(text);
}
text = document.GetText(s);
}
if (b != null)
{
if (text != null) b.Append(text);
return b.ToString();
}
else
{
return text ?? string.Empty;
}
}
// TODO: html
/// <summary>
/// Creates a HTML fragment for the selected text.
/// </summary>
//public string CreateHtmlFragment(HtmlOptions options)
//{
// if (options == null)
// throw new ArgumentNullException("options");
// IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter;
// StringBuilder html = new StringBuilder();
// bool first = true;
// foreach (ISegment selectedSegment in this.Segments) {
// if (first)
// first = false;
// else
// html.AppendLine("<br>");
// html.Append(HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, selectedSegment, options));
// }
// return html.ToString();
//}
/// <inheritdoc/>
public abstract override bool Equals(object obj);
/// <inheritdoc/>
public abstract override int GetHashCode();
/// <summary>
/// Gets whether the specified offset is included in the selection.
/// </summary>
/// <returns>True, if the selection contains the offset (selection borders inclusive);
/// otherwise, false.</returns>
internal virtual bool Contains(int offset)
{
if (IsEmpty)
{
return false;
}
return SurroundingSegment.Contains(offset, 0) &&
Segments.Any(s => s.Contains(offset, 0));
}
// TODO: clipboard
///// <summary>
///// Creates a data object containing the selection's text.
///// </summary>
//public virtual DataObject CreateDataObject(TextArea textArea)
//{
// DataObject data = new DataObject();
// // Ensure we use the appropriate newline sequence for the OS
// string text = TextUtilities.NormalizeNewLines(GetText(), Environment.NewLine);
// // Enable drag/drop to Word, Notepad++ and others
// if (EditingCommandHandler.ConfirmDataFormat(textArea, data, DataFormats.UnicodeText)) {
// data.SetText(text);
// }
// // Enable drag/drop to SciTe:
// // We cannot use SetText, thus we need to use typeof(string).FullName as data format.
// // new DataObject(object) calls SetData(object), which in turn calls SetData(Type, data),
// // which then uses Type.FullName as format.
// // We immitate that behavior here as well:
// if (EditingCommandHandler.ConfirmDataFormat(textArea, data, typeof(string).FullName)) {
// data.SetData(typeof(string).FullName, text);
// }
// // Also copy text in HTML format to clipboard - good for pasting text into Word
// // or to the SharpDevelop forums.
// if (EditingCommandHandler.ConfirmDataFormat(textArea, data, DataFormats.Html)) {
// HtmlClipboard.SetHtml(data, CreateHtmlFragment(new HtmlOptions(textArea.Options)));
// }
// return data;
//}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 7289f88fb8294b549b7bc6d75d95d475
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,71 @@
// 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 Unity.CodeEditor.Rendering;
namespace Unity.CodeEditor.Editing
{
internal sealed class SelectionColorizer : ColorizingTransformer
{
private readonly TextArea _textArea;
internal SelectionColorizer(TextArea textArea)
{
_textArea = textArea ?? throw new ArgumentNullException(nameof(textArea));
}
protected override void Colorize(ITextRunConstructionContext context)
{
// if SelectionForeground is null, keep the existing foreground color
if (_textArea.SelectionForeground == null)
return;
var lineStartOffset = context.VisualLine.FirstDocumentLine.Offset;
var lineEndOffset = context.VisualLine.LastDocumentLine.Offset + context.VisualLine.LastDocumentLine.TotalLength;
foreach (var segment in _textArea.Selection.Segments)
{
var segmentStart = segment.StartOffset;
var segmentEnd = segment.EndOffset;
if (segmentEnd <= lineStartOffset)
continue;
if (segmentStart >= lineEndOffset)
continue;
int startColumn;
startColumn = segmentStart < lineStartOffset
? 0
: context.VisualLine.ValidateVisualColumn(segment.StartOffset, segment.StartVisualColumn,
_textArea.Selection.EnableVirtualSpace);
int endColumn;
if (segmentEnd > lineEndOffset)
endColumn = _textArea.Selection.EnableVirtualSpace ? int.MaxValue : context.VisualLine.VisualLengthWithEndOfLineMarker;
else
endColumn = context.VisualLine.ValidateVisualColumn(segment.EndOffset, segment.EndVisualColumn, _textArea.Selection.EnableVirtualSpace);
ChangeVisualElements(
startColumn, endColumn,
element =>
{
//element.TextRunProperties.SetForegroundBrush(_textArea.SelectionForeground);
});
}
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 3b30e6342e7149441aa64d1d4bd764b7
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,93 @@
// 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.Collections.Generic;
using Unity.CodeEditor.Rendering;
using UnityEngine;
using UnityEngine.UIElements;
namespace Unity.CodeEditor.Editing
{
internal sealed class SelectionLayer : Layer
{
private static readonly Color SelectionColor = TextEditorColors.Selection;
private readonly TextArea _textArea;
private readonly List<VisualElement> _selectionElements = new List<VisualElement>();
internal SelectionLayer(TextArea textArea) : base(textArea.TextView, KnownLayer.Selection)
{
_textArea = textArea;
TextView.VisualLinesChanged += (s, e) => InvalidateSelection();
TextView.ScrollOffsetChanged += (s, e) => InvalidateSelection();
}
internal void InvalidateSelection()
{
UpdateSelectionVisuals();
}
private void UpdateSelectionVisuals()
{
if (_textArea.Selection is EmptySelection)
{
for (int i = 0; i < _selectionElements.Count; i++)
_selectionElements[i].visible = false;
return;
}
int needed = 0;
foreach (var segment in _textArea.Selection.Segments)
{
foreach (var rect in BackgroundGeometryBuilder.GetRectsForSegment(
TextView, segment, _textArea.Selection.EnableVirtualSpace))
{
needed++;
}
}
while (_selectionElements.Count < needed)
{
var el = new VisualElement();
el.pickingMode = PickingMode.Ignore;
el.style.position = Position.Absolute;
el.style.backgroundColor = SelectionColor;
_selectionElements.Add(el);
Add(el);
}
int index = 0;
foreach (var segment in _textArea.Selection.Segments)
{
foreach (var rect in BackgroundGeometryBuilder.GetRectsForSegment(
TextView, segment, _textArea.Selection.EnableVirtualSpace))
{
var el = _selectionElements[index];
el.style.left = rect.x;
el.style.top = rect.y;
el.style.width = rect.width;
el.style.height = rect.height;
el.visible = true;
index++;
}
}
for (int i = index; i < _selectionElements.Count; i++)
_selectionElements[i].visible = false;
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: e474d6ad70f144ef80492c464c2e8d4c
timeCreated: 1710951316
@@ -0,0 +1,736 @@
// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.ComponentModel;
using System.Linq;
using Unity.CodeEditor.Document;
using Unity.CodeEditor.Utils;
using UnityEngine;
using UnityEngine.UIElements;
namespace Unity.CodeEditor.Editing
{
/// <summary>
/// Handles selection of text using the mouse.
/// </summary>
internal sealed class SelectionMouseHandler //: ITextAreaInputHandler
{
#region enum SelectionMode
private enum SelectionMode
{
/// <summary>
/// no selection (no mouse button down)
/// </summary>
None,
/// <summary>
/// left mouse button down on selection, might be normal click
/// or might be drag'n'drop
/// </summary>
PossibleDragStart,
/// <summary>
/// dragging text
/// </summary>
Drag,
/// <summary>
/// normal selection (click+drag)
/// </summary>
Normal,
/// <summary>
/// whole-word selection (double click+drag or ctrl+click+drag)
/// </summary>
WholeWord,
/// <summary>
/// whole-line selection (triple click+drag)
/// </summary>
WholeLine,
/// <summary>
/// rectangular selection (alt+click+drag)
/// </summary>
Rectangular
}
#endregion
private SelectionMode _mode;
private AnchorSegment _startWord;
private Vector2 _possibleDragStartMousePos;
private int _consecutiveClicks;
private float _lastClickTime;
private Vector2 _lastClickPosition;
#region Constructor + Attach + Detach
internal SelectionMouseHandler(TextArea textArea)
{
TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea));
}
internal TextArea TextArea { get; }
internal void Attach()
{
//TextArea.PointerPressed += TextArea_MouseLeftButtonDown;
//TextArea.PointerMoved += TextArea_MouseMove;
//TextArea.PointerReleased += TextArea_MouseLeftButtonUp;
//textArea.QueryCursor += textArea_QueryCursor;
TextArea.OptionChanged += TextArea_OptionChanged;
_enableTextDragDrop = TextArea.Options.EnableTextDragDrop;
if (_enableTextDragDrop)
{
AttachDragDrop();
}
}
internal void Detach()
{
_mode = SelectionMode.None;
//TextArea.PointerPressed -= TextArea_MouseLeftButtonDown;
//TextArea.PointerMoved -= TextArea_MouseMove;
//TextArea.PointerReleased -= TextArea_MouseLeftButtonUp;
//textArea.QueryCursor -= textArea_QueryCursor;
TextArea.OptionChanged -= TextArea_OptionChanged;
if (_enableTextDragDrop)
{
DetachDragDrop();
}
}
private void AttachDragDrop()
{
//textArea.AllowDrop = true;
//textArea.GiveFeedback += textArea_GiveFeedback;
//textArea.QueryContinueDrag += textArea_QueryContinueDrag;
//textArea.DragEnter += textArea_DragEnter;
//textArea.DragOver += textArea_DragOver;
//textArea.DragLeave += textArea_DragLeave;
//textArea.Drop += textArea_Drop;
}
private void DetachDragDrop()
{
//textArea.AllowDrop = false;
//textArea.GiveFeedback -= textArea_GiveFeedback;
//textArea.QueryContinueDrag -= textArea_QueryContinueDrag;
//textArea.DragEnter -= textArea_DragEnter;
//textArea.DragOver -= textArea_DragOver;
//textArea.DragLeave -= textArea_DragLeave;
//textArea.Drop -= textArea_Drop;
}
private bool _enableTextDragDrop;
private void TextArea_OptionChanged(object sender, PropertyChangedEventArgs e)
{
var newEnableTextDragDrop = TextArea.Options.EnableTextDragDrop;
if (newEnableTextDragDrop != _enableTextDragDrop)
{
_enableTextDragDrop = newEnableTextDragDrop;
if (newEnableTextDragDrop)
AttachDragDrop();
else
DetachDragDrop();
}
}
#endregion
#region Dropping text
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_DragEnter(object sender, DragEventArgs e)
//{
// try {
// e.Effects = GetEffect(e);
// textArea.Caret.Show();
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_DragOver(object sender, DragEventArgs e)
//{
// try {
// e.Effects = GetEffect(e);
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
//DragDropEffects GetEffect(DragEventArgs e)
//{
// if (e.Data.GetDataPresent(DataFormats.UnicodeText, true)) {
// e.Handled = true;
// int visualColumn;
// bool isAtEndOfLine;
// int offset = GetOffsetFromMousePosition(e.GetPosition(textArea.TextView), out visualColumn, out isAtEndOfLine);
// if (offset >= 0) {
// textArea.Caret.Position = new TextViewPosition(textArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine };
// textArea.Caret.DesiredXPos = double.NaN;
// if (textArea.ReadOnlySectionProvider.CanInsert(offset)) {
// if ((e.AllowedEffects & DragDropEffects.Move) == DragDropEffects.Move
// && (e.KeyStates & DragDropKeyStates.ControlKey) != DragDropKeyStates.ControlKey)
// {
// return DragDropEffects.Move;
// } else {
// return e.AllowedEffects & DragDropEffects.Copy;
// }
// }
// }
// }
// return DragDropEffects.None;
//}
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_DragLeave(object sender, DragEventArgs e)
//{
// try {
// e.Handled = true;
// if (!textArea.IsKeyboardFocusWithin)
// textArea.Caret.Hide();
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_Drop(object sender, DragEventArgs e)
//{
// try {
// DragDropEffects effect = GetEffect(e);
// e.Effects = effect;
// if (effect != DragDropEffects.None) {
// int start = textArea.Caret.Offset;
// if (mode == SelectionMode.Drag && textArea.Selection.Contains(start)) {
// Debug.WriteLine("Drop: did not drop: drop target is inside selection");
// e.Effects = DragDropEffects.None;
// } else {
// Debug.WriteLine("Drop: insert at " + start);
// var pastingEventArgs = new DataObjectPastingEventArgs(e.Data, true, DataFormats.UnicodeText);
// textArea.RaiseEvent(pastingEventArgs);
// if (pastingEventArgs.CommandCancelled)
// return;
// string text = EditingCommandHandler.GetTextToPaste(pastingEventArgs, textArea);
// if (text == null)
// return;
// bool rectangular = pastingEventArgs.DataObject.GetDataPresent(RectangleSelection.RectangularSelectionDataType);
// // Mark the undo group with the currentDragDescriptor, if the drag
// // is originating from the same control. This allows combining
// // the undo groups when text is moved.
// textArea.Document.UndoStack.StartUndoGroup(this.currentDragDescriptor);
// try {
// if (rectangular && RectangleSelection.PerformRectangularPaste(textArea, textArea.Caret.Position, text, true)) {
// } else {
// textArea.Document.Insert(start, text);
// textArea.Selection = Selection.Create(textArea, start, start + text.Length);
// }
// } finally {
// textArea.Document.UndoStack.EndUndoGroup();
// }
// }
// e.Handled = true;
// }
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
//void OnDragException(Exception ex)
//{
// // swallows exceptions during drag'n'drop or reports them incorrectly, so
// // we re-throw them later to allow the application's unhandled exception handler
// // to catch them
// textArea.Dispatcher.BeginInvoke(
// DispatcherPriority.Send,
// new Action(delegate {
// throw new DragDropException("Exception during drag'n'drop", ex);
// }));
//}
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_GiveFeedback(object sender, GiveFeedbackEventArgs e)
//{
// try {
// e.UseDefaultCursors = true;
// e.Handled = true;
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_QueryContinueDrag(object sender, QueryContinueDragEventArgs e)
//{
// try {
// if (e.EscapePressed) {
// e.Action = DragAction.Cancel;
// } else if ((e.KeyStates & DragDropKeyStates.LeftMouseButton) != DragDropKeyStates.LeftMouseButton) {
// e.Action = DragAction.Drop;
// } else {
// e.Action = DragAction.Continue;
// }
// e.Handled = true;
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
#endregion
#region Start Drag
//object currentDragDescriptor;
//void StartDrag()
//{
// // prevent nested StartDrag calls
// mode = SelectionMode.Drag;
// // mouse capture and Drag'n'Drop doesn't mix
// textArea.ReleaseMouseCapture();
// DataObject dataObject = textArea.Selection.CreateDataObject(textArea);
// DragDropEffects allowedEffects = DragDropEffects.All;
// var deleteOnMove = textArea.Selection.Segments.Select(s => new AnchorSegment(textArea.Document, s)).ToList();
// foreach (ISegment s in deleteOnMove) {
// ISegment[] result = textArea.GetDeletableSegments(s);
// if (result.Length != 1 || result[0].Offset != s.Offset || result[0].EndOffset != s.EndOffset) {
// allowedEffects &= ~DragDropEffects.Move;
// }
// }
// var copyingEventArgs = new DataObjectCopyingEventArgs(dataObject, true);
// textArea.RaiseEvent(copyingEventArgs);
// if (copyingEventArgs.CommandCancelled)
// return;
// object dragDescriptor = new object();
// this.currentDragDescriptor = dragDescriptor;
// DragDropEffects resultEffect;
// using (textArea.AllowCaretOutsideSelection()) {
// var oldCaretPosition = textArea.Caret.Position;
// try {
// Debug.WriteLine("DoDragDrop with allowedEffects=" + allowedEffects);
// resultEffect = DragDrop.DoDragDrop(textArea, dataObject, allowedEffects);
// Debug.WriteLine("DoDragDrop done, resultEffect=" + resultEffect);
// } catch (COMException ex) {
// // ignore COM errors - don't crash on badly implemented drop targets
// Debug.WriteLine("DoDragDrop failed: " + ex.ToString());
// return;
// }
// if (resultEffect == DragDropEffects.None) {
// // reset caret if drag was aborted
// textArea.Caret.Position = oldCaretPosition;
// }
// }
// this.currentDragDescriptor = null;
// if (deleteOnMove != null && resultEffect == DragDropEffects.Move && (allowedEffects & DragDropEffects.Move) == DragDropEffects.Move) {
// bool draggedInsideSingleDocument = (dragDescriptor == textArea.Document.UndoStack.LastGroupDescriptor);
// if (draggedInsideSingleDocument)
// textArea.Document.UndoStack.StartContinuedUndoGroup(null);
// textArea.Document.BeginUpdate();
// try {
// foreach (ISegment s in deleteOnMove) {
// textArea.Document.Remove(s.Offset, s.Length);
// }
// } finally {
// textArea.Document.EndUpdate();
// if (draggedInsideSingleDocument)
// textArea.Document.UndoStack.EndUndoGroup();
// }
// }
//}
#endregion
#region QueryCursor
// provide the IBeam Cursor for the text area
//void textArea_QueryCursor(object sender, QueryCursorEventArgs e)
//{
// if (!e.Handled) {
// if (mode != SelectionMode.None) {
// // during selection, use IBeam cursor even outside the text area
// e.Cursor = Cursors.IBeam;
// e.Handled = true;
// } else if (textArea.TextView.VisualLinesValid) {
// // Only query the cursor if the visual lines are valid.
// // If they are invalid, the cursor will get re-queried when the visual lines
// // get refreshed.
// Point p = e.GetPosition(textArea.TextView);
// if (p.X >= 0 && p.Y >= 0 && p.X <= textArea.TextView.ActualWidth && p.Y <= textArea.TextView.ActualHeight) {
// int visualColumn;
// bool isAtEndOfLine;
// int offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine);
// if (enableTextDragDrop && textArea.Selection.Contains(offset))
// e.Cursor = Cursors.Arrow;
// else
// e.Cursor = Cursors.IBeam;
// e.Handled = true;
// }
// }
// }
//}
#endregion
#region LeftButtonDown
internal void OnPointerPressed(PointerDownEvent e)
{
Vector2 mousePoint = GetTextViewRelativePosition(e);
if (e.button != 0)
{
if (TextArea.RightClickMovesCaret == true)
{
SetCaretOffsetToMousePosition(mousePoint);
}
}
else
{
int clickCount = ComputeClickCount(e);
_mode = SelectionMode.None;
bool isShift = (e.modifiers & EventModifiers.Shift) != 0;
bool isAlt = (e.modifiers & EventModifiers.Alt) != 0;
bool isCtrl = (e.modifiers & EventModifiers.Control) != 0
|| (e.modifiers & EventModifiers.Command) != 0;
if (_enableTextDragDrop && clickCount == 1 && !isShift)
{
var offset = GetOffsetFromMousePosition(mousePoint, out _, out _);
if (TextArea.Selection.Contains(offset))
{
_mode = SelectionMode.PossibleDragStart;
_possibleDragStartMousePos = mousePoint;
return;
}
}
var oldPosition = TextArea.Caret.Position;
SetCaretOffsetToMousePosition(mousePoint);
if (!isShift)
{
TextArea.ClearSelection();
}
if (isAlt && TextArea.Options.EnableRectangularSelection)
{
_mode = SelectionMode.Rectangular;
if (isShift && TextArea.Selection is RectangleSelection)
{
TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
}
}
else if (isCtrl && clickCount == 1)
{
_mode = SelectionMode.WholeWord;
if (isShift && !(TextArea.Selection is RectangleSelection))
{
TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
}
}
else if (e.button == 0 && clickCount == 1)
{
_mode = SelectionMode.Normal;
if (isShift && !(TextArea.Selection is RectangleSelection))
{
TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
}
}
else
{
SimpleSegment startWord;
if (clickCount == 3)
{
_mode = SelectionMode.WholeLine;
startWord = GetLineAtMousePosition(mousePoint);
}
else
{
_mode = SelectionMode.WholeWord;
startWord = GetWordAtMousePosition(mousePoint);
}
if (startWord == SimpleSegment.Invalid)
{
_mode = SelectionMode.None;
return;
}
if (isShift && !TextArea.Selection.IsEmpty)
{
if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset)
{
TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset)));
}
else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset)
{
TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset)));
}
_startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment);
}
else
{
TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset);
_startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length);
}
}
}
}
private int ComputeClickCount(PointerDownEvent e)
{
float currentTime = Time.realtimeSinceStartup;
Vector2 currentPosition = e.position;
if (currentTime - _lastClickTime < TripleClickTimeSeconds
&& Vector2.Distance(currentPosition, _lastClickPosition) < TripleClickMaxDistance)
{
_consecutiveClicks++;
}
else
{
_consecutiveClicks = 1;
}
_lastClickTime = currentTime;
_lastClickPosition = currentPosition;
return _consecutiveClicks;
}
#endregion
#region LeftButtonClick
#endregion
#region LeftButtonDoubleTap
#endregion
#region Mouse Position <-> Text coordinates
private Vector2 GetTextViewRelativePosition(IPointerEvent e)
{
return TextArea.TextView.WorldToLocal(e.position);
}
private SimpleSegment GetWordAtMousePosition(Vector2 posRelativeToTextView)
{
var textView = TextArea.TextView;
if (textView == null) return SimpleSegment.Invalid;
var pos = posRelativeToTextView;
if (pos.y < 0)
pos.y = 0;
if (pos.y > textView.Bounds.height)
pos.y = textView.Bounds.height;
pos += textView.ScrollOffset;
var line = textView.GetVisualLineFromVisualTop(pos.y);
if (line != null && line.TextLines != null)
{
var visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace);
var wordStartVc = line.GetNextCaretPosition(visualColumn + 1, LogicalDirection.Backward, CaretPositioningMode.WordStartOrSymbol, TextArea.Selection.EnableVirtualSpace);
if (wordStartVc == -1)
wordStartVc = 0;
var wordEndVc = line.GetNextCaretPosition(wordStartVc, LogicalDirection.Forward, CaretPositioningMode.WordBorderOrSymbol, TextArea.Selection.EnableVirtualSpace);
if (wordEndVc == -1)
wordEndVc = line.VisualLength;
var relOffset = line.FirstDocumentLine.Offset;
var wordStartOffset = line.GetRelativeOffset(wordStartVc) + relOffset;
var wordEndOffset = line.GetRelativeOffset(wordEndVc) + relOffset;
return new SimpleSegment(wordStartOffset, wordEndOffset - wordStartOffset);
}
else
{
return SimpleSegment.Invalid;
}
}
private SimpleSegment GetLineAtMousePosition(Vector2 posRelativeToTextView)
{
var textView = TextArea.TextView;
if (textView == null) return SimpleSegment.Invalid;
var pos = posRelativeToTextView;
if (pos.y < 0)
pos.y = 0;
if (pos.y > textView.Bounds.height)
pos.y = textView.Bounds.height;
pos += textView.ScrollOffset;
var line = textView.GetVisualLineFromVisualTop(pos.y);
return line != null && line.TextLines != null
? new SimpleSegment(line.StartOffset, line.LastDocumentLine.EndOffset - line.StartOffset)
: SimpleSegment.Invalid;
}
private int GetOffsetFromMousePosition(Vector2 mousePosition, out int visualColumn, out bool isAtEndOfLine)
{
visualColumn = 0;
var textView = TextArea.TextView;
var pos = mousePosition;
if (pos.y < 0)
pos.y = 0;
if (pos.y > textView.Bounds.height)
pos.y = textView.Bounds.height;
pos += textView.ScrollOffset;
if (pos.y >= textView.DocumentHeight)
pos.y = textView.DocumentHeight - ExtensionMethods.Epsilon;
var line = textView.GetVisualLineFromVisualTop(pos.y);
if (line != null && line.TextLines != null)
{
visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace, out isAtEndOfLine);
return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset;
}
isAtEndOfLine = false;
return -1;
}
private int GetOffsetFromMousePositionFirstTextLineOnly(Vector2 positionRelativeToTextView, out int visualColumn)
{
visualColumn = 0;
var textView = TextArea.TextView;
var pos = positionRelativeToTextView;
if (pos.y < 0)
pos.y = 0;
if (pos.y > textView.Bounds.height)
pos.y = textView.Bounds.height;
pos += textView.ScrollOffset;
if (pos.y >= textView.DocumentHeight)
pos.y = textView.DocumentHeight - ExtensionMethods.Epsilon;
var line = textView.GetVisualLineFromVisualTop(pos.y);
if (line != null && line.TextLines != null)
{
visualColumn = line.GetVisualColumn(line.TextLines.First(), pos.x, TextArea.Selection.EnableVirtualSpace);
return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset;
}
return -1;
}
#endregion
private const int MinimumHorizontalDragDistance = 2;
private const int MinimumVerticalDragDistance = 2;
private const float TripleClickTimeSeconds = 0.5f;
private const float TripleClickMaxDistance = 5f;
#region MouseMove
internal void OnPointerMoved(PointerMoveEvent e)
{
Vector2 mousePoint = GetTextViewRelativePosition(e);
if (_mode == SelectionMode.Normal || _mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine || _mode == SelectionMode.Rectangular)
{
if (TextArea.TextView.VisualLinesValid)
{
ExtendSelectionToMouse(mousePoint);
}
}
else if (_mode == SelectionMode.PossibleDragStart)
{
Vector2 mouseMovement = mousePoint - _possibleDragStartMousePos;
if (Math.Abs(mouseMovement.x) > MinimumHorizontalDragDistance
|| Math.Abs(mouseMovement.y) > MinimumVerticalDragDistance)
{
// TODO: drag
//StartDrag();
}
}
}
#endregion
#region ExtendSelection
private void SetCaretOffsetToMousePosition(Vector2 posRelativeToTextView)
{
int visualColumn;
bool isAtEndOfLine;
int offset;
if (_mode == SelectionMode.Rectangular)
{
offset = GetOffsetFromMousePositionFirstTextLineOnly(posRelativeToTextView, out visualColumn);
isAtEndOfLine = true;
}
else
{
offset = GetOffsetFromMousePosition(posRelativeToTextView, out visualColumn, out isAtEndOfLine);
}
if (offset >= 0)
{
TextArea.Caret.Position = new TextViewPosition(TextArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine };
TextArea.Caret.DesiredXPos = float.NaN;
}
}
private void ExtendSelectionToMouse(Vector2 posRelativeToTextView)
{
var oldPosition = TextArea.Caret.Position;
if (_mode == SelectionMode.Normal || _mode == SelectionMode.Rectangular)
{
SetCaretOffsetToMousePosition(posRelativeToTextView);
if (_mode == SelectionMode.Normal && TextArea.Selection is RectangleSelection)
TextArea.Selection = new SimpleSelection(TextArea, oldPosition, TextArea.Caret.Position);
else if (_mode == SelectionMode.Rectangular && !(TextArea.Selection is RectangleSelection))
TextArea.Selection = new RectangleSelection(TextArea, oldPosition, TextArea.Caret.Position);
else
TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
}
else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine)
{
var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(posRelativeToTextView) : GetWordAtMousePosition(posRelativeToTextView);
if (newWord != SimpleSegment.Invalid && _startWord != null)
{
TextArea.Selection = Selection.Create(TextArea,
Math.Min(newWord.Offset, _startWord.Offset),
Math.Max(newWord.EndOffset, _startWord.EndOffset));
TextArea.Caret.Offset = newWord.Offset < _startWord.Offset ? newWord.Offset : Math.Max(newWord.EndOffset, _startWord.EndOffset);
}
}
TextArea.Caret.BringCaretToView(5.0f);
}
#endregion
#region MouseLeftButtonUp
internal void OnPointerReleased(PointerUpEvent e)
{
if (_mode == SelectionMode.None)
return;
Vector2 mousePoint = GetTextViewRelativePosition(e);
switch (_mode)
{
case SelectionMode.PossibleDragStart:
SetCaretOffsetToMousePosition(mousePoint);
TextArea.ClearSelection();
break;
case SelectionMode.Normal:
case SelectionMode.WholeWord:
case SelectionMode.WholeLine:
case SelectionMode.Rectangular:
if (TextArea.Options.ExtendSelectionOnMouseUp)
ExtendSelectionToMouse(mousePoint);
break;
}
_mode = SelectionMode.None;
}
#endregion
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 08c7b01b22714cd0a8ff0b3d9add5c1c
timeCreated: 1710926549
@@ -0,0 +1,92 @@
// 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 Unity.CodeEditor.Document;
namespace Unity.CodeEditor.Editing
{
/// <summary>
/// Represents a selected segment.
/// </summary>
internal class SelectionSegment : ISegment
{
/// <summary>
/// Creates a SelectionSegment from two offsets.
/// </summary>
internal SelectionSegment(int startOffset, int endOffset)
{
StartOffset = Math.Min(startOffset, endOffset);
EndOffset = Math.Max(startOffset, endOffset);
StartVisualColumn = EndVisualColumn = -1;
}
/// <summary>
/// Creates a SelectionSegment from two offsets and visual columns.
/// </summary>
internal SelectionSegment(int startOffset, int startVisualColumn, int endOffset, int endVisualColumn)
{
if (startOffset < endOffset || (startOffset == endOffset && startVisualColumn <= endVisualColumn))
{
StartOffset = startOffset;
StartVisualColumn = startVisualColumn;
EndOffset = endOffset;
EndVisualColumn = endVisualColumn;
}
else
{
StartOffset = endOffset;
StartVisualColumn = endVisualColumn;
EndOffset = startOffset;
EndVisualColumn = startVisualColumn;
}
}
/// <summary>
/// Gets the start offset.
/// </summary>
internal int StartOffset { get; }
/// <summary>
/// Gets the end offset.
/// </summary>
public int EndOffset { get; }
/// <summary>
/// Gets the start visual column.
/// </summary>
internal int StartVisualColumn { get; }
/// <summary>
/// Gets the end visual column.
/// </summary>
internal int EndVisualColumn { get; }
/// <inheritdoc/>
int ISegment.Offset => StartOffset;
/// <inheritdoc/>
public int Length => EndOffset - StartOffset;
/// <inheritdoc/>
public override string ToString()
{
return $"[SelectionSegment StartOffset={StartOffset}, EndOffset={EndOffset}, StartVC={StartVisualColumn}, EndVC={EndVisualColumn}]";
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 72b0ca78cb7b28b4c966c626e0eebf77
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,169 @@
// 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 Unity.CodeEditor.Document;
using Unity.CodeEditor.Utils;
namespace Unity.CodeEditor.Editing
{
/// <summary>
/// A simple selection.
/// </summary>
internal sealed class SimpleSelection : Selection
{
private readonly TextViewPosition _start;
private readonly TextViewPosition _end;
private readonly int _startOffset;
private readonly int _endOffset;
/// <summary>
/// Creates a new SimpleSelection instance.
/// </summary>
internal SimpleSelection(TextArea textArea, TextViewPosition start, TextViewPosition end)
: base(textArea)
{
_start = start;
_end = end;
_startOffset = textArea.Document.GetOffset(start.Location);
_endOffset = textArea.Document.GetOffset(end.Location);
}
/// <inheritdoc/>
internal override IEnumerable<SelectionSegment> Segments => ExtensionMethods.Sequence(new SelectionSegment(_startOffset, _start.VisualColumn, _endOffset, _end.VisualColumn));
/// <inheritdoc/>
internal override ISegment SurroundingSegment => new SelectionSegment(_startOffset, _endOffset);
/// <inheritdoc/>
internal override void ReplaceSelectionWithText(string newText)
{
if (newText == null)
throw new ArgumentNullException(nameof(newText));
using (TextArea.Document.RunUpdate())
{
var segmentsToDelete = TextArea.GetDeletableSegments(SurroundingSegment);
for (var i = segmentsToDelete.Length - 1; i >= 0; i--)
{
if (i == segmentsToDelete.Length - 1)
{
if (segmentsToDelete[i].Offset == SurroundingSegment.Offset && segmentsToDelete[i].Length == SurroundingSegment.Length)
{
newText = AddSpacesIfRequired(newText, _start, _end);
}
if (string.IsNullOrEmpty(newText))
{
// place caret at the beginning of the selection
// ReSharper disable once ImpureMethodCallOnReadonlyValueField
TextArea.Caret.Position = _start.CompareTo(_end) <= 0 ? _start : _end;
}
else
{
// place caret so that it ends up behind the new text
TextArea.Caret.Offset = segmentsToDelete[i].EndOffset;
}
TextArea.Document.Replace(segmentsToDelete[i], newText);
}
else
{
TextArea.Document.Remove(segmentsToDelete[i]);
}
}
if (segmentsToDelete.Length != 0)
{
TextArea.ClearSelection();
}
}
}
internal override TextViewPosition StartPosition => _start;
internal override TextViewPosition EndPosition => _end;
/// <inheritdoc/>
internal override Selection UpdateOnDocumentChange(DocumentChangeEventArgs e)
{
if (e == null)
throw new ArgumentNullException(nameof(e));
int newStartOffset, newEndOffset;
if (_startOffset <= _endOffset)
{
newStartOffset = e.GetNewOffset(_startOffset);
newEndOffset = Math.Max(newStartOffset, e.GetNewOffset(_endOffset, AnchorMovementType.BeforeInsertion));
}
else
{
newEndOffset = e.GetNewOffset(_endOffset);
newStartOffset = Math.Max(newEndOffset, e.GetNewOffset(_startOffset, AnchorMovementType.BeforeInsertion));
}
return Create(
TextArea,
new TextViewPosition(TextArea.Document.GetLocation(newStartOffset), _start.VisualColumn),
new TextViewPosition(TextArea.Document.GetLocation(newEndOffset), _end.VisualColumn)
);
}
/// <inheritdoc/>
internal override bool IsEmpty => _startOffset == _endOffset && _start.VisualColumn == _end.VisualColumn;
/// <inheritdoc/>
internal override int Length => Math.Abs(_endOffset - _startOffset);
/// <inheritdoc/>
internal override Selection SetEndpoint(TextViewPosition endPosition)
{
return Create(TextArea, _start, endPosition);
}
internal override Selection StartSelectionOrSetEndpoint(TextViewPosition startPosition, TextViewPosition endPosition)
{
var document = TextArea.Document;
if (document == null)
throw ThrowUtil.NoDocumentAssigned();
return Create(TextArea, _start, endPosition);
}
/// <inheritdoc/>
public override int GetHashCode()
{
unchecked
{
return _startOffset * 27811 + _endOffset + TextArea.GetHashCode();
}
}
/// <inheritdoc/>
public override bool Equals(object obj)
{
var other = obj as SimpleSelection;
if (other == null) return false;
// ReSharper disable ImpureMethodCallOnReadonlyValueField
return _start.Equals(other._start) && _end.Equals(other._end)
&& _startOffset == other._startOffset && _endOffset == other._endOffset
&& TextArea == other.TextArea;
// ReSharper restore ImpureMethodCallOnReadonlyValueField
}
/// <inheritdoc/>
public override string ToString()
{
return "[SimpleSelection Start=" + _start + " End=" + _end + "]";
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: e9659e74fbe8f46bdaded071ce191504
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,824 @@
using System;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using Unity.CodeEditor.Document;
using Unity.CodeEditor.Indentation;
using Unity.CodeEditor.Platform;
using Unity.CodeEditor.Rendering;
using Unity.CodeEditor.Utils;
using Unity.PlasticSCM.Editor.UI;
using UnityEditor;
using UnityEngine;
using UnityEngine.UIElements;
namespace Unity.CodeEditor.Editing
{
internal class TextArea : VisualElement
{
private bool _isFocused;
private TextEditorOptions _options;
private TextDocument _document;
private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance;
private bool _rigthClickMovesCaret;
private SelectionMouseHandler _selectionMouseHandler;
private EditingCommandHandler _editingCommandHandler;
private CaretNavigationCommandHandler _caretNavigationCommandHandler;
internal EditingCommandHandler EditingCommandHandler => _editingCommandHandler;
private VisualElement _leftMarginsContainer;
internal bool IsFocused => _isFocused;
#region Caret handling on document changes
private void OnDocumentChanging(object sender, DocumentChangeEventArgs e)
{
Caret.OnDocumentChanging();
}
private void OnDocumentChanged(object sender, DocumentChangeEventArgs e)
{
Caret.OnDocumentChanged(e);
Selection = _selection.UpdateOnDocumentChange(e);
}
private void OnUpdateStarted(object sender, EventArgs e)
{
Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this));
}
private void OnUpdateFinished(object sender, EventArgs e)
{
Caret.OnDocumentUpdateFinished();
}
private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation
{
// keep textarea in weak reference because the IUndoableOperation is stored with the document
private readonly WeakReference _textAreaReference;
private readonly TextViewPosition _caretPosition;
private readonly Selection _selection;
internal RestoreCaretAndSelectionUndoAction(TextArea textArea)
{
_textAreaReference = new WeakReference(textArea);
// Just save the old caret position, no need to validate here.
// If we restore it, we'll validate it anyways.
_caretPosition = textArea.Caret.NonValidatedPosition;
_selection = textArea.Selection;
}
public void Undo()
{
var textArea = (TextArea)_textAreaReference.Target;
if (textArea != null)
{
textArea.Caret.Position = _caretPosition;
textArea.Selection = _selection;
}
}
public void Redo()
{
// redo=undo: we just restore the caret/selection state
Undo();
}
}
#endregion
#region TextView property
/// <summary>
/// Gets the text view used to display text in this text area.
/// </summary>
internal TextView TextView { get; }
#endregion
#region Document property
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
internal TextDocument Document
{
get
{
return _document;
}
set
{
TextDocument oldValue = _document;
_document = value;
OnDocumentChanged(oldValue, value);
}
}
/// <inheritdoc/>
internal event EventHandler<DocumentChangedEventArgs> DocumentChanged;
/// <summary>
/// Gets if the the document displayed by the text editor is readonly
/// </summary>
internal bool IsReadOnly
{
get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance;
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging);
TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged);
TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted);
TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished);
}
TextView.Document = newValue;
if (newValue != null)
{
TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging);
TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged);
TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted);
TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished);
MarkDirtyRepaint();
}
// Reset caret location and selection: this is necessary because the caret/selection might be invalid
// in the new document (e.g. if new document is shorter than the old document).
Caret.Location = new TextLocation(1, 1);
ClearSelection();
DocumentChanged?.Invoke(this, new DocumentChangedEventArgs(oldValue, newValue));
//CommandManager.InvalidateRequerySuggested();
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
internal TextEditorOptions Options
{
get
{
return _options;
}
set
{
TextEditorOptions oldValue = _options;
_options = value;
OnOptionsChanged(oldValue, value);
}
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
internal event PropertyChangedEventHandler OptionChanged;
private void OnOptionChanged(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged);
}
TextView.Options = newValue;
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
#endregion
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
internal TextArea() : this(new TextView())
{
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
protected TextArea(TextView textView)
{
focusable = true;
style.flexDirection = FlexDirection.Row;
style.flexGrow = 1;
style.backgroundColor = TextEditorColors.Background;
_selectionMouseHandler = new SelectionMouseHandler(this);
_editingCommandHandler = new EditingCommandHandler(this);
_caretNavigationCommandHandler = new CaretNavigationCommandHandler(this);
TextView = textView ?? throw new ArgumentNullException(nameof(textView));
Options = textView.Options;
_selection = EmptySelection = new EmptySelection(this);
textView.Services.AddService(this);
_selectionLayer = new SelectionLayer(this);
textView.InsertLayer(_selectionLayer, KnownLayer.Selection, LayerInsertionPosition.Replace);
Caret = new Caret(this);
Caret.PositionChanged += (sender, e) => RequestSelectionValidation();
Caret.PositionChanged += CaretPositionChanged;
LeftMargins.CollectionChanged += LeftMargins_CollectionChanged;
_leftMarginsContainer = new VisualElement();
_leftMarginsContainer.style.flexDirection = FlexDirection.Row;
_leftMarginsContainer.style.flexShrink = 0;
Add(_leftMarginsContainer);
Add(textView);
RegisterCallback<KeyDownEvent>(OnKeyDownEvent);
RegisterCallback<NavigationMoveEvent>(OnNavigationMoveEvent);
RegisterCallback<FocusInEvent>(OnFocusIn);
RegisterCallback<FocusOutEvent>(OnFocusOut);
RegisterCallback<PointerDownEvent>(OnPointerDownEvent);
RegisterCallback<PointerUpEvent>(OnPointerUpEvent);
RegisterCallback<PointerMoveEvent>(OnPointerMoveEvent);
}
internal void Dispose()
{
UnregisterCallback<KeyDownEvent>(OnKeyDownEvent);
UnregisterCallback<NavigationMoveEvent>(OnNavigationMoveEvent);
UnregisterCallback<FocusInEvent>(OnFocusIn);
UnregisterCallback<FocusOutEvent>(OnFocusOut);
UnregisterCallback<PointerDownEvent>(OnPointerDownEvent);
UnregisterCallback<PointerUpEvent>(OnPointerUpEvent);
UnregisterCallback<PointerMoveEvent>(OnPointerMoveEvent);
}
private void OnKeyDownEvent(KeyDownEvent e)
{
_caretNavigationCommandHandler.OnKeyDown(e);
_editingCommandHandler.OnKeyDown(e);
ProcessTextInput(e);
}
private void OnNavigationMoveEvent(NavigationMoveEvent e)
{
if (IsReadOnly)
return;
// Tab and Shift+Tab generate a NavigationMoveEvent with direction
// Next/Previous. Consuming it prevents the focus controller from
// moving focus away from the text editor.
if (e.direction == NavigationMoveEvent.Direction.Next ||
e.direction == NavigationMoveEvent.Direction.Previous)
{
e.StopPropagation();
focusController.IgnoreEvent(e);
}
}
private void OnFocusIn(FocusInEvent e)
{
OnFocus();
}
private void OnFocusOut(FocusOutEvent e)
{
OnLostFocus();
}
private void OnPointerDownEvent(PointerDownEvent e)
{
var localPos = e.localPosition;
var textViewPos = TextView.WorldToLocal(e.position);
TextView.OnPointerPressed(textViewPos);
_selectionMouseHandler.OnPointerPressed(e);
OnFocus();
this.CapturePointer(e.pointerId);
}
private void OnPointerUpEvent(PointerUpEvent e)
{
var textViewPos = TextView.WorldToLocal(e.position);
TextView.OnPointerReleased(textViewPos);
_selectionMouseHandler.OnPointerReleased(e);
this.ReleasePointer(e.pointerId);
}
private void OnPointerMoveEvent(PointerMoveEvent e)
{
if (this.HasPointerCapture(e.pointerId))
{
TextView.OnPointerMoved();
_selectionMouseHandler.OnPointerMoved(e);
}
}
#region Force caret to stay inside selection
private bool _ensureSelectionValidRequested;
private int _allowCaretOutsideSelection;
private void RequestSelectionValidation()
{
if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0)
{
_ensureSelectionValidRequested = true;
EditorDispatcher.Dispatch(EnsureSelectionValid);
}
}
/// <summary>
/// Code that updates only the caret but not the selection can cause confusion when
/// keys like 'Delete' delete the (possibly invisible) selected text and not the
/// text around the caret.
///
/// So we'll ensure that the caret is inside the selection.
/// (when the caret is not in the selection, we'll clear the selection)
///
/// This method is invoked using the Dispatcher so that code may temporarily violate this rule
/// (e.g. most 'extend selection' methods work by first setting the caret, then the selection),
/// it's sufficient to fix it after any event handlers have run.
/// </summary>
private void EnsureSelectionValid()
{
_ensureSelectionValidRequested = false;
if (_allowCaretOutsideSelection == 0)
{
if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset))
{
ClearSelection();
}
}
}
/// <summary>
/// Temporarily allows positioning the caret outside the selection.
/// Dispose the returned IDisposable to revert the allowance.
/// </summary>
/// <remarks>
/// The text area only forces the caret to be inside the selection when other events
/// have finished running (using the dispatcher), so you don't have to use this method
/// for temporarily positioning the caret in event handlers.
/// This method is only necessary if you want to run the dispatcher, e.g. if you
/// perform a drag'n'drop operation.
/// </remarks>
internal IDisposable AllowCaretOutsideSelection()
{
EditorDispatcher.VerifyMainThreadAccess();
_allowCaretOutsideSelection++;
return new CallbackOnDispose(
delegate
{
EditorDispatcher.VerifyMainThreadAccess();
_allowCaretOutsideSelection--;
RequestSelectionValidation();
});
}
#endregion
#region Properties
/// <summary>
/// Gets the Caret used for this text area.
/// </summary>
internal Caret Caret { get; }
/// <summary>
/// Scrolls the text view so that the requested line is in the middle.
/// If the textview can be scrolled.
/// </summary>
/// <param name="line">The line to scroll to.</param>
internal void ScrollToLine(int line)
{
var viewPortLines = (int)TextView.ScrollViewport.y;
if (viewPortLines < Document.LineCount)
{
ScrollToLine(line, 2, viewPortLines / 2);
}
}
/// <summary>
/// Scrolls the textview to a position with n lines above and below it.
/// </summary>
/// <param name="line">the requested line number.</param>
/// <param name="linesEitherSide">The number of lines above and below.</param>
internal void ScrollToLine(int line, int linesEitherSide)
{
ScrollToLine(line, linesEitherSide, linesEitherSide);
}
/// <summary>
/// Scrolls the textview to a position with n lines above and below it.
/// </summary>
/// <param name="line">the requested line number.</param>
/// <param name="linesAbove">The number of lines above.</param>
/// <param name="linesBelow">The number of lines below.</param>
internal void ScrollToLine(int line, int linesAbove, int linesBelow)
{
var offset = line - linesAbove;
if (offset < 0)
{
offset = 0;
}
this.TextView.MakeVisible(new Rect(1, offset, 0, 1));
offset = line + linesBelow;
if (offset >= 0)
{
this.TextView.MakeVisible(new Rect(1, offset, 0, 1));
}
}
private void CaretPositionChanged(object sender, EventArgs e)
{
// TODO: review!! ScrollToLine is not correct
/*if (TextView == null)
return;
TextView.HighlightedLine = Caret.Line;
ScrollToLine(Caret.Line, 2);*/
}
#endregion
/// <summary>
/// Gets the collection of margins displayed to the left of the text view.
/// </summary>
internal ObservableCollection<AbstractMargin> LeftMargins { get; } = new ObservableCollection<AbstractMargin>();
private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.OldItems != null)
{
foreach (var item in e.OldItems)
{
if (item is ITextViewConnect c)
c.RemoveFromTextView(TextView);
if (item is VisualElement ve)
ve.RemoveFromHierarchy();
}
}
if (e.NewItems != null)
{
foreach (var item in e.NewItems)
{
if (item is ITextViewConnect c)
c.AddToTextView(TextView);
if (item is VisualElement ve && _leftMarginsContainer != null)
_leftMarginsContainer.Add(ve);
}
}
}
/// <summary>
/// Gets/Sets an object that provides read-only sections for the text area.
/// </summary>
internal IReadOnlySectionProvider ReadOnlySectionProvider
{
get => _readOnlySectionProvider;
set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value));
}
/// <summary>
/// Determines whether caret position should be changed to the mouse position when you right click or not.
/// </summary>
internal bool RightClickMovesCaret
{
get => _rigthClickMovesCaret;
set => _rigthClickMovesCaret = value;
}
internal readonly Selection EmptySelection;
private Selection _selection;
private SelectionLayer _selectionLayer;
/// <summary>
/// Occurs when the selection has changed.
/// </summary>
internal event EventHandler SelectionChanged;
/// <summary>
/// Gets/Sets the selection in this text area.
/// </summary>
internal Selection Selection
{
get => _selection;
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
if (value.TextArea != this)
throw new ArgumentException("Cannot use a Selection instance that belongs to another text area.");
if (!Equals(_selection, value))
{
if (TextView != null)
{
var oldSegment = _selection.SurroundingSegment;
var newSegment = value.SurroundingSegment;
if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null))
{
// perf optimization:
// When a simple selection changes, don't redraw the whole selection, but only the changed parts.
var oldSegmentOffset = oldSegment.Offset;
var newSegmentOffset = newSegment.Offset;
if (oldSegmentOffset != newSegmentOffset)
{
TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset),
Math.Abs(oldSegmentOffset - newSegmentOffset));
}
var oldSegmentEndOffset = oldSegment.EndOffset;
var newSegmentEndOffset = newSegment.EndOffset;
if (oldSegmentEndOffset != newSegmentEndOffset)
{
TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset),
Math.Abs(oldSegmentEndOffset - newSegmentEndOffset));
}
}
else
{
TextView.Redraw(oldSegment);
TextView.Redraw(newSegment);
}
}
_selection = value;
_selectionLayer.InvalidateSelection();
SelectionChanged?.Invoke(this, EventArgs.Empty);
// a selection change causes commands like copy/paste/etc. to change status
//CommandManager.InvalidateRequerySuggested();
}
}
}
/// <summary>
/// Clears the current selection.
/// </summary>
internal void ClearSelection()
{
Selection = EmptySelection;
}
Color mSelectionForeground;
/// <summary>
/// Gets/Sets the foreground brush used for selected text.
/// </summary>
internal Color SelectionForeground
{
get => mSelectionForeground;
set
{
mSelectionForeground = value;
TextView.Redraw();
}
}
#region Focus Handling (Show/Hide Caret)
internal void OnFocus()
{
_isFocused = true;
Caret.Show();
}
internal void OnLostFocus()
{
_isFocused = false;
Caret.Hide();
}
void ProcessTextInput(KeyDownEvent e)
{
if (e.character != 0 && TextView.Font != null && TextView.Font.HasCharacter(e.character))
{
TextInputEventArgs inputEventArgs = new TextInputEventArgs()
{
Text = e.character.ToString(),
};
e.StopPropagation();
PerformTextInput(inputEventArgs);
}
}
#endregion
#region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText
/// <summary>
/// Occurs when the TextArea receives text input.
/// but occurs immediately before the TextArea handles the TextInput event.
/// </summary>
internal event EventHandler<TextInputEventArgs> TextEntering;
/// <summary>
/// Occurs when the TextArea receives text input.
/// but occurs immediately after the TextArea handles the TextInput event.
/// </summary>
internal event EventHandler<TextInputEventArgs> TextEntered;
/// <summary>
/// Raises the TextEntering event.
/// </summary>
protected virtual void OnTextEntering(TextInputEventArgs e)
{
TextEntering?.Invoke(this, e);
}
/// <summary>
/// Raises the TextEntered event.
/// </summary>
protected virtual void OnTextEntered(TextInputEventArgs e)
{
TextEntered?.Invoke(this, e);
}
/*protected override void OnTextInput(TextInputEventArgs e)
{
base.OnTextInput(e);
if (!e.Handled && Document != null)
{
if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f")
{
// TODO: check this
// ASCII 0x1b = ESC.
// produces a TextInput event with that old ASCII control char
// when Escape is pressed. We'll just ignore it.
// A deadkey followed by backspace causes a textinput event for the BS character.
// Similarly, some shortcuts like Alt+Space produce an empty TextInput event.
// We have to ignore those (not handle them) to keep the shortcut working.
return;
}
HideMouseCursor();
PerformTextInput(e);
e.Handled = true;
}
}*/
/// <summary>
/// Performs text input.
/// This raises the <see cref="TextEntering"/> event, replaces the selection with the text,
/// and then raises the <see cref="TextEntered"/> event.
/// </summary>
internal void PerformTextInput(string text)
{
var e = new TextInputEventArgs
{
Text = text,
};
PerformTextInput(e);
}
/// <summary>
/// Performs text input.
/// This raises the <see cref="TextEntering"/> event, replaces the selection with the text,
/// and then raises the <see cref="TextEntered"/> event.
/// </summary>
internal void PerformTextInput(TextInputEventArgs e)
{
if (e == null)
throw new ArgumentNullException(nameof(e));
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
OnTextEntering(e);
if (!e.Handled)
{
if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n")
ReplaceSelectionWithNewLine();
else
{
// TODO
//if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset)
// EditingCommands.SelectRightByCharacter.Execute(null, this);
ReplaceSelectionWithText(e.Text);
}
OnTextEntered(e);
Caret.BringCaretToView();
}
}
private void ReplaceSelectionWithNewLine()
{
var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line);
using (Document.RunUpdate())
{
ReplaceSelectionWithText(newLine);
if (IndentationStrategy != null)
{
var line = Document.GetLineByNumber(Caret.Line);
var deletable = GetDeletableSegments(line);
if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length)
{
// use indentation strategy only if the line is not read-only
IndentationStrategy.IndentLine(Document, line);
}
}
}
}
internal void ReplaceSelectionWithText(string newText)
{
if (newText == null)
throw new ArgumentNullException(nameof(newText));
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
_selection.ReplaceSelectionWithText(newText);
}
internal ISegment[] GetDeletableSegments(ISegment segment)
{
var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment);
if (deletableSegments == null)
throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null");
var array = deletableSegments.ToArray();
var lastIndex = segment.Offset;
foreach (var t in array)
{
if (t.Offset < lastIndex)
throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)");
lastIndex = t.EndOffset;
}
if (lastIndex > segment.EndOffset)
throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)");
return array;
}
#endregion
#region IndentationStrategy property
/// <summary>
/// Gets/Sets the indentation strategy used when inserting new lines.
/// </summary>
internal IIndentationStrategy IndentationStrategy { get; set; }
#endregion
internal void RemoveSelectedText()
{
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
_selection.ReplaceSelectionWithText(string.Empty);
#if DEBUG
if (!_selection.IsEmpty)
{
foreach (var s in _selection.Segments)
{
Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any());
}
}
#endif
}
/// <summary>
/// Occurs when text inside the TextArea was copied.
/// </summary>
internal event EventHandler<TextEventArgs> TextCopied;
internal void OnTextCopied(TextEventArgs e)
{
TextCopied?.Invoke(this, e);
}
/// <summary>
/// EventArgs with text.
/// </summary>
internal class TextEventArgs : EventArgs
{
/// <summary>
/// Gets the text.
/// </summary>
internal string Text { get; }
/// <summary>
/// Creates a new TextEventArgs instance.
/// </summary>
internal TextEventArgs(string text)
{
Text = text ?? throw new ArgumentNullException(nameof(text));
}
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 76f83e4befc84169b2dab9ee2cc3545f
timeCreated: 1710764446
@@ -0,0 +1,97 @@
// 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.Linq;
using Unity.CodeEditor.Document;
namespace Unity.CodeEditor.Editing
{
/// <summary>
/// Implementation for <see cref="IReadOnlySectionProvider"/> that stores the segments
/// in a <see cref="TextSegmentCollection{T}"/>.
/// </summary>
internal class TextSegmentReadOnlySectionProvider<T> : IReadOnlySectionProvider where T : TextSegment
{
/// <summary>
/// Gets the collection storing the read-only segments.
/// </summary>
internal TextSegmentCollection<T> Segments { get; }
/// <summary>
/// Creates a new TextSegmentReadOnlySectionProvider instance for the specified document.
/// </summary>
internal TextSegmentReadOnlySectionProvider(TextDocument textDocument)
{
Segments = new TextSegmentCollection<T>(textDocument);
}
/// <summary>
/// Creates a new TextSegmentReadOnlySectionProvider instance using the specified TextSegmentCollection.
/// </summary>
internal TextSegmentReadOnlySectionProvider(TextSegmentCollection<T> segments)
{
Segments = segments ?? throw new ArgumentNullException(nameof(segments));
}
/// <summary>
/// Gets whether insertion is possible at the specified offset.
/// </summary>
public virtual bool CanInsert(int offset)
{
return Segments.FindSegmentsContaining(offset)
.All(segment => segment.StartOffset >= offset || offset >= segment.EndOffset);
}
/// <summary>
/// Gets the deletable segments inside the given segment.
/// </summary>
public virtual IEnumerable<ISegment> GetDeletableSegments(ISegment segment)
{
if (segment == null)
throw new ArgumentNullException(nameof(segment));
if (segment.Length == 0 && CanInsert(segment.Offset))
{
yield return segment;
yield break;
}
var readonlyUntil = segment.Offset;
foreach (var ts in Segments.FindOverlappingSegments(segment))
{
var start = ts.StartOffset;
var end = start + ts.Length;
if (start > readonlyUntil)
{
yield return new SimpleSegment(readonlyUntil, start - readonlyUntil);
}
if (end > readonlyUntil)
{
readonlyUntil = end;
}
}
var endOffset = segment.EndOffset;
if (readonlyUntil < endOffset)
{
yield return new SimpleSegment(readonlyUntil, endOffset - readonlyUntil);
}
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: c70164c20e48fc7478fd88c1613ac05a
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant: