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,8 @@
fileFormatVersion: 2
guid: 046f41539da654ce3b0651f5979455af
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,119 @@
// 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.Document
{
/// <summary>
/// Describes a change of the document text.
/// This class is thread-safe.
/// </summary>
internal class DocumentChangeEventArgs : TextChangeEventArgs
{
/// <summary>
/// Gets the OffsetChangeMap associated with this document change.
/// </summary>
/// <remarks>The OffsetChangeMap instance is guaranteed to be frozen and thus thread-safe.</remarks>
internal OffsetChangeMap OffsetChangeMap
{
get
{
OffsetChangeMap map = OffsetChangeMapOrNull;
if (map == null)
{
// create OffsetChangeMap on demand
map = OffsetChangeMap.FromSingleElement(CreateSingleChangeMapEntry());
OffsetChangeMapOrNull = map;
}
return map;
}
}
internal OffsetChangeMapEntry CreateSingleChangeMapEntry()
{
return new OffsetChangeMapEntry(Offset, RemovalLength, InsertionLength);
}
/// <summary>
/// Gets the OffsetChangeMap, or null if the default offset map (=single replacement) is being used.
/// </summary>
internal OffsetChangeMap OffsetChangeMapOrNull { get; private set; }
/// <summary>
/// Gets the new offset where the specified offset moves after this document change.
/// </summary>
internal override int GetNewOffset(int offset, AnchorMovementType movementType = AnchorMovementType.Default)
{
if (OffsetChangeMapOrNull != null)
return OffsetChangeMapOrNull.GetNewOffset(offset, movementType);
return CreateSingleChangeMapEntry().GetNewOffset(offset, movementType);
}
/// <summary>
/// Creates a new DocumentChangeEventArgs object.
/// </summary>
internal DocumentChangeEventArgs(int offset, string removedText, string insertedText)
: this(offset, removedText, insertedText, null)
{
}
/// <summary>
/// Creates a new DocumentChangeEventArgs object.
/// </summary>
internal DocumentChangeEventArgs(int offset, string removedText, string insertedText, OffsetChangeMap offsetChangeMap)
: base(offset, removedText, insertedText)
{
SetOffsetChangeMap(offsetChangeMap);
}
/// <summary>
/// Creates a new DocumentChangeEventArgs object.
/// </summary>
internal DocumentChangeEventArgs(int offset, ITextSource removedText, ITextSource insertedText, OffsetChangeMap offsetChangeMap)
: base(offset, removedText, insertedText)
{
SetOffsetChangeMap(offsetChangeMap);
}
private void SetOffsetChangeMap(OffsetChangeMap offsetChangeMap)
{
if (offsetChangeMap != null)
{
if (!offsetChangeMap.IsFrozen)
throw new ArgumentException("The OffsetChangeMap must be frozen before it can be used in DocumentChangeEventArgs");
if (!offsetChangeMap.IsValidForDocumentChange(Offset, RemovalLength, InsertionLength))
throw new ArgumentException("OffsetChangeMap is not valid for this document change", nameof(offsetChangeMap));
OffsetChangeMapOrNull = offsetChangeMap;
}
}
/// <inheritdoc/>
internal override TextChangeEventArgs Invert()
{
OffsetChangeMap map = OffsetChangeMapOrNull;
if (map != null)
{
map = map.Invert();
map.Freeze();
}
return new DocumentChangeEventArgs(Offset, InsertedText, RemovedText, map);
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: eb0dcdae5773e44869a9ea2b87f7d8a1
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,66 @@
// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System.Diagnostics;
namespace Unity.CodeEditor.Document
{
/// <summary>
/// Describes a change to a TextDocument.
/// </summary>
internal sealed class DocumentChangeOperation : IUndoableOperationWithContext
{
private readonly TextDocument _document;
private readonly DocumentChangeEventArgs _change;
internal DocumentChangeOperation(TextDocument document, DocumentChangeEventArgs change)
{
_document = document;
_change = change;
}
public void Undo(UndoStack stack)
{
Debug.Assert(stack.State == UndoStack.StatePlayback);
stack.RegisterAffectedDocument(_document);
stack.State = UndoStack.StatePlaybackModifyDocument;
Undo();
stack.State = UndoStack.StatePlayback;
}
public void Redo(UndoStack stack)
{
Debug.Assert(stack.State == UndoStack.StatePlayback);
stack.RegisterAffectedDocument(_document);
stack.State = UndoStack.StatePlaybackModifyDocument;
Redo();
stack.State = UndoStack.StatePlayback;
}
public void Undo()
{
var map = _change.OffsetChangeMapOrNull;
_document.Replace(_change.Offset, _change.InsertionLength, _change.RemovedText, map?.Invert());
}
public void Redo()
{
_document.Replace(_change.Offset, _change.RemovalLength, _change.InsertedText, _change.OffsetChangeMapOrNull);
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 3fdd4fc558bf14e809d9ede79af274da
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,25 @@
using System;
namespace Unity.CodeEditor.Document
{
internal class DocumentChangedEventArgs : EventArgs
{
/// <summary>
/// Gets the old TextDocument.
/// </summary>
internal TextDocument OldDocument { get; private set; }
/// <summary>
/// Gets the new TextDocument.
/// </summary>
internal TextDocument NewDocument { get; private set; }
/// <summary>
/// Provides data for the <see cref="ITextEditorComponent.DocumentChanged"/> event.
/// </summary>
internal DocumentChangedEventArgs(TextDocument oldDocument, TextDocument newDocument)
{
OldDocument = oldDocument;
NewDocument = newDocument;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 719f01626c14c440c852febfcc5ecf9d
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,95 @@
// 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.
namespace Unity.CodeEditor.Document
{
// A tree node in the document line tree.
// For the purpose of the invariants, "children", "descendents", "siblings" etc. include the DocumentLine object,
// it is treated as a third child node between left and right.
partial class DocumentLine
{
internal DocumentLine Left { get; set; }
internal DocumentLine Right { get; set; }
internal DocumentLine Parent { get; set; }
internal bool Color { get; set; }
// optimization note: I tried packing color and isDeleted into a single byte field, but that
// actually increased the memory requirements. The JIT packs two bools and a byte (delimiterSize)
// into a single DWORD, but two bytes get each their own DWORD. Three bytes end up in the same DWORD, so
// apparently the JIT only optimizes for memory when there are at least three small fields.
// Currently, DocumentLine takes 36 bytes on x86 (8 byte object overhead, 3 pointers, 3 ints, and another DWORD
// for the small fields).
// TODO: a possible optimization would be to combine 'totalLength' and the small fields into a single uint.
// delimiterSize takes only two bits, the two bools take another two bits; so there's still
// 28 bits left for totalLength. 268435455 characters per line should be enough for everyone :)
/// <summary>
/// Resets the line to enable its reuse after a document rebuild.
/// </summary>
internal void ResetLine()
{
_totalLength = _delimiterLength = 0;
_isDeleted = Color = false;
Left = Right = Parent = null;
}
internal DocumentLine InitLineNode()
{
NodeTotalCount = 1;
NodeTotalLength = TotalLength;
return this;
}
internal DocumentLine LeftMost
{
get
{
DocumentLine node = this;
while (node.Left != null)
node = node.Left;
return node;
}
}
internal DocumentLine RightMost
{
get
{
DocumentLine node = this;
while (node.Right != null)
node = node.Right;
return node;
}
}
/// <summary>
/// The number of lines in this node and its child nodes.
/// Invariant:
/// nodeTotalCount = 1 + left.nodeTotalCount + right.nodeTotalCount
/// </summary>
internal int NodeTotalCount { get; set; }
/// <summary>
/// The total text length of this node and its child nodes.
/// Invariant:
/// nodeTotalLength = left.nodeTotalLength + documentLine.TotalLength + right.nodeTotalLength
/// </summary>
internal int NodeTotalLength { get; set; }
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: aba34a0d0084f48f19b98ac1c78902b5
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,279 @@
// 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 System.Globalization;
namespace Unity.CodeEditor.Document
{
/// <summary>
/// Represents a line inside a <see cref="TextDocument"/>.
/// </summary>
/// <remarks>
/// <para>
/// The <see cref="TextDocument.Lines"/> collection contains one DocumentLine instance
/// for every line in the document. This collection is read-only to user code and is automatically
/// updated to reflect the current document content.
/// </para>
/// <para>
/// Internally, the DocumentLine instances are arranged in a binary tree that allows for both efficient updates and lookup.
/// Converting between offset and line number is possible in O(lg N) time,
/// and the data structure also updates all offsets in O(lg N) whenever a line is inserted or removed.
/// </para>
/// </remarks>
internal sealed partial class DocumentLine : IDocumentLine
{
#region Constructor
#if DEBUG
// Required for thread safety check which is done only in debug builds.
// To save space, we don't store the document reference in release builds as we don't need it there.
private readonly TextDocument _document;
#endif
private bool _isDeleted;
internal DocumentLine(TextDocument document)
{
#if DEBUG
Debug.Assert(document != null);
_document = document;
#endif
}
[Conditional("DEBUG")]
private void DebugVerifyAccess()
{
#if DEBUG
_document.DebugVerifyAccess();
#endif
}
#endregion
#region Events
// /// <summary>
// /// Is raised when the line is deleted.
// /// </summary>
// public event EventHandler Deleted;
//
// /// <summary>
// /// Is raised when the line's text changes.
// /// </summary>
// public event EventHandler TextChanged;
//
// /// <summary>
// /// Raises the Deleted or TextChanged event.
// /// </summary>
// internal void RaiseChanged()
// {
// if (IsDeleted) {
// if (Deleted != null)
// Deleted(this, EventArgs.Empty);
// } else {
// if (TextChanged != null)
// TextChanged(this, EventArgs.Empty);
// }
// }
#endregion
#region Properties stored in tree
/// <summary>
/// Gets if this line was deleted from the document.
/// </summary>
public bool IsDeleted
{
get
{
DebugVerifyAccess();
return _isDeleted;
}
set => _isDeleted = value;
}
/// <summary>
/// Gets the number of this line.
/// Runtime: O(log n)
/// </summary>
/// <exception cref="InvalidOperationException">The line was deleted.</exception>
public int LineNumber
{
get
{
if (IsDeleted)
throw new InvalidOperationException();
return DocumentLineTree.GetIndexFromNode(this) + 1;
}
}
/// <summary>
/// Gets the starting offset of the line in the document's text.
/// Runtime: O(log n)
/// </summary>
/// <exception cref="InvalidOperationException">The line was deleted.</exception>
public int Offset
{
get
{
if (IsDeleted)
throw new InvalidOperationException();
return DocumentLineTree.GetOffsetFromNode(this);
}
}
/// <summary>
/// Gets the end offset of the line in the document's text (the offset before the line delimiter).
/// Runtime: O(log n)
/// </summary>
/// <exception cref="InvalidOperationException">The line was deleted.</exception>
/// <remarks>EndOffset = <see cref="Offset"/> + <see cref="Length"/>.</remarks>
public int EndOffset => Offset + Length;
#endregion
#region Length
private int _totalLength;
private byte _delimiterLength;
/// <summary>
/// Gets the length of this line. The length does not include the line delimiter. O(1)
/// </summary>
/// <remarks>This property is still available even if the line was deleted;
/// in that case, it contains the line's length before the deletion.</remarks>
public int Length
{
get
{
DebugVerifyAccess();
return _totalLength - _delimiterLength;
}
}
/// <summary>
/// Gets the length of this line, including the line delimiter. O(1)
/// </summary>
/// <remarks>This property is still available even if the line was deleted;
/// in that case, it contains the line's length before the deletion.</remarks>
public int TotalLength
{
get
{
DebugVerifyAccess();
return _totalLength;
}
// this is set by DocumentLineTree
set => _totalLength = value;
}
/// <summary>
/// <para>Gets the length of the line delimiter.</para>
/// <para>The value is 1 for single <c>"\r"</c> or <c>"\n"</c>, 2 for the <c>"\r\n"</c> sequence;
/// and 0 for the last line in the document.</para>
/// </summary>
/// <remarks>This property is still available even if the line was deleted;
/// in that case, it contains the line delimiter's length before the deletion.</remarks>
public int DelimiterLength
{
get
{
DebugVerifyAccess();
return _delimiterLength;
}
set
{
Debug.Assert(value >= 0 && value <= 2);
_delimiterLength = (byte)value;
}
}
#endregion
#region Previous / Next Line
/// <summary>
/// Gets the next line in the document.
/// </summary>
/// <returns>The line following this line, or null if this is the last line.</returns>
public DocumentLine NextLine
{
get
{
DebugVerifyAccess();
if (Right != null)
{
return Right.LeftMost;
}
DocumentLine node = this;
DocumentLine oldNode;
do
{
oldNode = node;
node = node.Parent;
// we are on the way up from the right part, don't output node again
} while (node != null && node.Right == oldNode);
return node;
}
}
/// <summary>
/// Gets the previous line in the document.
/// </summary>
/// <returns>The line before this line, or null if this is the first line.</returns>
public DocumentLine PreviousLine
{
get
{
DebugVerifyAccess();
if (Left != null)
{
return Left.RightMost;
}
DocumentLine node = this;
DocumentLine oldNode;
do
{
oldNode = node;
node = node.Parent;
// we are on the way up from the left part, don't output node again
} while (node != null && node.Left == oldNode);
return node;
}
}
IDocumentLine IDocumentLine.NextLine => NextLine;
IDocumentLine IDocumentLine.PreviousLine => PreviousLine;
#endregion
#region ToString
/// <summary>
/// Gets a string with debug output showing the line number and offset.
/// Does not include the line's text.
/// </summary>
public override string ToString()
{
if (IsDeleted)
return "[DocumentLine deleted]";
return string.Format(
CultureInfo.InvariantCulture,
"[DocumentLine Number={0} Offset={1} Length={2}]", LineNumber, Offset, Length);
}
#endregion
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: add4a8f16bfab4878bb29c08218cad07
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,782 @@
// 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.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Text;
using Unity.PlasticSCM.Editor.UI;
namespace Unity.CodeEditor.Document
{
/// <summary>
/// Data structure for efficient management of the document lines (most operations are O(lg n)).
/// This implements an augmented red-black tree.
/// See <see cref="DocumentLine"/> for the augmented data.
///
/// NOTE: The tree is never empty, initially it contains an empty line.
/// </summary>
internal sealed class DocumentLineTree : IList<DocumentLine>
{
#region Constructor
private readonly TextDocument _document;
private DocumentLine _root;
internal DocumentLineTree(TextDocument document)
{
_document = document;
var emptyLine = new DocumentLine(document);
_root = emptyLine.InitLineNode();
}
#endregion
#region Rotation callbacks
internal static void UpdateAfterChildrenChange(DocumentLine node)
{
var totalCount = 1;
var totalLength = node.TotalLength;
if (node.Left != null)
{
totalCount += node.Left.NodeTotalCount;
totalLength += node.Left.NodeTotalLength;
}
if (node.Right != null)
{
totalCount += node.Right.NodeTotalCount;
totalLength += node.Right.NodeTotalLength;
}
if (totalCount != node.NodeTotalCount
|| totalLength != node.NodeTotalLength)
{
node.NodeTotalCount = totalCount;
node.NodeTotalLength = totalLength;
if (node.Parent != null) UpdateAfterChildrenChange(node.Parent);
}
}
private static void UpdateAfterRotateLeft(DocumentLine node)
{
UpdateAfterChildrenChange(node);
// not required: rotations only happen on insertions/deletions
// -> totalCount changes -> the parent is always updated
//UpdateAfterChildrenChange(node.parent);
}
private static void UpdateAfterRotateRight(DocumentLine node)
{
UpdateAfterChildrenChange(node);
// not required: rotations only happen on insertions/deletions
// -> totalCount changes -> the parent is always updated
//UpdateAfterChildrenChange(node.parent);
}
#endregion
#region RebuildDocument
/// <summary>
/// Rebuild the tree, in O(n).
/// </summary>
internal void RebuildTree(List<DocumentLine> documentLines)
{
var nodes = new DocumentLine[documentLines.Count];
for (var i = 0; i < documentLines.Count; i++)
{
var ls = documentLines[i];
var node = ls.InitLineNode();
nodes[i] = node;
}
Debug.Assert(nodes.Length > 0);
// now build the corresponding balanced tree
var height = GetTreeHeight(nodes.Length);
Debug.WriteLine("DocumentLineTree will have height: " + height);
_root = BuildTree(nodes, 0, nodes.Length, height);
_root.Color = Black;
#if DEBUG
CheckProperties();
#endif
}
internal static int GetTreeHeight(int size)
{
if (size == 0)
return 0;
else
return GetTreeHeight(size / 2) + 1;
}
/// <summary>
/// build a tree from a list of nodes
/// </summary>
private DocumentLine BuildTree(DocumentLine[] nodes, int start, int end, int subtreeHeight)
{
Debug.Assert(start <= end);
if (start == end)
{
return null;
}
var middle = (start + end) / 2;
var node = nodes[middle];
node.Left = BuildTree(nodes, start, middle, subtreeHeight - 1);
node.Right = BuildTree(nodes, middle + 1, end, subtreeHeight - 1);
if (node.Left != null) node.Left.Parent = node;
if (node.Right != null) node.Right.Parent = node;
if (subtreeHeight == 1)
node.Color = Red;
UpdateAfterChildrenChange(node);
return node;
}
#endregion
#region GetNodeBy... / Get...FromNode
private DocumentLine GetNodeByIndex(int index)
{
Debug.Assert(index >= 0);
Debug.Assert(index < _root.NodeTotalCount);
var node = _root;
while (true)
{
if (node.Left != null && index < node.Left.NodeTotalCount)
{
node = node.Left;
}
else
{
if (node.Left != null)
{
index -= node.Left.NodeTotalCount;
}
if (index == 0)
return node;
index--;
node = node.Right;
}
}
}
internal static int GetIndexFromNode(DocumentLine node)
{
var index = node.Left?.NodeTotalCount ?? 0;
while (node.Parent != null)
{
if (node == node.Parent.Right)
{
if (node.Parent.Left != null)
index += node.Parent.Left.NodeTotalCount;
index++;
}
node = node.Parent;
}
return index;
}
private DocumentLine GetNodeByOffset(int offset)
{
Debug.Assert(offset >= 0);
Debug.Assert(offset <= _root.NodeTotalLength);
if (offset == _root.NodeTotalLength)
{
return _root.RightMost;
}
var node = _root;
while (true)
{
if (node.Left != null && offset < node.Left.NodeTotalLength)
{
node = node.Left;
}
else
{
if (node.Left != null)
{
offset -= node.Left.NodeTotalLength;
}
offset -= node.TotalLength;
if (offset < 0)
return node;
node = node.Right;
}
}
}
internal static int GetOffsetFromNode(DocumentLine node)
{
var offset = node.Left?.NodeTotalLength ?? 0;
while (node.Parent != null)
{
if (node == node.Parent.Right)
{
if (node.Parent.Left != null)
offset += node.Parent.Left.NodeTotalLength;
offset += node.Parent.TotalLength;
}
node = node.Parent;
}
return offset;
}
#endregion
#region GetLineBy
internal DocumentLine GetByNumber(int number)
{
return GetNodeByIndex(number - 1);
}
internal DocumentLine GetByOffset(int offset)
{
return GetNodeByOffset(offset);
}
#endregion
#region LineCount
internal int LineCount => _root.NodeTotalCount;
#endregion
#region CheckProperties
#if DEBUG
[Conditional("DATACONSISTENCYTEST")]
internal void CheckProperties()
{
Debug.Assert(_root.NodeTotalLength == _document.TextLength);
CheckProperties(_root);
// check red-black property:
var blackCount = -1;
CheckNodeProperties(_root, null, Red, 0, ref blackCount);
}
private void CheckProperties(DocumentLine node)
{
var totalCount = 1;
var totalLength = node.TotalLength;
if (node.Left != null)
{
CheckProperties(node.Left);
totalCount += node.Left.NodeTotalCount;
totalLength += node.Left.NodeTotalLength;
}
if (node.Right != null)
{
CheckProperties(node.Right);
totalCount += node.Right.NodeTotalCount;
totalLength += node.Right.NodeTotalLength;
}
Debug.Assert(node.NodeTotalCount == totalCount);
Debug.Assert(node.NodeTotalLength == totalLength);
}
/*
1. A node is either red or black.
2. The root is black.
3. All leaves are black. (The leaves are the NIL children.)
4. Both children of every red node are black. (So every red node must have a black parent.)
5. Every simple path from a node to a descendant leaf contains the same number of black nodes. (Not counting the leaf node.)
*/
[SuppressMessage("ReSharper", "UnusedParameter.Local")]
private void CheckNodeProperties(DocumentLine node, DocumentLine parentNode, bool parentColor, int blackCount, ref int expectedBlackCount)
{
if (node == null) return;
Debug.Assert(node.Parent == parentNode);
if (parentColor == Red)
{
Debug.Assert(node.Color == Black);
}
if (node.Color == Black)
{
blackCount++;
}
if (node.Left == null && node.Right == null)
{
// node is a leaf node:
if (expectedBlackCount == -1)
expectedBlackCount = blackCount;
else
Debug.Assert(expectedBlackCount == blackCount);
}
CheckNodeProperties(node.Left, node, node.Color, blackCount, ref expectedBlackCount);
CheckNodeProperties(node.Right, node, node.Color, blackCount, ref expectedBlackCount);
}
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal string GetTreeAsString()
{
var b = new StringBuilder();
AppendTreeToString(_root, b, 0);
return b.ToString();
}
private static void AppendTreeToString(DocumentLine node, StringBuilder b, int indent)
{
b.Append(node.Color == Red ? "RED " : "BLACK ");
b.AppendLine(node.ToString());
indent += 2;
if (node.Left != null)
{
b.Append(' ', indent);
b.Append("L: ");
AppendTreeToString(node.Left, b, indent);
}
if (node.Right != null)
{
b.Append(' ', indent);
b.Append("R: ");
AppendTreeToString(node.Right, b, indent);
}
}
#endif
#endregion
#region Insert/Remove lines
internal void RemoveLine(DocumentLine line)
{
RemoveNode(line);
line.IsDeleted = true;
}
internal DocumentLine InsertLineAfter(DocumentLine line, int totalLength)
{
var newLine = new DocumentLine(_document) {TotalLength = totalLength};
InsertAfter(line, newLine);
return newLine;
}
private void InsertAfter(DocumentLine node, DocumentLine newLine)
{
var newNode = newLine.InitLineNode();
if (node.Right == null)
{
InsertAsRight(node, newNode);
}
else
{
InsertAsLeft(node.Right.LeftMost, newNode);
}
}
#endregion
#region Red/Black Tree
internal const bool Red = true;
internal const bool Black = false;
private void InsertAsLeft(DocumentLine parentNode, DocumentLine newNode)
{
Debug.Assert(parentNode.Left == null);
parentNode.Left = newNode;
newNode.Parent = parentNode;
newNode.Color = Red;
UpdateAfterChildrenChange(parentNode);
FixTreeOnInsert(newNode);
}
private void InsertAsRight(DocumentLine parentNode, DocumentLine newNode)
{
Debug.Assert(parentNode.Right == null);
parentNode.Right = newNode;
newNode.Parent = parentNode;
newNode.Color = Red;
UpdateAfterChildrenChange(parentNode);
FixTreeOnInsert(newNode);
}
private void FixTreeOnInsert(DocumentLine node)
{
Debug.Assert(node != null);
Debug.Assert(node.Color == Red);
Debug.Assert(node.Left == null || node.Left.Color == Black);
Debug.Assert(node.Right == null || node.Right.Color == Black);
var parentNode = node.Parent;
if (parentNode == null)
{
// we inserted in the root -> the node must be black
// since this is a root node, making the node black increments the number of black nodes
// on all paths by one, so it is still the same for all paths.
node.Color = Black;
return;
}
if (parentNode.Color == Black)
{
// if the parent node where we inserted was black, our red node is placed correctly.
// since we inserted a red node, the number of black nodes on each path is unchanged
// -> the tree is still balanced
return;
}
// parentNode is red, so there is a conflict here!
// because the root is black, parentNode is not the root -> there is a grandparent node
var grandparentNode = parentNode.Parent;
var uncleNode = Sibling(parentNode);
if (uncleNode != null && uncleNode.Color == Red)
{
parentNode.Color = Black;
uncleNode.Color = Black;
grandparentNode.Color = Red;
FixTreeOnInsert(grandparentNode);
return;
}
// now we know: parent is red but uncle is black
// First rotation:
if (node == parentNode.Right && parentNode == grandparentNode.Left)
{
RotateLeft(parentNode);
node = node.Left;
}
else if (node == parentNode.Left && parentNode == grandparentNode.Right)
{
RotateRight(parentNode);
node = node.Right;
}
// because node might have changed, reassign variables:
// ReSharper disable once PossibleNullReferenceException
parentNode = node.Parent;
grandparentNode = parentNode.Parent;
// Now recolor a bit:
parentNode.Color = Black;
grandparentNode.Color = Red;
// Second rotation:
if (node == parentNode.Left && parentNode == grandparentNode.Left)
{
RotateRight(grandparentNode);
}
else
{
// because of the first rotation, this is guaranteed:
Debug.Assert(node == parentNode.Right && parentNode == grandparentNode.Right);
RotateLeft(grandparentNode);
}
}
private void RemoveNode(DocumentLine removedNode)
{
if (removedNode.Left != null && removedNode.Right != null)
{
// replace removedNode with it's in-order successor
var leftMost = removedNode.Right.LeftMost;
RemoveNode(leftMost); // remove leftMost from its current location
// and overwrite the removedNode with it
ReplaceNode(removedNode, leftMost);
leftMost.Left = removedNode.Left;
if (leftMost.Left != null) leftMost.Left.Parent = leftMost;
leftMost.Right = removedNode.Right;
if (leftMost.Right != null) leftMost.Right.Parent = leftMost;
leftMost.Color = removedNode.Color;
UpdateAfterChildrenChange(leftMost);
if (leftMost.Parent != null) UpdateAfterChildrenChange(leftMost.Parent);
return;
}
// now either removedNode.left or removedNode.right is null
// get the remaining child
var parentNode = removedNode.Parent;
var childNode = removedNode.Left ?? removedNode.Right;
ReplaceNode(removedNode, childNode);
if (parentNode != null) UpdateAfterChildrenChange(parentNode);
if (removedNode.Color == Black)
{
if (childNode != null && childNode.Color == Red)
{
childNode.Color = Black;
}
else
{
FixTreeOnDelete(childNode, parentNode);
}
}
}
private void FixTreeOnDelete(DocumentLine node, DocumentLine parentNode)
{
Debug.Assert(node == null || node.Parent == parentNode);
if (parentNode == null)
return;
// warning: node may be null
var sibling = Sibling(node, parentNode);
if (sibling.Color == Red)
{
parentNode.Color = Red;
sibling.Color = Black;
if (node == parentNode.Left)
{
RotateLeft(parentNode);
}
else
{
RotateRight(parentNode);
}
sibling = Sibling(node, parentNode); // update value of sibling after rotation
}
if (parentNode.Color == Black
&& sibling.Color == Black
&& GetColor(sibling.Left) == Black
&& GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
FixTreeOnDelete(parentNode, parentNode.Parent);
return;
}
if (parentNode.Color == Red
&& sibling.Color == Black
&& GetColor(sibling.Left) == Black
&& GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
parentNode.Color = Black;
return;
}
if (node == parentNode.Left &&
sibling.Color == Black &&
GetColor(sibling.Left) == Red &&
GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
sibling.Left.Color = Black;
RotateRight(sibling);
}
else if (node == parentNode.Right &&
sibling.Color == Black &&
GetColor(sibling.Right) == Red &&
GetColor(sibling.Left) == Black)
{
sibling.Color = Red;
sibling.Right.Color = Black;
RotateLeft(sibling);
}
sibling = Sibling(node, parentNode); // update value of sibling after rotation
sibling.Color = parentNode.Color;
parentNode.Color = Black;
if (node == parentNode.Left)
{
if (sibling.Right != null)
{
Debug.Assert(sibling.Right.Color == Red);
sibling.Right.Color = Black;
}
RotateLeft(parentNode);
}
else
{
if (sibling.Left != null)
{
Debug.Assert(sibling.Left.Color == Red);
sibling.Left.Color = Black;
}
RotateRight(parentNode);
}
}
private void ReplaceNode(DocumentLine replacedNode, DocumentLine newNode)
{
if (replacedNode.Parent == null)
{
Debug.Assert(replacedNode == _root);
_root = newNode;
}
else
{
if (replacedNode.Parent.Left == replacedNode)
replacedNode.Parent.Left = newNode;
else
replacedNode.Parent.Right = newNode;
}
if (newNode != null)
{
newNode.Parent = replacedNode.Parent;
}
replacedNode.Parent = null;
}
private void RotateLeft(DocumentLine p)
{
// let q be p's right child
var q = p.Right;
Debug.Assert(q != null);
Debug.Assert(q.Parent == p);
// set q to be the new root
ReplaceNode(p, q);
// set p's right child to be q's left child
p.Right = q.Left;
if (p.Right != null) p.Right.Parent = p;
// set q's left child to be p
q.Left = p;
p.Parent = q;
UpdateAfterRotateLeft(p);
}
private void RotateRight(DocumentLine p)
{
// let q be p's left child
var q = p.Left;
Debug.Assert(q != null);
Debug.Assert(q.Parent == p);
// set q to be the new root
ReplaceNode(p, q);
// set p's left child to be q's right child
p.Left = q.Right;
if (p.Left != null) p.Left.Parent = p;
// set q's right child to be p
q.Right = p;
p.Parent = q;
UpdateAfterRotateRight(p);
}
private static DocumentLine Sibling(DocumentLine node)
{
if (node == node.Parent.Left)
return node.Parent.Right;
else
return node.Parent.Left;
}
private static DocumentLine Sibling(DocumentLine node, DocumentLine parentNode)
{
Debug.Assert(node == null || node.Parent == parentNode);
if (node == parentNode.Left)
return parentNode.Right;
else
return parentNode.Left;
}
private static bool GetColor(DocumentLine node)
{
return node != null && node.Color;
}
#endregion
#region IList implementation
DocumentLine IList<DocumentLine>.this[int index]
{
get
{
EditorDispatcher.VerifyMainThreadAccess();
return GetByNumber(1 + index);
}
set => throw new NotSupportedException();
}
int ICollection<DocumentLine>.Count
{
get
{
//EditorDispatcher.VerifyAccess();
return LineCount;
}
}
bool ICollection<DocumentLine>.IsReadOnly => true;
int IList<DocumentLine>.IndexOf(DocumentLine item)
{
//EditorDispatcher.VerifyAccess();
if (item == null || item.IsDeleted)
return -1;
var index = item.LineNumber - 1;
if (index < LineCount && GetNodeByIndex(index) == item)
return index;
else
return -1;
}
void IList<DocumentLine>.Insert(int index, DocumentLine item)
{
throw new NotSupportedException();
}
void IList<DocumentLine>.RemoveAt(int index)
{
throw new NotSupportedException();
}
void ICollection<DocumentLine>.Add(DocumentLine item)
{
throw new NotSupportedException();
}
void ICollection<DocumentLine>.Clear()
{
throw new NotSupportedException();
}
bool ICollection<DocumentLine>.Contains(DocumentLine item)
{
IList<DocumentLine> self = this;
return self.IndexOf(item) >= 0;
}
void ICollection<DocumentLine>.CopyTo(DocumentLine[] array, int arrayIndex)
{
if (array == null)
throw new ArgumentNullException(nameof(array));
if (array.Length < LineCount)
throw new ArgumentException("The array is too small", nameof(array));
if (arrayIndex < 0 || arrayIndex + LineCount > array.Length)
throw new ArgumentOutOfRangeException(nameof(arrayIndex), arrayIndex, "Value must be between 0 and " + (array.Length - LineCount));
foreach (var ls in this)
{
array[arrayIndex++] = ls;
}
}
bool ICollection<DocumentLine>.Remove(DocumentLine item)
{
throw new NotSupportedException();
}
public IEnumerator<DocumentLine> GetEnumerator()
{
//EditorDispatcher.VerifyAccess();
return Enumerate();
}
private IEnumerator<DocumentLine> Enumerate()
{
//EditorDispatcher.VerifyAccess();
var line = _root.LeftMost;
while (line != null)
{
yield return line;
line = line.NextLine;
}
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 7d8e4407573404e26af41eacb660eb3e
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,78 @@
// 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.IO;
using System.Text;
namespace Unity.CodeEditor.Document
{
/// <summary>
/// A TextWriter implementation that directly inserts into a document.
/// </summary>
internal class DocumentTextWriter : TextWriter
{
private readonly IDocument _document;
/// <summary>
/// Creates a new DocumentTextWriter that inserts into document, starting at insertionOffset.
/// </summary>
internal DocumentTextWriter(IDocument document, int insertionOffset)
{
InsertionOffset = insertionOffset;
_document = document ?? throw new ArgumentNullException(nameof(document));
var line = document.GetLineByOffset(insertionOffset);
if (line.DelimiterLength == 0)
line = line.PreviousLine;
if (line != null)
{
// ReSharper disable once VirtualMemberCallInConstructor
NewLine = document.GetText(line.EndOffset, line.DelimiterLength);
}
}
/// <summary>
/// Gets/Sets the current insertion offset.
/// </summary>
internal int InsertionOffset { get; set; }
/// <inheritdoc/>
public override void Write(char value)
{
_document.Insert(InsertionOffset, value.ToString());
InsertionOffset++;
}
/// <inheritdoc/>
public override void Write(char[] buffer, int index, int count)
{
_document.Insert(InsertionOffset, new string(buffer, index, count));
InsertionOffset += count;
}
/// <inheritdoc/>
public override void Write(string value)
{
_document.Insert(InsertionOffset, value);
InsertionOffset += value.Length;
}
/// <inheritdoc/>
public override Encoding Encoding => Encoding.UTF8;
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 36d9d402826ee48d8816a061c1aba22e
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,320 @@
// 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.Document
{
/// <summary>
/// A document representing a source code file for refactoring.
/// Line and column counting starts at 1.
/// Offset counting starts at 0.
/// </summary>
internal interface IDocument : ITextSource, IServiceProvider
{
/// <summary>
/// Gets/Sets the text of the whole document..
/// </summary>
new string Text { get; set; } // hides ITextSource.Text to add the setter
/// <summary>
/// This event is called directly before a change is applied to the document.
/// </summary>
/// <remarks>
/// It is invalid to modify the document within this event handler.
/// Aborting the change (by throwing an exception) is likely to cause corruption of data structures
/// that listen to the Changing and Changed events.
/// </remarks>
event EventHandler<TextChangeEventArgs> TextChanging;
/// <summary>
/// This event is called directly after a change is applied to the document.
/// </summary>
/// <remarks>
/// It is invalid to modify the document within this event handler.
/// Aborting the event handler (by throwing an exception) is likely to cause corruption of data structures
/// that listen to the Changing and Changed events.
/// </remarks>
event EventHandler<TextChangeEventArgs> TextChanged;
/// <summary>
/// This event is called after a group of changes is completed.
/// </summary>
/// <seealso cref="EndUndoableAction"/>
event EventHandler ChangeCompleted;
/// <summary>
/// Gets the number of lines in the document.
/// </summary>
int LineCount { get; }
/// <summary>
/// Gets the document line with the specified number.
/// </summary>
/// <param name="lineNumber">The number of the line to retrieve. The first line has number 1.</param>
IDocumentLine GetLineByNumber(int lineNumber);
/// <summary>
/// Gets the document line that contains the specified offset.
/// </summary>
IDocumentLine GetLineByOffset(int offset);
/// <summary>
/// Gets the offset from a text location.
/// </summary>
/// <seealso cref="GetLocation"/>
int GetOffset(int line, int column);
/// <summary>
/// Gets the offset from a text location.
/// </summary>
/// <seealso cref="GetLocation"/>
int GetOffset(TextLocation location);
/// <summary>
/// Gets the location from an offset.
/// </summary>
/// <seealso cref="GetOffset(TextLocation)"/>
TextLocation GetLocation(int offset);
/// <summary>
/// Inserts text.
/// </summary>
/// <param name="offset">The offset at which the text is inserted.</param>
/// <param name="text">The new text.</param>
/// <remarks>
/// Anchors positioned exactly at the insertion offset will move according to their movement type.
/// For AnchorMovementType.Default, they will move behind the inserted text.
/// The caret will also move behind the inserted text.
/// </remarks>
void Insert(int offset, string text);
/// <summary>
/// Inserts text.
/// </summary>
/// <param name="offset">The offset at which the text is inserted.</param>
/// <param name="text">The new text.</param>
/// <remarks>
/// Anchors positioned exactly at the insertion offset will move according to their movement type.
/// For AnchorMovementType.Default, they will move behind the inserted text.
/// The caret will also move behind the inserted text.
/// </remarks>
void Insert(int offset, ITextSource text);
/// <summary>
/// Inserts text.
/// </summary>
/// <param name="offset">The offset at which the text is inserted.</param>
/// <param name="text">The new text.</param>
/// <param name="defaultAnchorMovementType">
/// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type.
/// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter.
/// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter.
/// </param>
void Insert(int offset, string text, AnchorMovementType defaultAnchorMovementType);
/// <summary>
/// Inserts text.
/// </summary>
/// <param name="offset">The offset at which the text is inserted.</param>
/// <param name="text">The new text.</param>
/// <param name="defaultAnchorMovementType">
/// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type.
/// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter.
/// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter.
/// </param>
void Insert(int offset, ITextSource text, AnchorMovementType defaultAnchorMovementType);
/// <summary>
/// Removes text.
/// </summary>
/// <param name="offset">Starting offset of the text to be removed.</param>
/// <param name="length">Length of the text to be removed.</param>
void Remove(int offset, int length);
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="newText">The new text.</param>
void Replace(int offset, int length, string newText);
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="newText">The new text.</param>
void Replace(int offset, int length, ITextSource newText);
/// <summary>
/// Make the document combine the following actions into a single
/// action for undo purposes.
/// </summary>
void StartUndoableAction();
/// <summary>
/// Ends the undoable action started with <see cref="StartUndoableAction"/>.
/// </summary>
void EndUndoableAction();
/// <summary>
/// Creates an undo group. Dispose the returned value to close the undo group.
/// </summary>
/// <returns>An object that closes the undo group when Dispose() is called.</returns>
IDisposable OpenUndoGroup();
/// <summary>
/// Creates a new <see cref="ITextAnchor"/> at the specified offset.
/// </summary>
/// <inheritdoc cref="ITextAnchor" select="remarks|example"/>
ITextAnchor CreateAnchor(int offset);
/// <summary>
/// Gets the name of the file the document is stored in.
/// Could also be a non-existent dummy file name or null if no name has been set.
/// </summary>
string FileName { get; }
/// <summary>
/// Fired when the file name of the document changes.
/// </summary>
event EventHandler FileNameChanged;
}
/// <summary>
/// A line inside a <see cref="IDocument"/>.
/// </summary>
internal interface IDocumentLine : ISegment
{
/// <summary>
/// Gets the length of this line, including the line delimiter.
/// </summary>
int TotalLength { get; }
/// <summary>
/// Gets the length of the line terminator.
/// Returns 1 or 2; or 0 at the end of the document.
/// </summary>
int DelimiterLength { get; }
/// <summary>
/// Gets the number of this line.
/// The first line has the number 1.
/// </summary>
int LineNumber { get; }
/// <summary>
/// Gets the previous line. Returns null if this is the first line in the document.
/// </summary>
IDocumentLine PreviousLine { get; }
/// <summary>
/// Gets the next line. Returns null if this is the last line in the document.
/// </summary>
IDocumentLine NextLine { get; }
/// <summary>
/// Gets whether the line was deleted.
/// </summary>
bool IsDeleted { get; }
}
/// <summary>
/// Describes a change of the document text.
/// This class is thread-safe.
/// </summary>
internal class TextChangeEventArgs : EventArgs
{
/// <summary>
/// The offset at which the change occurs.
/// </summary>
internal int Offset { get; }
/// <summary>
/// The text that was removed.
/// </summary>
internal ITextSource RemovedText { get; }
/// <summary>
/// The number of characters removed.
/// </summary>
internal int RemovalLength => RemovedText.TextLength;
/// <summary>
/// The text that was inserted.
/// </summary>
internal ITextSource InsertedText { get; }
/// <summary>
/// The number of characters inserted.
/// </summary>
internal int InsertionLength => InsertedText.TextLength;
/// <summary>
/// Creates a new TextChangeEventArgs object.
/// </summary>
internal TextChangeEventArgs(int offset, string removedText, string insertedText)
{
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset), offset, "offset must not be negative");
Offset = offset;
RemovedText = removedText != null ? new StringTextSource(removedText) : StringTextSource.Empty;
InsertedText = insertedText != null ? new StringTextSource(insertedText) : StringTextSource.Empty;
}
/// <summary>
/// Creates a new TextChangeEventArgs object.
/// </summary>
internal TextChangeEventArgs(int offset, ITextSource removedText, ITextSource insertedText)
{
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset), offset, "offset must not be negative");
Offset = offset;
RemovedText = removedText ?? StringTextSource.Empty;
InsertedText = insertedText ?? StringTextSource.Empty;
}
/// <summary>
/// Gets the new offset where the specified offset moves after this document change.
/// </summary>
internal virtual int GetNewOffset(int offset, AnchorMovementType movementType = AnchorMovementType.Default)
{
if (offset >= Offset && offset <= Offset + RemovalLength)
{
if (movementType == AnchorMovementType.BeforeInsertion)
return Offset;
return Offset + InsertionLength;
}
if (offset > Offset)
{
return offset + InsertionLength - RemovalLength;
}
return offset;
}
/// <summary>
/// Creates TextChangeEventArgs for the reverse change.
/// </summary>
internal virtual TextChangeEventArgs Invert()
{
return new TextChangeEventArgs(Offset, InsertedText, RemovedText);
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: d170e6aba78146b09759f774ef27c7fd
timeCreated: 1710753857
@@ -0,0 +1,70 @@
// 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.
namespace Unity.CodeEditor.Document
{
/// <summary>
/// Allows for low-level line tracking.
/// </summary>
/// <remarks>
/// The methods on this interface are called by the TextDocument's LineManager immediately after the document
/// has changed, *while* the DocumentLineTree is updating.
/// Thus, the DocumentLineTree may be in an invalid state when these methods are called.
/// This interface should only be used to update per-line data structures like the HeightTree.
/// Line trackers must not cause any events to be raised during an update to prevent other code from seeing
/// the invalid state.
/// Line trackers may be called while the TextDocument has taken a lock.
/// You must be careful not to dead-lock inside ILineTracker callbacks.
/// </remarks>
internal interface ILineTracker
{
/// <summary>
/// Is called immediately before a document line is removed.
/// </summary>
void BeforeRemoveLine(DocumentLine line);
/// <summary>
/// Is called immediately before a document line changes length.
/// This method will be called whenever the line is changed, even when the length stays as it is.
/// The method might be called multiple times for a single line because
/// a replacement is internally handled as removal followed by insertion.
/// </summary>
void SetLineLength(DocumentLine line, int newTotalLength);
/// <summary>
/// Is called immediately after a line was inserted.
/// </summary>
/// <param name="newLine">The new line</param>
/// <param name="insertionPos">The existing line before the new line</param>
void LineInserted(DocumentLine insertionPos, DocumentLine newLine);
/// <summary>
/// Indicates that there were changes to the document that the line tracker was not notified of.
/// The document is in a consistent state (but the line trackers aren't), and line trackers should
/// throw away their data and rebuild the document.
/// </summary>
void RebuildDocument();
/// <summary>
/// Notifies the line tracker that a document change (a single change, not a change group) has completed.
/// This method gets called after the change has been performed, but before the <see cref="TextDocument.Changed"/> event
/// is raised.
/// </summary>
void ChangeComplete(DocumentChangeEventArgs e);
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 1bad6294dbf1045048f29381bfdf4961
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,139 @@
// 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.Document
{
/// <summary>
/// The TextAnchor class references an offset (a position between two characters).
/// It automatically updates the offset when text is inserted/removed in front of the anchor.
/// </summary>
/// <remarks>
/// <para>Use the <see cref="ITextAnchor.Offset"/> property to get the offset from a text anchor.
/// Use the <see cref="IDocument.CreateAnchor"/> method to create an anchor from an offset.
/// </para>
/// <para>
/// The document will automatically update all text anchors; and because it uses weak references to do so,
/// the garbage collector can simply collect the anchor object when you don't need it anymore.
/// </para>
/// <para>Moreover, the document is able to efficiently update a large number of anchors without having to look
/// at each anchor object individually. Updating the offsets of all anchors usually only takes time logarithmic
/// to the number of anchors. Retrieving the <see cref="ITextAnchor.Offset"/> property also runs in O(lg N).</para>
/// </remarks>
/// <example>
/// Usage:
/// <code>TextAnchor anchor = document.CreateAnchor(offset);
/// ChangeMyDocument();
/// int newOffset = anchor.Offset;
/// </code>
/// </example>
internal interface ITextAnchor
{
/// <summary>
/// Gets the text location of this anchor.
/// </summary>
/// <exception cref="InvalidOperationException">Thrown when trying to get the Offset from a deleted anchor.</exception>
TextLocation Location { get; }
/// <summary>
/// Gets the offset of the text anchor.
/// </summary>
/// <exception cref="InvalidOperationException">Thrown when trying to get the Offset from a deleted anchor.</exception>
int Offset { get; }
/// <summary>
/// Controls how the anchor moves.
/// </summary>
/// <remarks>Anchor movement is ambiguous if text is inserted exactly at the anchor's location.
/// Does the anchor stay before the inserted text, or does it move after it?
/// The property <see cref="MovementType"/> will be used to determine which of these two options the anchor will choose.
/// The default value is <see cref="AnchorMovementType.Default"/>.</remarks>
AnchorMovementType MovementType { get; set; }
/// <summary>
/// <para>
/// Specifies whether the anchor survives deletion of the text containing it.
/// </para><para>
/// <c>false</c>: The anchor is deleted when the a selection that includes the anchor is deleted.
/// <c>true</c>: The anchor is not deleted.
/// </para>
/// </summary>
/// <remarks><inheritdoc cref="IsDeleted" /></remarks>
bool SurviveDeletion { get; set; }
/// <summary>
/// Gets whether the anchor was deleted.
/// </summary>
/// <remarks>
/// <para>When a piece of text containing an anchor is removed, then that anchor will be deleted.
/// First, the <see cref="IsDeleted"/> property is set to true on all deleted anchors,
/// then the <see cref="Deleted"/> events are raised.
/// You cannot retrieve the offset from an anchor that has been deleted.</para>
/// <para>This deletion behavior might be useful when using anchors for building a bookmark feature,
/// but in other cases you want to still be able to use the anchor. For those cases, set <c><see cref="SurviveDeletion"/> = true</c>.</para>
/// </remarks>
bool IsDeleted { get; }
/// <summary>
/// Occurs after the anchor was deleted.
/// </summary>
/// <remarks>
/// <inheritdoc cref="IsDeleted" />
/// <para>Due to the 'weak reference' nature of text anchors, you will receive
/// the Deleted event only while your code holds a reference to the TextAnchor object.
/// </para>
/// </remarks>
event EventHandler Deleted;
/// <summary>
/// Gets the line number of the anchor.
/// </summary>
/// <exception cref="InvalidOperationException">Thrown when trying to get the Offset from a deleted anchor.</exception>
int Line { get; }
/// <summary>
/// Gets the column number of this anchor.
/// </summary>
/// <exception cref="InvalidOperationException">Thrown when trying to get the Offset from a deleted anchor.</exception>
int Column { get; }
}
/// <summary>
/// Defines how a text anchor moves.
/// </summary>
internal enum AnchorMovementType
{
/// <summary>
/// When text is inserted at the anchor position, the type of the insertion
/// determines where the caret moves to. For normal insertions, the anchor will move
/// after the inserted text.
/// </summary>
Default,
/// <summary>
/// Behaves like a start marker - when text is inserted at the anchor position, the anchor will stay
/// before the inserted text.
/// </summary>
BeforeInsertion,
/// <summary>
/// Behave like an end marker - when text is insered at the anchor position, the anchor will move
/// after the inserted text.
/// </summary>
AfterInsertion
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 1cb83927eaf714ec9ad8234a784bb1a9
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,356 @@
// 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.Diagnostics.CodeAnalysis;
using System.IO;
namespace Unity.CodeEditor.Document
{
/// <summary>
/// A read-only view on a (potentially mutable) text source.
/// The IDocument interface derives from this interface.
/// </summary>
internal interface ITextSource
{
/// <summary>
/// Gets a version identifier for this text source.
/// Returns null for unversioned text sources.
/// </summary>
ITextSourceVersion Version { get; }
/// <summary>
/// Creates an immutable snapshot of this text source.
/// Unlike all other methods in this interface, this method is thread-safe.
/// </summary>
ITextSource CreateSnapshot();
/// <summary>
/// Creates an immutable snapshot of a part of this text source.
/// Unlike all other methods in this interface, this method is thread-safe.
/// </summary>
ITextSource CreateSnapshot(int offset, int length);
/// <summary>
/// Creates a new TextReader to read from this text source.
/// </summary>
TextReader CreateReader();
/// <summary>
/// Creates a new TextReader to read from this text source.
/// </summary>
TextReader CreateReader(int offset, int length);
/// <summary>
/// Gets the total text length.
/// </summary>
/// <returns>The length of the text, in characters.</returns>
/// <remarks>This is the same as Text.Length, but is more efficient because
/// it doesn't require creating a String object.</remarks>
int TextLength { get; }
/// <summary>
/// Gets the whole text as string.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods")]
string Text { get; }
/// <summary>
/// Gets a character at the specified position in the document.
/// </summary>
/// <paramref name="offset">The index of the character to get.</paramref>
/// <exception cref="ArgumentOutOfRangeException">Offset is outside the valid range (0 to TextLength-1).</exception>
/// <returns>The character at the specified position.</returns>
/// <remarks>This is the same as Text[offset], but is more efficient because
/// it doesn't require creating a String object.</remarks>
char GetCharAt(int offset);
/// <summary>
/// Retrieves the text for a portion of the document.
/// </summary>
/// <exception cref="ArgumentOutOfRangeException">offset or length is outside the valid range.</exception>
/// <remarks>This is the same as Text.Substring, but is more efficient because
/// it doesn't require creating a String object for the whole document.</remarks>
string GetText(int offset, int length);
/// <summary>
/// Retrieves the text for a portion of the document as ReadOnlyMemory&lt;char&gt;.
/// </summary>
/// <exception cref="ArgumentOutOfRangeException">offset or length is outside the valid range.</exception>
/// <remarks>This method may be more efficient than GetText(int, int) because it can avoid allocating a new string
/// in some implementations.</remarks>
ReadOnlyMemory<char> GetTextAsMemory(int offset, int length);
/// <summary>
/// Retrieves the text for a portion of the document.
/// </summary>
/// <exception cref="ArgumentOutOfRangeException">offset or length is outside the valid range.</exception>
string GetText(ISegment segment);
/// <summary>
/// Writes the text from this document into the TextWriter.
/// </summary>
void WriteTextTo(TextWriter writer);
/// <summary>
/// Writes the text from this document into the TextWriter.
/// </summary>
void WriteTextTo(TextWriter writer, int offset, int length);
/// <summary>
/// Gets the index of the first occurrence of the character in the specified array.
/// </summary>
/// <param name="c">Character to search for</param>
/// <param name="startIndex">Start index of the area to search.</param>
/// <param name="count">Length of the area to search.</param>
/// <returns>The first index where the character was found; or -1 if no occurrence was found.</returns>
int IndexOf(char c, int startIndex, int count);
/// <summary>
/// Gets the index of the first occurrence of any character in the specified array.
/// </summary>
/// <param name="anyOf">Characters to search for</param>
/// <param name="startIndex">Start index of the area to search.</param>
/// <param name="count">Length of the area to search.</param>
/// <returns>The first index where any character was found; or -1 if no occurrence was found.</returns>
int IndexOfAny(char[] anyOf, int startIndex, int count);
/// <summary>
/// Gets the index of the first occurrence of the specified search text in this text source.
/// </summary>
/// <param name="searchText">The search text</param>
/// <param name="startIndex">Start index of the area to search.</param>
/// <param name="count">Length of the area to search.</param>
/// <param name="comparisonType">String comparison to use.</param>
/// <returns>The first index where the search term was found; or -1 if no occurrence was found.</returns>
int IndexOf(string searchText, int startIndex, int count, StringComparison comparisonType);
/// <summary>
/// Gets the index of the last occurrence of the specified character in this text source.
/// </summary>
/// <param name="c">The search character</param>
/// <param name="startIndex">Start index of the area to search.</param>
/// <param name="count">Length of the area to search.</param>
/// <returns>The last index where the search term was found; or -1 if no occurrence was found.</returns>
/// <remarks>The search proceeds backwards from (startIndex+count) to startIndex.
/// This is different than the meaning of the parameters on string.LastIndexOf!</remarks>
int LastIndexOf(char c, int startIndex, int count);
/// <summary>
/// Gets the index of the last occurrence of the specified search text in this text source.
/// </summary>
/// <param name="searchText">The search text</param>
/// <param name="startIndex">Start index of the area to search.</param>
/// <param name="count">Length of the area to search.</param>
/// <param name="comparisonType">String comparison to use.</param>
/// <returns>The last index where the search term was found; or -1 if no occurrence was found.</returns>
/// <remarks>The search proceeds backwards from (startIndex+count) to startIndex.
/// This is different than the meaning of the parameters on string.LastIndexOf!</remarks>
int LastIndexOf(string searchText, int startIndex, int count, StringComparison comparisonType);
/* What about:
void Insert (int offset, string value);
void Remove (int offset, int count);
void Remove (ISegment segment);
void Replace (int offset, int count, string value);
Or more search operations:
IEnumerable<int> SearchForward (string pattern, int startIndex);
IEnumerable<int> SearchForwardIgnoreCase (string pattern, int startIndex);
IEnumerable<int> SearchBackward (string pattern, int startIndex);
IEnumerable<int> SearchBackwardIgnoreCase (string pattern, int startIndex);
*/
}
/// <summary>
/// Represents a version identifier for a text source.
/// </summary>
/// <remarks>
/// Verions can be used to efficiently detect whether a document has changed and needs reparsing;
/// or even to implement incremental parsers.
/// It is a separate class from ITextSource to allow the GC to collect the text source while
/// the version checkpoint is still in use.
/// </remarks>
internal interface ITextSourceVersion
{
/// <summary>
/// Gets whether this checkpoint belongs to the same document as the other checkpoint.
/// </summary>
/// <remarks>
/// Returns false when given <c>null</c>.
/// </remarks>
bool BelongsToSameDocumentAs(ITextSourceVersion other);
/// <summary>
/// Compares the age of this checkpoint to the other checkpoint.
/// </summary>
/// <remarks>This method is thread-safe.</remarks>
/// <exception cref="ArgumentException">Raised if 'other' belongs to a different document than this version.</exception>
/// <returns>-1 if this version is older than <paramref name="other"/>.
/// 0 if <c>this</c> version instance represents the same version as <paramref name="other"/>.
/// 1 if this version is newer than <paramref name="other"/>.</returns>
int CompareAge(ITextSourceVersion other);
/// <summary>
/// Gets the changes from this checkpoint to the other checkpoint.
/// If 'other' is older than this checkpoint, reverse changes are calculated.
/// </summary>
/// <remarks>This method is thread-safe.</remarks>
/// <exception cref="ArgumentException">Raised if 'other' belongs to a different document than this checkpoint.</exception>
IEnumerable<TextChangeEventArgs> GetChangesTo(ITextSourceVersion other);
/// <summary>
/// Calculates where the offset has moved in the other buffer version.
/// </summary>
/// <exception cref="ArgumentException">Raised if 'other' belongs to a different document than this checkpoint.</exception>
int MoveOffsetTo(ITextSourceVersion other, int oldOffset, AnchorMovementType movement = AnchorMovementType.Default);
}
/// <summary>
/// Implements the ITextSource interface using a string.
/// </summary>
internal class StringTextSource : ITextSource
{
/// <summary>
/// Gets a text source containing the empty string.
/// </summary>
internal static readonly StringTextSource Empty = new StringTextSource(string.Empty);
/// <summary>
/// Creates a new StringTextSource with the given text.
/// </summary>
internal StringTextSource(string text)
{
Text = text ?? throw new ArgumentNullException(nameof(text));
}
/// <summary>
/// Creates a new StringTextSource with the given text.
/// </summary>
internal StringTextSource(string text, ITextSourceVersion version)
{
Text = text ?? throw new ArgumentNullException(nameof(text));
Version = version;
}
/// <inheritdoc/>
public ITextSourceVersion Version { get; }
/// <inheritdoc/>
public int TextLength => Text.Length;
/// <inheritdoc/>
public string Text { get; }
/// <inheritdoc/>
public ITextSource CreateSnapshot()
{
return this; // StringTextSource is immutable
}
/// <inheritdoc/>
public ITextSource CreateSnapshot(int offset, int length)
{
return new StringTextSource(Text.Substring(offset, length));
}
/// <inheritdoc/>
public TextReader CreateReader()
{
return new StringReader(Text);
}
/// <inheritdoc/>
public TextReader CreateReader(int offset, int length)
{
return new StringReader(Text.Substring(offset, length));
}
/// <inheritdoc/>
public void WriteTextTo(TextWriter writer)
{
writer.Write(Text);
}
/// <inheritdoc/>
public void WriteTextTo(TextWriter writer, int offset, int length)
{
writer.Write(Text.Substring(offset, length));
}
/// <inheritdoc/>
public char GetCharAt(int offset)
{
return Text[offset];
}
/// <inheritdoc/>
public string GetText(int offset, int length)
{
return Text.Substring(offset, length);
}
/// <inheritdoc/>
public ReadOnlyMemory<char> GetTextAsMemory(int offset, int length)
{
return Text.AsMemory(offset, length);
}
/// <inheritdoc/>
public string GetText(ISegment segment)
{
if (segment == null)
throw new ArgumentNullException(nameof(segment));
return Text.Substring(segment.Offset, segment.Length);
}
/// <inheritdoc/>
public int IndexOf(char c, int startIndex, int count)
{
return Text.IndexOf(c, startIndex, count);
}
/// <inheritdoc/>
public int IndexOfAny(char[] anyOf, int startIndex, int count)
{
return Text.IndexOfAny(anyOf, startIndex, count);
}
/// <inheritdoc/>
public int IndexOf(string searchText, int startIndex, int count, StringComparison comparisonType)
{
return Text.IndexOf(searchText, startIndex, count, comparisonType);
}
/// <inheritdoc/>
public int LastIndexOf(char c, int startIndex, int count)
{
return Text.LastIndexOf(c, startIndex + count - 1, count);
}
/// <inheritdoc/>
public int LastIndexOf(string searchText, int startIndex, int count, StringComparison comparisonType)
{
return Text.LastIndexOf(searchText, startIndex + count - 1, count, comparisonType);
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 11f102ea76a834282a8a533f1a797d3e
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,43 @@
// 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.
namespace Unity.CodeEditor.Document
{
/// <summary>
/// This Interface describes a the basic Undo/Redo operation
/// all Undo Operations must implement this interface.
/// </summary>
internal interface IUndoableOperation
{
/// <summary>
/// Undo the last operation
/// </summary>
void Undo();
/// <summary>
/// Redo the last operation
/// </summary>
void Redo();
}
interface IUndoableOperationWithContext : IUndoableOperation
{
void Undo(UndoStack stack);
void Redo(UndoStack stack);
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 85086b32b8552416fbdc73ec5d384b63
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,340 @@
// 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 System.Diagnostics;
using System.Linq;
namespace Unity.CodeEditor.Document
{
/// <summary>
/// Creates/Deletes lines when text is inserted/removed.
/// </summary>
internal sealed class LineManager
{
#region Constructor
private readonly TextDocument _document;
private readonly DocumentLineTree _documentLineTree;
/// <summary>
/// A copy of the line trackers. We need a copy so that line trackers may remove themselves
/// while being notified (used e.g. by WeakLineTracker)
/// </summary>
private ILineTracker[] _lineTrackers;
internal void UpdateListOfLineTrackers()
{
_lineTrackers = _document.LineTrackers.ToArray();
}
internal LineManager(DocumentLineTree documentLineTree, TextDocument document)
{
_document = document;
_documentLineTree = documentLineTree;
UpdateListOfLineTrackers();
Rebuild();
}
#endregion
#region Change events
/*
HashSet<DocumentLine> deletedLines = new HashSet<DocumentLine>();
readonly HashSet<DocumentLine> changedLines = new HashSet<DocumentLine>();
HashSet<DocumentLine> deletedOrChangedLines = new HashSet<DocumentLine>();
/// <summary>
/// Gets the list of lines deleted since the last RetrieveChangedLines() call.
/// The returned list is unsorted.
/// </summary>
internal ICollection<DocumentLine> RetrieveDeletedLines()
{
var r = deletedLines;
deletedLines = new HashSet<DocumentLine>();
return r;
}
/// <summary>
/// Gets the list of lines changed since the last RetrieveChangedLines() call.
/// The returned list is sorted by line number and does not contain deleted lines.
/// </summary>
internal List<DocumentLine> RetrieveChangedLines()
{
var list = (from line in changedLines
where !line.IsDeleted
let number = line.LineNumber
orderby number
select line).ToList();
changedLines.Clear();
return list;
}
/// <summary>
/// Gets the list of lines changed since the last RetrieveDeletedOrChangedLines() call.
/// The returned list is not sorted.
/// </summary>
internal ICollection<DocumentLine> RetrieveDeletedOrChangedLines()
{
var r = deletedOrChangedLines;
deletedOrChangedLines = new HashSet<DocumentLine>();
return r;
}
*/
#endregion
#region Rebuild
internal void Rebuild()
{
// keep the first document line
var ls = _documentLineTree.GetByNumber(1);
// but mark all other lines as deleted, and detach them from the other nodes
for (var line = ls.NextLine; line != null; line = line.NextLine)
{
line.IsDeleted = true;
line.Parent = line.Left = line.Right = null;
}
// Reset the first line to detach it from the deleted lines
ls.ResetLine();
var ds = NewLineFinder.NextNewLine(_document, 0);
var lines = new List<DocumentLine>();
var lastDelimiterEnd = 0;
while (ds != SimpleSegment.Invalid)
{
ls.TotalLength = ds.Offset + ds.Length - lastDelimiterEnd;
ls.DelimiterLength = ds.Length;
lastDelimiterEnd = ds.Offset + ds.Length;
lines.Add(ls);
ls = new DocumentLine(_document);
ds = NewLineFinder.NextNewLine(_document, lastDelimiterEnd);
}
ls.TotalLength = _document.TextLength - lastDelimiterEnd;
lines.Add(ls);
_documentLineTree.RebuildTree(lines);
foreach (var lineTracker in _lineTrackers)
lineTracker.RebuildDocument();
}
#endregion
#region Remove
internal void Remove(int offset, int length)
{
Debug.Assert(length >= 0);
if (length == 0) return;
var startLine = _documentLineTree.GetByOffset(offset);
var startLineOffset = startLine.Offset;
Debug.Assert(offset < startLineOffset + startLine.TotalLength);
if (offset > startLineOffset + startLine.Length)
{
Debug.Assert(startLine.DelimiterLength == 2);
// we are deleting starting in the middle of a delimiter
// remove last delimiter part
SetLineLength(startLine, startLine.TotalLength - 1);
// remove remaining text
Remove(offset, length - 1);
return;
}
if (offset + length < startLineOffset + startLine.TotalLength)
{
// just removing a part of this line
//startLine.RemovedLinePart(ref deferredEventList, offset - startLineOffset, length);
SetLineLength(startLine, startLine.TotalLength - length);
return;
}
// merge startLine with another line because startLine's delimiter was deleted
// possibly remove lines in between if multiple delimiters were deleted
var charactersRemovedInStartLine = startLineOffset + startLine.TotalLength - offset;
Debug.Assert(charactersRemovedInStartLine > 0);
//startLine.RemovedLinePart(ref deferredEventList, offset - startLineOffset, charactersRemovedInStartLine);
var endLine = _documentLineTree.GetByOffset(offset + length);
if (endLine == startLine)
{
// special case: we are removing a part of the last line up to the
// end of the document
SetLineLength(startLine, startLine.TotalLength - length);
return;
}
var endLineOffset = endLine.Offset;
var charactersLeftInEndLine = endLineOffset + endLine.TotalLength - (offset + length);
//endLine.RemovedLinePart(ref deferredEventList, 0, endLine.TotalLength - charactersLeftInEndLine);
//startLine.MergedWith(endLine, offset - startLineOffset);
// remove all lines between startLine (excl.) and endLine (incl.)
var tmp = startLine.NextLine;
DocumentLine lineToRemove;
do
{
lineToRemove = tmp;
tmp = tmp.NextLine;
RemoveLine(lineToRemove);
} while (lineToRemove != endLine);
SetLineLength(startLine, startLine.TotalLength - charactersRemovedInStartLine + charactersLeftInEndLine);
}
private void RemoveLine(DocumentLine lineToRemove)
{
foreach (var lt in _lineTrackers)
lt.BeforeRemoveLine(lineToRemove);
_documentLineTree.RemoveLine(lineToRemove);
// foreach (ILineTracker lt in lineTracker)
// lt.AfterRemoveLine(lineToRemove);
// deletedLines.Add(lineToRemove);
// deletedOrChangedLines.Add(lineToRemove);
}
#endregion
#region Insert
internal void Insert(int offset, ITextSource text)
{
var line = _documentLineTree.GetByOffset(offset);
var lineOffset = line.Offset;
Debug.Assert(offset <= lineOffset + line.TotalLength);
if (offset > lineOffset + line.Length)
{
Debug.Assert(line.DelimiterLength == 2);
// we are inserting in the middle of a delimiter
// shorten line
SetLineLength(line, line.TotalLength - 1);
// add new line
line = InsertLineAfter(line, 1);
line = SetLineLength(line, 1);
}
var ds = NewLineFinder.NextNewLine(text, 0);
if (ds == SimpleSegment.Invalid)
{
// no newline is being inserted, all text is inserted in a single line
//line.InsertedLinePart(offset - line.Offset, text.Length);
SetLineLength(line, line.TotalLength + text.TextLength);
return;
}
//DocumentLine firstLine = line;
//firstLine.InsertedLinePart(offset - firstLine.Offset, ds.Offset);
var lastDelimiterEnd = 0;
while (ds != SimpleSegment.Invalid)
{
// split line segment at line delimiter
var lineBreakOffset = offset + ds.Offset + ds.Length;
lineOffset = line.Offset;
var lengthAfterInsertionPos = lineOffset + line.TotalLength - (offset + lastDelimiterEnd);
line = SetLineLength(line, lineBreakOffset - lineOffset);
var newLine = InsertLineAfter(line, lengthAfterInsertionPos);
newLine = SetLineLength(newLine, lengthAfterInsertionPos);
line = newLine;
lastDelimiterEnd = ds.Offset + ds.Length;
ds = NewLineFinder.NextNewLine(text, lastDelimiterEnd);
}
//firstLine.SplitTo(line);
// insert rest after last delimiter
if (lastDelimiterEnd != text.TextLength)
{
//line.InsertedLinePart(0, text.Length - lastDelimiterEnd);
SetLineLength(line, line.TotalLength + text.TextLength - lastDelimiterEnd);
}
}
private DocumentLine InsertLineAfter(DocumentLine line, int length)
{
var newLine = _documentLineTree.InsertLineAfter(line, length);
foreach (var lt in _lineTrackers)
lt.LineInserted(line, newLine);
return newLine;
}
#endregion
#region SetLineLength
/// <summary>
/// Sets the total line length and checks the delimiter.
/// This method can cause line to be deleted when it contains a single '\n' character
/// and the previous line ends with '\r'.
/// </summary>
/// <returns>Usually returns <paramref name="line"/>, but if line was deleted due to
/// the "\r\n" merge, returns the previous line.</returns>
private DocumentLine SetLineLength(DocumentLine line, int newTotalLength)
{
var delta = newTotalLength - line.TotalLength;
if (delta != 0)
{
foreach (var lt in _lineTrackers)
lt.SetLineLength(line, newTotalLength);
line.TotalLength = newTotalLength;
DocumentLineTree.UpdateAfterChildrenChange(line);
}
// determine new DelimiterLength
if (newTotalLength == 0)
{
line.DelimiterLength = 0;
}
else
{
var lineOffset = line.Offset;
var lastChar = _document.GetCharAt(lineOffset + newTotalLength - 1);
if (lastChar == '\r')
{
line.DelimiterLength = 1;
}
else if (lastChar == '\n')
{
if (newTotalLength >= 2 && _document.GetCharAt(lineOffset + newTotalLength - 2) == '\r')
{
line.DelimiterLength = 2;
}
else if (newTotalLength == 1 && lineOffset > 0 && _document.GetCharAt(lineOffset - 1) == '\r')
{
// we need to join this line with the previous line
var previousLine = line.PreviousLine;
RemoveLine(line);
return SetLineLength(previousLine, previousLine.TotalLength + 1);
}
else
{
line.DelimiterLength = 1;
}
}
else
{
line.DelimiterLength = 0;
}
}
return line;
}
#endregion
#region ChangeComplete
internal void ChangeComplete(DocumentChangeEventArgs e)
{
foreach (var lt in _lineTrackers)
{
lt.ChangeComplete(e);
}
}
#endregion
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: a8c19b64eb4ef43a2bdea621c5acaf14
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,158 @@
// 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.Text;
namespace Unity.CodeEditor.Document
{
internal static class NewLineFinder
{
private static readonly char[] Newline = { '\r', '\n' };
internal static readonly string[] NewlineStrings = { "\r\n", "\r", "\n" };
/// <summary>
/// Gets the location of the next new line character, or SimpleSegment.Invalid
/// if none is found.
/// </summary>
internal static SimpleSegment NextNewLine(string text, int offset)
{
var pos = text.IndexOfAny(Newline, offset);
if (pos >= 0)
{
if (text[pos] == '\r')
{
if (pos + 1 < text.Length && text[pos + 1] == '\n')
return new SimpleSegment(pos, 2);
}
return new SimpleSegment(pos, 1);
}
return SimpleSegment.Invalid;
}
/// <summary>
/// Gets the location of the next new line character, or SimpleSegment.Invalid
/// if none is found.
/// </summary>
internal static SimpleSegment NextNewLine(ITextSource text, int offset)
{
var textLength = text.TextLength;
var pos = text.IndexOfAny(Newline, offset, textLength - offset);
if (pos >= 0)
{
if (text.GetCharAt(pos) == '\r')
{
if (pos + 1 < textLength && text.GetCharAt(pos + 1) == '\n')
return new SimpleSegment(pos, 2);
}
return new SimpleSegment(pos, 1);
}
return SimpleSegment.Invalid;
}
}
partial class TextUtilities
{
/// <summary>
/// Finds the next new line character starting at offset.
/// </summary>
/// <param name="text">The text source to search in.</param>
/// <param name="offset">The starting offset for the search.</param>
/// <param name="newLineType">The string representing the new line that was found, or null if no new line was found.</param>
/// <returns>The position of the first new line starting at or after <paramref name="offset"/>,
/// or -1 if no new line was found.</returns>
internal static int FindNextNewLine(ITextSource text, int offset, out string newLineType)
{
if (text == null)
throw new ArgumentNullException(nameof(text));
if (offset < 0 || offset > text.TextLength)
throw new ArgumentOutOfRangeException(nameof(offset), offset, "offset is outside of text source");
var s = NewLineFinder.NextNewLine(text, offset);
if (s == SimpleSegment.Invalid)
{
newLineType = null;
return -1;
}
if (s.Length == 2)
{
newLineType = "\r\n";
}
else if (text.GetCharAt(s.Offset) == '\n')
{
newLineType = "\n";
}
else
{
newLineType = "\r";
}
return s.Offset;
}
/// <summary>
/// Gets whether the specified string is a newline sequence.
/// </summary>
internal static bool IsNewLine(string newLine)
{
return newLine == "\r\n" || newLine == "\n" || newLine == "\r";
}
/// <summary>
/// Normalizes all new lines in <paramref name="input"/> to be <paramref name="newLine"/>.
/// </summary>
internal static string NormalizeNewLines(string input, string newLine)
{
if (input == null)
return null;
if (!IsNewLine(newLine))
throw new ArgumentException("newLine must be one of the known newline sequences");
var ds = NewLineFinder.NextNewLine(input, 0);
if (ds == SimpleSegment.Invalid) // text does not contain any new lines
return input;
var b = new StringBuilder(input.Length);
var lastEndOffset = 0;
do
{
b.Append(input, lastEndOffset, ds.Offset - lastEndOffset);
b.Append(newLine);
lastEndOffset = ds.EndOffset;
ds = NewLineFinder.NextNewLine(input, lastEndOffset);
} while (ds != SimpleSegment.Invalid);
// remaining string (after last newline)
b.Append(input, lastEndOffset, input.Length - lastEndOffset);
return b.ToString();
}
/// <summary>
/// Gets the newline sequence used in the document at the specified line.
/// </summary>
internal static string GetNewLineFromDocument(IDocument document, int lineNumber)
{
var line = document.GetLineByNumber(lineNumber);
if (line.DelimiterLength == 0)
{
// at the end of the document, there's no line delimiter, so use the delimiter
// from the previous line
line = line.PreviousLine;
if (line == null)
return Environment.NewLine;
}
return document.GetText(line.Offset + line.Length, line.DelimiterLength);
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: e000057c8aef84d6d81a07b18c13db7e
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,342 @@
// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using Unity.CodeEditor.Utils;
namespace Unity.CodeEditor.Document
{
/// <summary>
/// Contains predefined offset change mapping types.
/// </summary>
internal enum OffsetChangeMappingType
{
/// <summary>
/// Normal replace.
/// Anchors in front of the replaced region will stay in front, anchors after the replaced region will stay after.
/// Anchors in the middle of the removed region will be deleted. If they survive deletion,
/// they move depending on their AnchorMovementType.
/// </summary>
/// <remarks>
/// This is the default implementation of DocumentChangeEventArgs when OffsetChangeMap is null,
/// so using this option usually works without creating an OffsetChangeMap instance.
/// This is equivalent to an OffsetChangeMap with a single entry describing the replace operation.
/// </remarks>
Normal,
/// <summary>
/// First the old text is removed, then the new text is inserted.
/// Anchors immediately in front (or after) the replaced region may move to the other side of the insertion,
/// depending on the AnchorMovementType.
/// </summary>
/// <remarks>
/// This is implemented as an OffsetChangeMap with two entries: the removal, and the insertion.
/// </remarks>
RemoveAndInsert,
/// <summary>
/// The text is replaced character-by-character.
/// Anchors keep their position inside the replaced text.
/// Anchors after the replaced region will move accordingly if the replacement text has a different length than the replaced text.
/// If the new text is shorter than the old text, anchors inside the old text that would end up behind the replacement text
/// will be moved so that they point to the end of the replacement text.
/// </summary>
/// <remarks>
/// On the OffsetChangeMap level, growing text is implemented by replacing the last character in the replaced text
/// with itself and the additional text segment. A simple insertion of the additional text would have the undesired
/// effect of moving anchors immediately after the replaced text into the replacement text if they used
/// AnchorMovementStyle.BeforeInsertion.
/// Shrinking text is implemented by removing the text segment that's too long; but in a special mode that
/// causes anchors to always survive irrespective of their <see cref="TextAnchor.SurviveDeletion"/> setting.
/// If the text keeps its old size, this is implemented as OffsetChangeMap.Empty.
/// </remarks>
CharacterReplace,
/// <summary>
/// Like 'Normal', but anchors with <see cref="TextAnchor.MovementType"/> = Default will stay in front of the
/// insertion instead of being moved behind it.
/// </summary>
KeepAnchorBeforeInsertion
}
/// <summary>
/// Describes a series of offset changes.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix",
Justification="It's a mapping old offsets -> new offsets")]
internal sealed class OffsetChangeMap : Collection<OffsetChangeMapEntry>
{
/// <summary>
/// Immutable OffsetChangeMap that is empty.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes",
Justification="The Empty instance is immutable")]
internal static readonly OffsetChangeMap Empty = new OffsetChangeMap(new OffsetChangeMapEntry[0], true);
/// <summary>
/// Creates a new OffsetChangeMap with a single element.
/// </summary>
/// <param name="entry">The entry.</param>
/// <returns>Returns a frozen OffsetChangeMap with a single entry.</returns>
internal static OffsetChangeMap FromSingleElement(OffsetChangeMapEntry entry)
{
return new OffsetChangeMap(new[] { entry }, true);
}
/// <summary>
/// Creates a new OffsetChangeMap instance.
/// </summary>
internal OffsetChangeMap()
{
}
internal OffsetChangeMap(int capacity)
: base(new List<OffsetChangeMapEntry>(capacity))
{
}
private OffsetChangeMap(IList<OffsetChangeMapEntry> entries, bool isFrozen)
: base(entries)
{
IsFrozen = isFrozen;
}
/// <summary>
/// Gets the new offset where the specified offset moves after this document change.
/// </summary>
internal int GetNewOffset(int offset, AnchorMovementType movementType = AnchorMovementType.Default)
{
IList<OffsetChangeMapEntry> items = Items;
int count = items.Count;
for (int i = 0; i < count; i++) {
offset = items[i].GetNewOffset(offset, movementType);
}
return offset;
}
/// <summary>
/// Gets whether this OffsetChangeMap is a valid explanation for the specified document change.
/// </summary>
internal bool IsValidForDocumentChange(int offset, int removalLength, int insertionLength)
{
int endOffset = offset + removalLength;
foreach (OffsetChangeMapEntry entry in this) {
// check that ChangeMapEntry is in valid range for this document change
if (entry.Offset < offset || entry.Offset + entry.RemovalLength > endOffset)
return false;
endOffset += entry.InsertionLength - entry.RemovalLength;
}
// check that the total delta matches
return endOffset == offset + insertionLength;
}
/// <summary>
/// Calculates the inverted OffsetChangeMap (used for the undo operation).
/// </summary>
internal OffsetChangeMap Invert()
{
if (this == Empty)
return this;
OffsetChangeMap newMap = new OffsetChangeMap(Count);
for (int i = Count - 1; i >= 0; i--) {
OffsetChangeMapEntry entry = this[i];
// swap InsertionLength and RemovalLength
newMap.Add(new OffsetChangeMapEntry(entry.Offset, entry.InsertionLength, entry.RemovalLength));
}
return newMap;
}
/// <inheritdoc/>
protected override void ClearItems()
{
CheckFrozen();
base.ClearItems();
}
/// <inheritdoc/>
protected override void InsertItem(int index, OffsetChangeMapEntry item)
{
CheckFrozen();
base.InsertItem(index, item);
}
/// <inheritdoc/>
protected override void RemoveItem(int index)
{
CheckFrozen();
base.RemoveItem(index);
}
/// <inheritdoc/>
protected override void SetItem(int index, OffsetChangeMapEntry item)
{
CheckFrozen();
base.SetItem(index, item);
}
private void CheckFrozen()
{
if (IsFrozen)
throw new InvalidOperationException("This instance is frozen and cannot be modified.");
}
/// <summary>
/// Gets if this instance is frozen. Frozen instances are immutable and thus thread-safe.
/// </summary>
internal bool IsFrozen { get; private set; }
/// <summary>
/// Freezes this instance.
/// </summary>
internal void Freeze()
{
IsFrozen = true;
}
}
/// <summary>
/// An entry in the OffsetChangeMap.
/// This represents the offset of a document change (either insertion or removal, not both at once).
/// </summary>
internal struct OffsetChangeMapEntry : IEquatable<OffsetChangeMapEntry>
{
// MSB: DefaultAnchorMovementIsBeforeInsertion
private readonly uint _insertionLengthWithMovementFlag;
// MSB: RemovalNeverCausesAnchorDeletion; other 31 bits: RemovalLength
private readonly uint _removalLengthWithDeletionFlag;
/// <summary>
/// The offset at which the change occurs.
/// </summary>
internal int Offset { get; }
/// <summary>
/// The number of characters inserted.
/// Returns 0 if this entry represents a removal.
/// </summary>
internal int InsertionLength => (int)(_insertionLengthWithMovementFlag & 0x7fffffff);
/// <summary>
/// The number of characters removed.
/// Returns 0 if this entry represents an insertion.
/// </summary>
internal int RemovalLength => (int)(_removalLengthWithDeletionFlag & 0x7fffffff);
/// <summary>
/// Gets whether the removal should not cause any anchor deletions.
/// </summary>
internal bool RemovalNeverCausesAnchorDeletion => (_removalLengthWithDeletionFlag & 0x80000000) != 0;
/// <summary>
/// Gets whether default anchor movement causes the anchor to stay in front of the caret.
/// </summary>
internal bool DefaultAnchorMovementIsBeforeInsertion => (_insertionLengthWithMovementFlag & 0x80000000) != 0;
/// <summary>
/// Gets the new offset where the specified offset moves after this document change.
/// </summary>
internal int GetNewOffset(int oldOffset, AnchorMovementType movementType = AnchorMovementType.Default)
{
int insertionLength = InsertionLength;
int removalLength = RemovalLength;
if (!(removalLength == 0 && oldOffset == Offset)) {
// we're getting trouble (both if statements in here would apply)
// if there's no removal and we insert at the offset
// -> we'd need to disambiguate by movementType, which is handled after the if
// offset is before start of change: no movement
if (oldOffset <= Offset)
return oldOffset;
// offset is after end of change: movement by normal delta
if (oldOffset >= Offset + removalLength)
return oldOffset + insertionLength - removalLength;
}
// we reach this point if
// a) the oldOffset is inside the deleted segment
// b) there was no removal and we insert at the caret position
if (movementType == AnchorMovementType.AfterInsertion)
return Offset + insertionLength;
if (movementType == AnchorMovementType.BeforeInsertion)
return Offset;
return DefaultAnchorMovementIsBeforeInsertion ? Offset : Offset + insertionLength;
}
/// <summary>
/// Creates a new OffsetChangeMapEntry instance.
/// </summary>
internal OffsetChangeMapEntry(int offset, int removalLength, int insertionLength)
{
ThrowUtil.CheckNotNegative(offset, "offset");
ThrowUtil.CheckNotNegative(removalLength, "removalLength");
ThrowUtil.CheckNotNegative(insertionLength, "insertionLength");
Offset = offset;
_removalLengthWithDeletionFlag = (uint)removalLength;
_insertionLengthWithMovementFlag = (uint)insertionLength;
}
/// <summary>
/// Creates a new OffsetChangeMapEntry instance.
/// </summary>
internal OffsetChangeMapEntry(int offset, int removalLength, int insertionLength, bool removalNeverCausesAnchorDeletion, bool defaultAnchorMovementIsBeforeInsertion)
: this(offset, removalLength, insertionLength)
{
if (removalNeverCausesAnchorDeletion)
_removalLengthWithDeletionFlag |= 0x80000000;
if (defaultAnchorMovementIsBeforeInsertion)
_insertionLengthWithMovementFlag |= 0x80000000;
}
/// <inheritdoc/>
public override int GetHashCode()
{
unchecked {
return Offset + 3559 * (int)_insertionLengthWithMovementFlag + 3571 * (int)_removalLengthWithDeletionFlag;
}
}
/// <inheritdoc/>
public override bool Equals(object obj)
{
return obj is OffsetChangeMapEntry && Equals((OffsetChangeMapEntry)obj);
}
/// <inheritdoc/>
public bool Equals(OffsetChangeMapEntry other)
{
return Offset == other.Offset && _insertionLengthWithMovementFlag == other._insertionLengthWithMovementFlag && _removalLengthWithDeletionFlag == other._removalLengthWithDeletionFlag;
}
/// <summary>
/// Tests the two entries for equality.
/// </summary>
public static bool operator ==(OffsetChangeMapEntry left, OffsetChangeMapEntry right)
{
return left.Equals(right);
}
/// <summary>
/// Tests the two entries for inequality.
/// </summary>
public static bool operator !=(OffsetChangeMapEntry left, OffsetChangeMapEntry right)
{
return !left.Equals(right);
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: c75b18825b89d4e2485182ab4ea5ddda
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,161 @@
// 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.CodeAnalysis;
using System.IO;
using Unity.CodeEditor.Utils;
namespace Unity.CodeEditor.Document
{
/// <summary>
/// Implements the ITextSource interface using a rope.
/// </summary>
internal sealed class RopeTextSource : ITextSource
{
private readonly Rope<char> _rope;
/// <summary>
/// Creates a new RopeTextSource.
/// </summary>
internal RopeTextSource(Rope<char> rope)
{
_rope = rope?.Clone() ?? throw new ArgumentNullException(nameof(rope));
}
/// <summary>
/// Creates a new RopeTextSource.
/// </summary>
internal RopeTextSource(Rope<char> rope, ITextSourceVersion version)
{
_rope = rope?.Clone() ?? throw new ArgumentNullException(nameof(rope));
Version = version;
}
/// <summary>
/// Returns a clone of the rope used for this text source.
/// </summary>
/// <remarks>
/// RopeTextSource only publishes a copy of the contained rope to ensure that the underlying rope cannot be modified.
/// </remarks>
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification="Not a property because it creates a clone")]
internal Rope<char> GetRope()
{
return _rope.Clone();
}
/// <inheritdoc/>
public string Text => _rope.ToString();
/// <inheritdoc/>
public int TextLength => _rope.Length;
/// <inheritdoc/>
public char GetCharAt(int offset)
{
return _rope[offset];
}
/// <inheritdoc/>
public string GetText(int offset, int length)
{
return _rope.ToString(offset, length);
}
/// <inheritdoc/>
public ReadOnlyMemory<char> GetTextAsMemory(int offset, int length)
{
return _rope.GetMemory(offset, length);
}
/// <inheritdoc/>
public string GetText(ISegment segment)
{
return _rope.ToString(segment.Offset, segment.Length);
}
/// <inheritdoc/>
public TextReader CreateReader()
{
return new RopeTextReader(_rope);
}
/// <inheritdoc/>
public TextReader CreateReader(int offset, int length)
{
return new RopeTextReader(_rope.GetRange(offset, length));
}
/// <inheritdoc/>
public ITextSource CreateSnapshot()
{
return this;
}
/// <inheritdoc/>
public ITextSource CreateSnapshot(int offset, int length)
{
return new RopeTextSource(_rope.GetRange(offset, length));
}
/// <inheritdoc/>
public int IndexOf(char c, int startIndex, int count)
{
return _rope.IndexOf(c, startIndex, count);
}
/// <inheritdoc/>
public int IndexOfAny(char[] anyOf, int startIndex, int count)
{
return _rope.IndexOfAny(anyOf, startIndex, count);
}
/// <inheritdoc/>
public int LastIndexOf(char c, int startIndex, int count)
{
return _rope.LastIndexOf(c, startIndex, count);
}
/// <inheritdoc/>
public ITextSourceVersion Version { get; }
/// <inheritdoc/>
public int IndexOf(string searchText, int startIndex, int count, StringComparison comparisonType)
{
return _rope.IndexOf(searchText, startIndex, count, comparisonType);
}
/// <inheritdoc/>
public int LastIndexOf(string searchText, int startIndex, int count, StringComparison comparisonType)
{
return _rope.LastIndexOf(searchText, startIndex, count, comparisonType);
}
/// <inheritdoc/>
public void WriteTextTo(TextWriter writer)
{
_rope.WriteTo(writer, 0, _rope.Length);
}
/// <inheritdoc/>
public void WriteTextTo(TextWriter writer, int offset, int length)
{
_rope.WriteTo(writer, offset, length);
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: f053b65364b4545b38e5a456af79939e
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,171 @@
// 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 System.Globalization;
using Unity.CodeEditor.Utils;
namespace Unity.CodeEditor.Document
{
/// <summary>
/// Represents a simple segment (Offset,Length pair) that is not automatically updated
/// on document changes.
/// </summary>
internal struct SimpleSegment : IEquatable<SimpleSegment>, ISegment
{
internal static readonly SimpleSegment Invalid = new SimpleSegment(-1, -1);
/// <summary>
/// Gets the overlapping portion of the segments.
/// Returns SimpleSegment.Invalid if the segments don't overlap.
/// </summary>
internal static SimpleSegment GetOverlap(ISegment segment1, ISegment segment2)
{
var start = Math.Max(segment1.Offset, segment2.Offset);
var end = Math.Min(segment1.EndOffset, segment2.EndOffset);
return end < start ? Invalid : new SimpleSegment(start, end - start);
}
public readonly int Offset, Length;
int ISegment.Offset => Offset;
int ISegment.Length => Length;
public int EndOffset => Offset + Length;
internal SimpleSegment(int offset, int length)
{
Offset = offset;
Length = length;
}
internal SimpleSegment(ISegment segment)
{
Debug.Assert(segment != null);
Offset = segment.Offset;
Length = segment.Length;
}
public override int GetHashCode()
{
unchecked
{
return Offset + 10301 * Length;
}
}
public override bool Equals(object obj)
{
return (obj is SimpleSegment) && Equals((SimpleSegment)obj);
}
public bool Equals(SimpleSegment other)
{
return Offset == other.Offset && Length == other.Length;
}
public static bool operator ==(SimpleSegment left, SimpleSegment right)
{
return left.Equals(right);
}
public static bool operator !=(SimpleSegment left, SimpleSegment right)
{
return !left.Equals(right);
}
/// <inheritdoc/>
public override string ToString()
{
return $"[Offset={Offset}, Length={Length}]";
}
}
/// <summary>
/// A segment using <see cref="TextAnchor"/>s as start and end positions.
/// </summary>
/// <remarks>
/// <para>
/// For the constructors creating new anchors, the start position will be AfterInsertion and the end position will be BeforeInsertion.
/// Should the end position move before the start position, the segment will have length 0.
/// </para>
/// </remarks>
/// <seealso cref="ISegment"/>
/// <seealso cref="TextSegment"/>
internal sealed class AnchorSegment : ISegment
{
private readonly TextAnchor _start;
private readonly TextAnchor _end;
/// <inheritdoc/>
public int Offset => _start.Offset;
/// <inheritdoc/>
public int Length => Math.Max(0, _end.Offset - _start.Offset);
/// <inheritdoc/>
public int EndOffset => Math.Max(_start.Offset, _end.Offset);
/// <summary>
/// Creates a new AnchorSegment using the specified anchors.
/// The anchors must have <see cref="TextAnchor.SurviveDeletion"/> set to true.
/// </summary>
internal AnchorSegment(TextAnchor start, TextAnchor end)
{
if (start == null)
throw new ArgumentNullException(nameof(start));
if (end == null)
throw new ArgumentNullException(nameof(end));
if (!start.SurviveDeletion)
throw new ArgumentException("Anchors for AnchorSegment must use SurviveDeletion", nameof(start));
if (!end.SurviveDeletion)
throw new ArgumentException("Anchors for AnchorSegment must use SurviveDeletion", nameof(end));
_start = start;
_end = end;
}
/// <summary>
/// Creates a new AnchorSegment that creates new anchors.
/// </summary>
internal AnchorSegment(TextDocument document, ISegment segment)
: this(document, ThrowUtil.CheckNotNull(segment, "segment").Offset, segment.Length)
{
}
/// <summary>
/// Creates a new AnchorSegment that creates new anchors.
/// </summary>
internal AnchorSegment(TextDocument document, int offset, int length)
{
_start = document?.CreateAnchor(offset) ?? throw new ArgumentNullException(nameof(document));
_start.SurviveDeletion = true;
_start.MovementType = AnchorMovementType.AfterInsertion;
_end = document.CreateAnchor(offset + length);
_end.SurviveDeletion = true;
_end.MovementType = AnchorMovementType.BeforeInsertion;
}
/// <inheritdoc/>
public override string ToString()
{
return "[Offset=" + Offset.ToString(CultureInfo.InvariantCulture) + ", EndOffset=" + EndOffset.ToString(CultureInfo.InvariantCulture) + "]";
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: f3989142b33d44a0ca19788765ba05cc
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,144 @@
// 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.Document
{
/// <summary>
/// The TextAnchor class references an offset (a position between two characters).
/// It automatically updates the offset when text is inserted/removed in front of the anchor.
/// </summary>
/// <remarks>
/// <para>Use the <see cref="Offset"/> property to get the offset from a text anchor.
/// Use the <see cref="TextDocument.CreateAnchor"/> method to create an anchor from an offset.
/// </para>
/// <para>
/// The document will automatically update all text anchors; and because it uses weak references to do so,
/// the garbage collector can simply collect the anchor object when you don't need it anymore.
/// </para>
/// <para>Moreover, the document is able to efficiently update a large number of anchors without having to look
/// at each anchor object individually. Updating the offsets of all anchors usually only takes time logarithmic
/// to the number of anchors. Retrieving the <see cref="Offset"/> property also runs in O(lg N).</para>
/// <inheritdoc cref="IsDeleted" />
/// <inheritdoc cref="MovementType" />
/// <para>If you want to track a segment, you can use the <see cref="AnchorSegment"/> class which
/// implements <see cref="ISegment"/> using two text anchors.</para>
/// </remarks>
/// <example>
/// Usage:
/// <code>TextAnchor anchor = document.CreateAnchor(offset);
/// ChangeMyDocument();
/// int newOffset = anchor.Offset;
/// </code>
/// </example>
internal sealed class TextAnchor : ITextAnchor
{
internal TextAnchorNode Node { get; set; }
internal TextAnchor(TextDocument document)
{
Document = document;
}
/// <summary>
/// Gets the document owning the anchor.
/// </summary>
internal TextDocument Document { get; }
/// <inheritdoc/>
public AnchorMovementType MovementType { get; set; }
/// <inheritdoc/>
public bool SurviveDeletion { get; set; }
/// <inheritdoc/>
public bool IsDeleted {
get {
Document.DebugVerifyAccess();
return Node == null;
}
}
/// <inheritdoc/>
public event EventHandler Deleted;
internal void OnDeleted(DelayedEvents delayedEvents)
{
Node = null;
delayedEvents.DelayedRaise(Deleted, this, EventArgs.Empty);
}
/// <summary>
/// Gets the offset of the text anchor.
/// </summary>
/// <exception cref="InvalidOperationException">Thrown when trying to get the Offset from a deleted anchor.</exception>
public int Offset {
get {
Document.DebugVerifyAccess();
var n = Node;
if (n == null)
throw new InvalidOperationException();
var offset = n.Length;
if (n.Left != null)
offset += n.Left.TotalLength;
while (n.Parent != null) {
if (n == n.Parent.Right) {
if (n.Parent.Left != null)
offset += n.Parent.Left.TotalLength;
offset += n.Parent.Length;
}
n = n.Parent;
}
return offset;
}
}
/// <summary>
/// Gets the line number of the anchor.
/// </summary>
/// <exception cref="InvalidOperationException">Thrown when trying to get the Offset from a deleted anchor.</exception>
public int Line => Document.GetLineByOffset(Offset).LineNumber;
/// <summary>
/// Gets the column number of this anchor.
/// </summary>
/// <exception cref="InvalidOperationException">Thrown when trying to get the Offset from a deleted anchor.</exception>
public int Column {
get {
var offset = Offset;
return offset - Document.GetLineByOffset(offset).Offset + 1;
}
}
/// <summary>
/// Gets the text location of this anchor.
/// </summary>
/// <exception cref="InvalidOperationException">Thrown when trying to get the Offset from a deleted anchor.</exception>
public TextLocation Location => Document.GetLocation(Offset);
/// <inheritdoc/>
public override string ToString()
{
return "[TextAnchor Offset=" + Offset + "]";
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 6fa7f4f386ba74571bc126c89255222e
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,104 @@
// 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.Document
{
/// <summary>
/// A TextAnchorNode is placed in the TextAnchorTree.
/// It describes a section of text with a text anchor at the end of the section.
/// A weak reference is used to refer to the TextAnchor. (to save memory, we derive from WeakReference instead of referencing it)
/// </summary>
internal sealed class TextAnchorNode : WeakReference
{
internal TextAnchorNode Left { get; set; }
internal TextAnchorNode Right { get; set; }
internal TextAnchorNode Parent { get; set; }
internal bool Color { get; set; }
internal int Length { get; set; }
internal int TotalLength { get; set; } // totalLength = length + left.totalLength + right.totalLength
internal TextAnchorNode(TextAnchor anchor) : base(anchor)
{
}
internal TextAnchorNode LeftMost {
get {
TextAnchorNode node = this;
while (node.Left != null)
node = node.Left;
return node;
}
}
internal TextAnchorNode RightMost {
get {
TextAnchorNode node = this;
while (node.Right != null)
node = node.Right;
return node;
}
}
/// <summary>
/// Gets the inorder successor of the node.
/// </summary>
internal TextAnchorNode Successor {
get {
if (Right != null) {
return Right.LeftMost;
} else {
TextAnchorNode node = this;
TextAnchorNode oldNode;
do {
oldNode = node;
node = node.Parent;
// go up until we are coming out of a left subtree
} while (node != null && node.Right == oldNode);
return node;
}
}
}
/// <summary>
/// Gets the inorder predecessor of the node.
/// </summary>
internal TextAnchorNode Predecessor {
get {
if (Left != null) {
return Left.RightMost;
} else {
TextAnchorNode node = this;
TextAnchorNode oldNode;
do {
oldNode = node;
node = node.Parent;
// go up until we are coming out of a right subtree
} while (node != null && node.Left == oldNode);
return node;
}
}
}
public override string ToString()
{
return "[TextAnchorNode Length=" + Length + " TotalLength=" + TotalLength + " Target=" + Target + "]";
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 8d60b8806ad5a453e978d149b4442288
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,847 @@
// 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 System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Text;
using Unity.CodeEditor.Utils;
namespace Unity.CodeEditor.Document
{
/// <summary>
/// A tree of TextAnchorNodes.
/// </summary>
internal sealed class TextAnchorTree
{
// The text anchor tree has difficult requirements:
// - it must QUICKLY update the offset in all anchors whenever there is a document change
// - it must not reference text anchors directly, using weak references instead
// Clearly, we cannot afford updating an Offset property on all anchors (that would be O(N)).
// So instead, the anchors need to be able to calculate their offset from a data structure
// that can be efficiently updated.
// This implementation is built using an augmented red-black-tree.
// There is a 'TextAnchorNode' for each text anchor.
// Such a node represents a section of text (just the length is stored) with a (weakly referenced) text anchor at the end.
// Basically, you can imagine the list of text anchors as a sorted list of text anchors, where each anchor
// just stores the distance to the previous anchor.
// (next node = TextAnchorNode.Successor, distance = TextAnchorNode.length)
// Distances are never negative, so this representation means anchors are always sorted by offset
// (the order of anchors at the same offset is undefined)
// Of course, a linked list of anchors would be way too slow (one would need to traverse the whole list
// every time the offset of an anchor is being looked up).
// Instead, we use a red-black-tree. We aren't actually using the tree for sorting - it's just a binary tree
// as storage format for what's conceptually a list, the red-black properties are used to keep the tree balanced.
// Other balanced binary trees would work, too.
// What makes the tree-form efficient is that is augments the data by a 'totalLength'. Where 'length'
// represents the distance to the previous node, 'totalLength' is the sum of all 'length' values in the subtree
// under that node.
// This allows computing the Offset from an anchor by walking up the list of parent nodes instead of going
// through all predecessor nodes. So computing the Offset runs in O(log N).
private readonly TextDocument _document;
private readonly List<TextAnchorNode> _nodesToDelete = new List<TextAnchorNode>();
private TextAnchorNode _root;
internal TextAnchorTree(TextDocument document)
{
_document = document;
}
[Conditional("DEBUG")]
private static void Log(string text)
{
Debug.WriteLine("TextAnchorTree: " + text);
}
#region Insert Text
private void InsertText(int offset, int length, bool defaultAnchorMovementIsBeforeInsertion)
{
if (length == 0 || _root == null || offset > _root.TotalLength)
return;
// find the range of nodes that are placed exactly at offset
// beginNode is inclusive, endNode is exclusive
if (offset == _root.TotalLength)
{
PerformInsertText(FindActualBeginNode(_root.RightMost), null, length, defaultAnchorMovementIsBeforeInsertion);
}
else
{
TextAnchorNode endNode = FindNode(ref offset);
Debug.Assert(endNode.Length > 0);
if (offset > 0)
{
// there are no nodes exactly at offset
endNode.Length += length;
UpdateAugmentedData(endNode);
}
else
{
PerformInsertText(FindActualBeginNode(endNode.Predecessor), endNode, length, defaultAnchorMovementIsBeforeInsertion);
}
}
DeleteMarkedNodes();
}
private TextAnchorNode FindActualBeginNode(TextAnchorNode node)
{
// now find the actual beginNode
while (node != null && node.Length == 0)
node = node.Predecessor;
// no predecessor = beginNode is first node in tree
return node ?? _root.LeftMost;
}
// Sorts the nodes in the range [beginNode, endNode) by MovementType
// and inserts the length between the BeforeInsertion and the AfterInsertion nodes.
private void PerformInsertText(TextAnchorNode beginNode, TextAnchorNode endNode, int length, bool defaultAnchorMovementIsBeforeInsertion)
{
Debug.Assert(beginNode != null);
// endNode may be null at the end of the anchor tree
// now we need to sort the nodes in the range [beginNode, endNode); putting those with
// MovementType.BeforeInsertion in front of those with MovementType.AfterInsertion
List<TextAnchorNode> beforeInsert = new List<TextAnchorNode>();
//List<TextAnchorNode> afterInsert = new List<TextAnchorNode>();
TextAnchorNode temp = beginNode;
while (temp != endNode)
{
TextAnchor anchor = (TextAnchor)temp.Target;
if (anchor == null)
{
// afterInsert.Add(temp);
MarkNodeForDelete(temp);
}
else if (defaultAnchorMovementIsBeforeInsertion
? anchor.MovementType != AnchorMovementType.AfterInsertion
: anchor.MovementType == AnchorMovementType.BeforeInsertion)
{
beforeInsert.Add(temp);
// } else {
// afterInsert.Add(temp);
}
temp = temp.Successor;
}
// now again go through the range and swap the nodes with those in the beforeInsert list
temp = beginNode;
foreach (TextAnchorNode node in beforeInsert)
{
SwapAnchors(node, temp);
temp = temp.Successor;
}
// now temp is pointing to the first node that is afterInsert,
// or to endNode, if there is no afterInsert node at the offset
// So add the length to temp
if (temp == null)
{
// temp might be null if endNode==null and no afterInserts
Debug.Assert(endNode == null);
}
else
{
temp.Length += length;
UpdateAugmentedData(temp);
}
}
/// <summary>
/// Swaps the anchors stored in the two nodes.
/// </summary>
private void SwapAnchors(TextAnchorNode n1, TextAnchorNode n2)
{
if (n1 != n2)
{
TextAnchor anchor1 = (TextAnchor)n1.Target;
TextAnchor anchor2 = (TextAnchor)n2.Target;
if (anchor1 == null && anchor2 == null)
{
// -> no swap required
return;
}
n1.Target = anchor2;
n2.Target = anchor1;
if (anchor1 == null)
{
// unmark n1 from deletion, mark n2 for deletion
_nodesToDelete.Remove(n1);
MarkNodeForDelete(n2);
anchor2.Node = n1;
}
else if (anchor2 == null)
{
// unmark n2 from deletion, mark n1 for deletion
_nodesToDelete.Remove(n2);
MarkNodeForDelete(n1);
anchor1.Node = n2;
}
else
{
anchor1.Node = n2;
anchor2.Node = n1;
}
}
}
#endregion
#region Remove or Replace text
internal void HandleTextChange(OffsetChangeMapEntry entry, DelayedEvents delayedEvents)
{
//Log("HandleTextChange(" + entry + ")");
if (entry.RemovalLength == 0)
{
// This is a pure insertion.
// Unlike a replace with removal, a pure insertion can result in nodes at the same location
// to split depending on their MovementType.
// Thus, we handle this case on a separate code path
// (the code below looks like it does something similar, but it can only split
// the set of deletion survivors, not all nodes at an offset)
InsertText(entry.Offset, entry.InsertionLength, entry.DefaultAnchorMovementIsBeforeInsertion);
return;
}
// When handling a replacing text change, we need to:
// - find all anchors in the deleted segment and delete them / move them to the appropriate
// surviving side.
// - adjust the segment size between the left and right side
int offset = entry.Offset;
int remainingRemovalLength = entry.RemovalLength;
// if the text change is happening after the last anchor, we don't have to do anything
if (_root == null || offset >= _root.TotalLength)
return;
TextAnchorNode node = FindNode(ref offset);
TextAnchorNode firstDeletionSurvivor = null;
// go forward through the tree and delete all nodes in the removal segment
while (node != null && offset + remainingRemovalLength > node.Length)
{
TextAnchor anchor = (TextAnchor)node.Target;
if (anchor != null && (anchor.SurviveDeletion || entry.RemovalNeverCausesAnchorDeletion))
{
if (firstDeletionSurvivor == null)
firstDeletionSurvivor = node;
// This node should be deleted, but it wants to survive.
// We'll just remove the deleted length segment, so the node will be positioned
// in front of the removed segment.
remainingRemovalLength -= node.Length - offset;
node.Length = offset;
offset = 0;
UpdateAugmentedData(node);
node = node.Successor;
}
else
{
// delete node
TextAnchorNode s = node.Successor;
remainingRemovalLength -= node.Length;
RemoveNode(node);
// we already deleted the node, don't delete it twice
_nodesToDelete.Remove(node);
anchor?.OnDeleted(delayedEvents);
node = s;
}
}
// 'node' now is the first anchor after the deleted segment.
// If there are no anchors after the deleted segment, 'node' is null.
// firstDeletionSurvivor was set to the first node surviving deletion.
// Because all non-surviving nodes up to 'node' were deleted, the node range
// [firstDeletionSurvivor, node) now refers to the set of all deletion survivors.
// do the remaining job of the removal
if (node != null)
{
node.Length -= remainingRemovalLength;
Debug.Assert(node.Length >= 0);
}
if (entry.InsertionLength > 0)
{
// we are performing a replacement
if (firstDeletionSurvivor != null)
{
// We got deletion survivors which need to be split into BeforeInsertion
// and AfterInsertion groups.
// Take care that we don't regroup everything at offset, but only the deletion
// survivors - from firstDeletionSurvivor (inclusive) to node (exclusive).
// This ensures that nodes immediately before or after the replaced segment
// stay where they are (independent from their MovementType)
PerformInsertText(firstDeletionSurvivor, node, entry.InsertionLength, entry.DefaultAnchorMovementIsBeforeInsertion);
}
else if (node != null)
{
// No deletion survivors:
// just perform the insertion
node.Length += entry.InsertionLength;
}
}
if (node != null)
{
UpdateAugmentedData(node);
}
DeleteMarkedNodes();
}
#endregion
#region Node removal when TextAnchor was GC'ed
private void MarkNodeForDelete(TextAnchorNode node)
{
if (!_nodesToDelete.Contains(node))
_nodesToDelete.Add(node);
}
private void DeleteMarkedNodes()
{
CheckProperties();
while (_nodesToDelete.Count > 0)
{
int pos = _nodesToDelete.Count - 1;
TextAnchorNode n = _nodesToDelete[pos];
// combine section of n with the following section
TextAnchorNode s = n.Successor;
if (s != null)
{
s.Length += n.Length;
}
RemoveNode(n);
if (s != null)
{
UpdateAugmentedData(s);
}
_nodesToDelete.RemoveAt(pos);
CheckProperties();
}
CheckProperties();
}
#endregion
#region FindNode
/// <summary>
/// Finds the node at the specified offset.
/// After the method has run, offset is relative to the beginning of the returned node.
/// </summary>
private TextAnchorNode FindNode(ref int offset)
{
TextAnchorNode n = _root;
while (true)
{
if (n.Left != null)
{
if (offset < n.Left.TotalLength)
{
n = n.Left; // descend into left subtree
continue;
}
offset -= n.Left.TotalLength; // skip left subtree
}
if (!n.IsAlive)
MarkNodeForDelete(n);
if (offset < n.Length)
{
return n; // found correct node
}
offset -= n.Length; // skip this node
if (n.Right != null)
{
n = n.Right; // descend into right subtree
}
else
{
// didn't find any node containing the offset
return null;
}
}
}
#endregion
#region UpdateAugmentedData
private void UpdateAugmentedData(TextAnchorNode n)
{
if (!n.IsAlive)
MarkNodeForDelete(n);
int totalLength = n.Length;
if (n.Left != null)
totalLength += n.Left.TotalLength;
if (n.Right != null)
totalLength += n.Right.TotalLength;
if (n.TotalLength != totalLength)
{
n.TotalLength = totalLength;
if (n.Parent != null)
UpdateAugmentedData(n.Parent);
}
}
#endregion
#region CreateAnchor
internal TextAnchor CreateAnchor(int offset)
{
Log("CreateAnchor(" + offset + ")");
TextAnchor anchor = new TextAnchor(_document);
anchor.Node = new TextAnchorNode(anchor);
if (_root == null)
{
// creating the first text anchor
_root = anchor.Node;
_root.TotalLength = _root.Length = offset;
}
else if (offset >= _root.TotalLength)
{
// append anchor at end of tree
anchor.Node.TotalLength = anchor.Node.Length = offset - _root.TotalLength;
InsertAsRight(_root.RightMost, anchor.Node);
}
else
{
// insert anchor in middle of tree
TextAnchorNode n = FindNode(ref offset);
Debug.Assert(offset < n.Length);
// split segment 'n' at offset
anchor.Node.TotalLength = anchor.Node.Length = offset;
n.Length -= offset;
InsertBefore(n, anchor.Node);
}
DeleteMarkedNodes();
return anchor;
}
private void InsertBefore(TextAnchorNode node, TextAnchorNode newNode)
{
if (node.Left == null)
{
InsertAsLeft(node, newNode);
}
else
{
InsertAsRight(node.Left.RightMost, newNode);
}
}
#endregion
#region Red/Black Tree
internal const bool Red = true;
internal const bool Black = false;
private void InsertAsLeft(TextAnchorNode parentNode, TextAnchorNode newNode)
{
Debug.Assert(parentNode.Left == null);
parentNode.Left = newNode;
newNode.Parent = parentNode;
newNode.Color = Red;
UpdateAugmentedData(parentNode);
FixTreeOnInsert(newNode);
}
private void InsertAsRight(TextAnchorNode parentNode, TextAnchorNode newNode)
{
Debug.Assert(parentNode.Right == null);
parentNode.Right = newNode;
newNode.Parent = parentNode;
newNode.Color = Red;
UpdateAugmentedData(parentNode);
FixTreeOnInsert(newNode);
}
private void FixTreeOnInsert(TextAnchorNode node)
{
Debug.Assert(node != null);
Debug.Assert(node.Color == Red);
Debug.Assert(node.Left == null || node.Left.Color == Black);
Debug.Assert(node.Right == null || node.Right.Color == Black);
TextAnchorNode parentNode = node.Parent;
if (parentNode == null)
{
// we inserted in the root -> the node must be black
// since this is a root node, making the node black increments the number of black nodes
// on all paths by one, so it is still the same for all paths.
node.Color = Black;
return;
}
if (parentNode.Color == Black)
{
// if the parent node where we inserted was black, our red node is placed correctly.
// since we inserted a red node, the number of black nodes on each path is unchanged
// -> the tree is still balanced
return;
}
// parentNode is red, so there is a conflict here!
// because the root is black, parentNode is not the root -> there is a grandparent node
TextAnchorNode grandparentNode = parentNode.Parent;
TextAnchorNode uncleNode = Sibling(parentNode);
if (uncleNode != null && uncleNode.Color == Red)
{
parentNode.Color = Black;
uncleNode.Color = Black;
grandparentNode.Color = Red;
FixTreeOnInsert(grandparentNode);
return;
}
// now we know: parent is red but uncle is black
// First rotation:
if (node == parentNode.Right && parentNode == grandparentNode.Left)
{
RotateLeft(parentNode);
node = node.Left;
}
else if (node == parentNode.Left && parentNode == grandparentNode.Right)
{
RotateRight(parentNode);
node = node.Right;
}
// because node might have changed, reassign variables:
// ReSharper disable once PossibleNullReferenceException
parentNode = node.Parent;
grandparentNode = parentNode.Parent;
// Now recolor a bit:
parentNode.Color = Black;
grandparentNode.Color = Red;
// Second rotation:
if (node == parentNode.Left && parentNode == grandparentNode.Left)
{
RotateRight(grandparentNode);
}
else
{
// because of the first rotation, this is guaranteed:
Debug.Assert(node == parentNode.Right && parentNode == grandparentNode.Right);
RotateLeft(grandparentNode);
}
}
private void RemoveNode(TextAnchorNode removedNode)
{
if (removedNode.Left != null && removedNode.Right != null)
{
// replace removedNode with it's in-order successor
TextAnchorNode leftMost = removedNode.Right.LeftMost;
RemoveNode(leftMost); // remove leftMost from its current location
// and overwrite the removedNode with it
ReplaceNode(removedNode, leftMost);
leftMost.Left = removedNode.Left;
if (leftMost.Left != null) leftMost.Left.Parent = leftMost;
leftMost.Right = removedNode.Right;
if (leftMost.Right != null) leftMost.Right.Parent = leftMost;
leftMost.Color = removedNode.Color;
UpdateAugmentedData(leftMost);
if (leftMost.Parent != null) UpdateAugmentedData(leftMost.Parent);
return;
}
// now either removedNode.left or removedNode.right is null
// get the remaining child
TextAnchorNode parentNode = removedNode.Parent;
TextAnchorNode childNode = removedNode.Left ?? removedNode.Right;
ReplaceNode(removedNode, childNode);
if (parentNode != null) UpdateAugmentedData(parentNode);
if (removedNode.Color == Black)
{
if (childNode != null && childNode.Color == Red)
{
childNode.Color = Black;
}
else
{
FixTreeOnDelete(childNode, parentNode);
}
}
}
private void FixTreeOnDelete(TextAnchorNode node, TextAnchorNode parentNode)
{
Debug.Assert(node == null || node.Parent == parentNode);
if (parentNode == null)
return;
// warning: node may be null
TextAnchorNode sibling = Sibling(node, parentNode);
if (sibling.Color == Red)
{
parentNode.Color = Red;
sibling.Color = Black;
if (node == parentNode.Left)
{
RotateLeft(parentNode);
}
else
{
RotateRight(parentNode);
}
sibling = Sibling(node, parentNode); // update value of sibling after rotation
}
if (parentNode.Color == Black
&& sibling.Color == Black
&& GetColor(sibling.Left) == Black
&& GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
FixTreeOnDelete(parentNode, parentNode.Parent);
return;
}
if (parentNode.Color == Red
&& sibling.Color == Black
&& GetColor(sibling.Left) == Black
&& GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
parentNode.Color = Black;
return;
}
if (node == parentNode.Left &&
sibling.Color == Black &&
GetColor(sibling.Left) == Red &&
GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
sibling.Left.Color = Black;
RotateRight(sibling);
}
else if (node == parentNode.Right &&
sibling.Color == Black &&
GetColor(sibling.Right) == Red &&
GetColor(sibling.Left) == Black)
{
sibling.Color = Red;
sibling.Right.Color = Black;
RotateLeft(sibling);
}
sibling = Sibling(node, parentNode); // update value of sibling after rotation
sibling.Color = parentNode.Color;
parentNode.Color = Black;
if (node == parentNode.Left)
{
if (sibling.Right != null)
{
Debug.Assert(sibling.Right.Color == Red);
sibling.Right.Color = Black;
}
RotateLeft(parentNode);
}
else
{
if (sibling.Left != null)
{
Debug.Assert(sibling.Left.Color == Red);
sibling.Left.Color = Black;
}
RotateRight(parentNode);
}
}
private void ReplaceNode(TextAnchorNode replacedNode, TextAnchorNode newNode)
{
if (replacedNode.Parent == null)
{
Debug.Assert(replacedNode == _root);
_root = newNode;
}
else
{
if (replacedNode.Parent.Left == replacedNode)
replacedNode.Parent.Left = newNode;
else
replacedNode.Parent.Right = newNode;
}
if (newNode != null)
{
newNode.Parent = replacedNode.Parent;
}
replacedNode.Parent = null;
}
private void RotateLeft(TextAnchorNode p)
{
// let q be p's right child
TextAnchorNode q = p.Right;
Debug.Assert(q != null);
Debug.Assert(q.Parent == p);
// set q to be the new root
ReplaceNode(p, q);
// set p's right child to be q's left child
p.Right = q.Left;
if (p.Right != null) p.Right.Parent = p;
// set q's left child to be p
q.Left = p;
p.Parent = q;
UpdateAugmentedData(p);
UpdateAugmentedData(q);
}
private void RotateRight(TextAnchorNode p)
{
// let q be p's left child
TextAnchorNode q = p.Left;
Debug.Assert(q != null);
Debug.Assert(q.Parent == p);
// set q to be the new root
ReplaceNode(p, q);
// set p's left child to be q's right child
p.Left = q.Right;
if (p.Left != null) p.Left.Parent = p;
// set q's right child to be p
q.Right = p;
p.Parent = q;
UpdateAugmentedData(p);
UpdateAugmentedData(q);
}
private static TextAnchorNode Sibling(TextAnchorNode node)
{
if (node == node.Parent.Left)
return node.Parent.Right;
return node.Parent.Left;
}
private static TextAnchorNode Sibling(TextAnchorNode node, TextAnchorNode parentNode)
{
Debug.Assert(node == null || node.Parent == parentNode);
if (node == parentNode.Left)
return parentNode.Right;
return parentNode.Left;
}
private static bool GetColor(TextAnchorNode node)
{
return node != null && node.Color;
}
#endregion
#region CheckProperties
[Conditional("DATACONSISTENCYTEST")]
internal void CheckProperties()
{
#if DEBUG
if (_root != null)
{
CheckProperties(_root);
// check red-black property:
int blackCount = -1;
CheckNodeProperties(_root, null, Red, 0, ref blackCount);
}
#endif
}
#if DEBUG
private void CheckProperties(TextAnchorNode node)
{
int totalLength = node.Length;
if (node.Left != null)
{
CheckProperties(node.Left);
totalLength += node.Left.TotalLength;
}
if (node.Right != null)
{
CheckProperties(node.Right);
totalLength += node.Right.TotalLength;
}
Debug.Assert(node.TotalLength == totalLength);
}
/*
1. A node is either red or black.
2. The root is black.
3. All leaves are black. (The leaves are the NIL children.)
4. Both children of every red node are black. (So every red node must have a black parent.)
5. Every simple path from a node to a descendant leaf contains the same number of black nodes. (Not counting the leaf node.)
*/
[SuppressMessage("ReSharper", "UnusedParameter.Local")]
private void CheckNodeProperties(TextAnchorNode node, TextAnchorNode parentNode, bool parentColor, int blackCount, ref int expectedBlackCount)
{
if (node == null) return;
Debug.Assert(node.Parent == parentNode);
if (parentColor == Red)
{
Debug.Assert(node.Color == Black);
}
if (node.Color == Black)
{
blackCount++;
}
if (node.Left == null && node.Right == null)
{
// node is a leaf node:
if (expectedBlackCount == -1)
expectedBlackCount = blackCount;
else
Debug.Assert(expectedBlackCount == blackCount);
}
CheckNodeProperties(node.Left, node, node.Color, blackCount, ref expectedBlackCount);
CheckNodeProperties(node.Right, node, node.Color, blackCount, ref expectedBlackCount);
}
#endif
#endregion
#region GetTreeAsString
#if DEBUG
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal string GetTreeAsString()
{
if (_root == null)
return "<empty tree>";
StringBuilder b = new StringBuilder();
AppendTreeToString(_root, b, 0);
return b.ToString();
}
private static void AppendTreeToString(TextAnchorNode node, StringBuilder b, int indent)
{
b.Append(node.Color == Red ? "RED " : "BLACK ");
b.AppendLine(node.ToString());
indent += 2;
if (node.Left != null)
{
b.Append(' ', indent);
b.Append("L: ");
AppendTreeToString(node.Left, b, indent);
}
if (node.Right != null)
{
b.Append(' ', indent);
b.Append("R: ");
AppendTreeToString(node.Right, b, indent);
}
}
#endif
#endregion
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 5a50ae8041732462c981b5464a2c568c
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 62446cb4d55e74ea999402dc661a65bf
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,107 @@
// 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.Document
{
/// <summary>
/// Contains weak event managers for the TextDocument events.
/// </summary>
internal static class TextDocumentWeakEventManager
{
/// <summary>
/// Weak event manager for the <see cref="TextDocument.UpdateStarted"/> event.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")]
internal sealed class UpdateStarted : WeakEventManagerBase<UpdateStarted, TextDocument, EventHandler, EventArgs>
{
protected override void StartListening(TextDocument source) => source.UpdateStarted += DeliverEvent;
protected override void StopListening(TextDocument source) => source.UpdateStarted -= DeliverEvent;
}
/// <summary>
/// Weak event manager for the <see cref="TextDocument.UpdateFinished"/> event.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")]
internal sealed class UpdateFinished : WeakEventManagerBase<UpdateFinished, TextDocument, EventHandler, EventArgs>
{
protected override void StartListening(TextDocument source) => source.UpdateFinished += DeliverEvent;
protected override void StopListening(TextDocument source) => source.UpdateFinished -= DeliverEvent;
}
/// <summary>
/// Weak event manager for the <see cref="TextDocument.Changing"/> event.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")]
internal sealed class Changing : WeakEventManagerBase<Changing, TextDocument, EventHandler<DocumentChangeEventArgs>, DocumentChangeEventArgs>
{
protected override void StartListening(TextDocument source) => source.Changing += DeliverEvent;
protected override void StopListening(TextDocument source) => source.Changing -= DeliverEvent;
}
/// <summary>
/// Weak event manager for the <see cref="TextDocument.Changed"/> event.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")]
internal sealed class Changed : WeakEventManagerBase<Changed, TextDocument, EventHandler<DocumentChangeEventArgs>, DocumentChangeEventArgs>
{
protected override void StartListening(TextDocument source) => source.Changed += DeliverEvent;
protected override void StopListening(TextDocument source) => source.Changed -= DeliverEvent;
}
/// <summary>
/// Weak event manager for the <see cref="TextDocument.LineCountChanged"/> event.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")]
internal sealed class LineCountChanged : WeakEventManagerBase<LineCountChanged, TextDocument, EventHandler, EventArgs>
{
protected override void StartListening(TextDocument source) => source.LineCountChanged += DeliverEvent;
protected override void StopListening(TextDocument source) => source.LineCountChanged -= DeliverEvent;
}
/// <summary>
/// Weak event manager for the <see cref="TextDocument.TextLengthChanged"/> event.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")]
internal sealed class TextLengthChanged : WeakEventManagerBase<TextLengthChanged, TextDocument, EventHandler, EventArgs>
{
protected override void StartListening(TextDocument source) => source.TextLengthChanged += DeliverEvent;
protected override void StopListening(TextDocument source) => source.TextLengthChanged -= DeliverEvent;
}
/// <summary>
/// Weak event manager for the <see cref="TextDocument.TextChanged"/> event.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")]
internal sealed class TextChanged : WeakEventManagerBase<TextChanged, TextDocument, EventHandler, EventArgs>
{
protected override void StartListening(TextDocument source) => source.TextChanged += DeliverEvent;
protected override void StopListening(TextDocument source) => source.TextChanged -= DeliverEvent;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 4e43250273a4d4b3392541c97d1eb150
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,255 @@
// Copyright (c) 2010-2013 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.Globalization;
using System.ComponentModel;
namespace Unity.CodeEditor.Document
{
/// <summary>
/// A line/column position.
/// Text editor lines/columns are counted started from one.
/// </summary>
/// <remarks>
/// The document provides the methods <see cref="IDocument.GetLocation"/> and
/// <see cref="IDocument.GetOffset(TextLocation)"/> to convert between offsets and TextLocations.
/// </remarks>
[TypeConverter(typeof(TextLocationConverter))]
internal struct TextLocation : IComparable<TextLocation>, IEquatable<TextLocation>
{
/// <summary>
/// Represents no text location (0, 0).
/// </summary>
internal static readonly TextLocation Empty = new TextLocation(0, 0);
/// <summary>
/// Creates a TextLocation instance.
/// </summary>
internal TextLocation(int line, int column)
{
Line = line;
Column = column;
}
/// <summary>
/// Gets the line number.
/// </summary>
internal int Line { get; }
/// <summary>
/// Gets the column number.
/// </summary>
internal int Column { get; }
/// <summary>
/// Gets whether the TextLocation instance is empty.
/// </summary>
internal bool IsEmpty => Column <= 0 && Line <= 0;
/// <summary>
/// Gets a string representation for debugging purposes.
/// </summary>
public override string ToString()
{
return string.Format(CultureInfo.InvariantCulture, "(Line {1}, Col {0})", Column, Line);
}
/// <summary>
/// Gets a hash code.
/// </summary>
public override int GetHashCode()
{
return unchecked(191 * Column.GetHashCode() ^ Line.GetHashCode());
}
/// <summary>
/// Equality test.
/// </summary>
public override bool Equals(object obj)
{
if (!(obj is TextLocation)) return false;
return (TextLocation)obj == this;
}
/// <summary>
/// Equality test.
/// </summary>
public bool Equals(TextLocation other)
{
return this == other;
}
/// <summary>
/// Equality test.
/// </summary>
public static bool operator ==(TextLocation left, TextLocation right)
{
return left.Column == right.Column && left.Line == right.Line;
}
/// <summary>
/// Inequality test.
/// </summary>
public static bool operator !=(TextLocation left, TextLocation right)
{
return left.Column != right.Column || left.Line != right.Line;
}
/// <summary>
/// Compares two text locations.
/// </summary>
public static bool operator <(TextLocation left, TextLocation right)
{
if (left.Line < right.Line)
return true;
if (left.Line == right.Line)
return left.Column < right.Column;
return false;
}
/// <summary>
/// Compares two text locations.
/// </summary>
public static bool operator >(TextLocation left, TextLocation right)
{
if (left.Line > right.Line)
return true;
if (left.Line == right.Line)
return left.Column > right.Column;
return false;
}
/// <summary>
/// Compares two text locations.
/// </summary>
public static bool operator <=(TextLocation left, TextLocation right)
{
return !(left > right);
}
/// <summary>
/// Compares two text locations.
/// </summary>
public static bool operator >=(TextLocation left, TextLocation right)
{
return !(left < right);
}
/// <summary>
/// Compares two text locations.
/// </summary>
public int CompareTo(TextLocation other)
{
if (this == other)
return 0;
if (this < other)
return -1;
return 1;
}
}
/// <summary>
/// Converts strings of the form '0+[;,]0+' to a <see cref="TextLocation"/>.
/// </summary>
internal class TextLocationConverter : TypeConverter
{
/// <inheritdoc/>
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
return sourceType == typeof(string);
}
/// <inheritdoc/>
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
return destinationType == typeof(TextLocation);
}
/// <inheritdoc/>
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
var s = value as string;
var parts = s?.Split(';', ',');
if (parts?.Length == 2)
{
return new TextLocation(int.Parse(parts[0], culture), int.Parse(parts[1], culture));
}
throw new InvalidOperationException();
}
/// <inheritdoc/>
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
if (value is TextLocation loc && destinationType == typeof(string))
{
return loc.Line.ToString(culture) + ";" + loc.Column.ToString(culture);
}
throw new InvalidOperationException();
}
}
/// <summary>
/// An (Offset,Length)-pair.
/// </summary>
internal interface ISegment
{
/// <summary>
/// Gets the start offset of the segment.
/// </summary>
int Offset { get; }
/// <summary>
/// Gets the length of the segment.
/// </summary>
/// <remarks>For line segments (IDocumentLine), the length does not include the line delimeter.</remarks>
int Length { get; }
/// <summary>
/// Gets the end offset of the segment.
/// </summary>
/// <remarks>EndOffset = Offset + Length;</remarks>
int EndOffset { get; }
}
/// <summary>
/// Extension methods for <see cref="ISegment"/>.
/// </summary>
internal static class SegmentExtensions
{
/// <summary>
/// Gets whether <paramref name="segment"/> fully contains the specified segment.
/// </summary>
/// <remarks>
/// Use <c>segment.Contains(offset, 0)</c> to detect whether a segment (end inclusive) contains offset;
/// use <c>segment.Contains(offset, 1)</c> to detect whether a segment (end exclusive) contains offset.
/// </remarks>
internal static bool Contains(this ISegment segment, int offset, int length)
{
return segment.Offset <= offset && offset + length <= segment.EndOffset;
}
/// <summary>
/// Gets whether <paramref name="thisSegment"/> fully contains the specified segment.
/// </summary>
internal static bool Contains(this ISegment thisSegment, ISegment segment)
{
return segment != null && thisSegment.Offset <= segment.Offset && segment.EndOffset <= thisSegment.EndOffset;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 690c38bf24d7648d381bc95a526c5f29
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,278 @@
// 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;
namespace Unity.CodeEditor.Document
{
/// <summary>
/// A segment that can be put into a <see cref="TextSegmentCollection{T}"/>.
/// </summary>
/// <remarks>
/// <para>
/// A <see cref="TextSegment"/> can be stand-alone or part of a <see cref="TextSegmentCollection{T}"/>.
/// If the segment is stored inside a TextSegmentCollection, its Offset and Length will be updated by that collection.
/// </para>
/// <para>
/// When the document changes, the offsets of all text segments in the TextSegmentCollection will be adjusted accordingly.
/// Start offsets move like <see cref="AnchorMovementType">AnchorMovementType.AfterInsertion</see>,
/// end offsets move like <see cref="AnchorMovementType">AnchorMovementType.BeforeInsertion</see>
/// (i.e. the segment will always stay as small as possible).</para>
/// <para>
/// If a document change causes a segment to be deleted completely, it will be reduced to length 0, but segments are
/// never automatically removed from the collection.
/// Segments with length 0 will never expand due to document changes, and they move as <c>AfterInsertion</c>.
/// </para>
/// <para>
/// Thread-safety: a TextSegmentCollection that is connected to a <see cref="TextDocument"/> may only be used on that document's owner thread.
/// A disconnected TextSegmentCollection is safe for concurrent reads, but concurrent access is not safe when there are writes.
/// Keep in mind that reading the Offset properties of a text segment inside the collection is a read access on the
/// collection; and setting an Offset property of a text segment is a write access on the collection.
/// </para>
/// </remarks>
/// <seealso cref="ISegment"/>
/// <seealso cref="AnchorSegment"/>
/// <seealso cref="TextSegmentCollection{T}"/>
internal class TextSegment : ISegment
{
internal ISegmentTree OwnerTree { get; set; }
internal TextSegment Left { get; set; }
internal TextSegment Right { get; set; }
internal TextSegment Parent { get; set; }
/// <summary>
/// The color of the segment in the red/black tree.
/// </summary>
internal bool Color { get; set; }
/// <summary>
/// The "length" of the node (distance to previous node)
/// </summary>
internal int NodeLength { get; set; }
/// <summary>
/// The total "length" of this subtree.
/// </summary>
internal int TotalNodeLength { get; set; } // totalNodeLength = nodeLength + left.totalNodeLength + right.totalNodeLength
/// <summary>
/// The length of the segment (do not confuse with nodeLength).
/// </summary>
internal int SegmentLength { get; set; }
/// <summary>
/// distanceToMaxEnd = Max(segmentLength,
/// left.distanceToMaxEnd + left.Offset - Offset,
/// left.distanceToMaxEnd + right.Offset - Offset)
/// </summary>
internal int DistanceToMaxEnd { get; set; }
int ISegment.Offset => StartOffset;
/// <summary>
/// Gets whether this segment is connected to a TextSegmentCollection and will automatically
/// update its offsets.
/// </summary>
protected bool IsConnectedToCollection => OwnerTree != null;
/// <summary>
/// Gets/Sets the start offset of the segment.
/// </summary>
/// <remarks>
/// When setting the start offset, the end offset will change, too: the Length of the segment will stay constant.
/// </remarks>
internal int StartOffset
{
get
{
// If the segment is not connected to a tree, we store the offset in "nodeLength".
// Otherwise, "nodeLength" contains the distance to the start offset of the previous node
Debug.Assert(!(OwnerTree == null && Parent != null));
Debug.Assert(!(OwnerTree == null && Left != null));
var n = this;
var offset = n.NodeLength;
if (n.Left != null)
offset += n.Left.TotalNodeLength;
while (n.Parent != null)
{
if (n == n.Parent.Right)
{
if (n.Parent.Left != null)
offset += n.Parent.Left.TotalNodeLength;
offset += n.Parent.NodeLength;
}
n = n.Parent;
}
return offset;
}
set
{
if (value < 0)
throw new ArgumentOutOfRangeException(nameof(value), "Offset must not be negative");
if (StartOffset != value)
{
// need a copy of the variable because ownerTree.Remove() sets this.ownerTree to null
var ownerTree = OwnerTree;
if (ownerTree != null)
{
ownerTree.Remove(this);
NodeLength = value;
ownerTree.Add(this);
}
else
{
NodeLength = value;
}
OnSegmentChanged();
}
}
}
/// <summary>
/// Gets/Sets the end offset of the segment.
/// </summary>
/// <remarks>
/// Setting the end offset will change the length, the start offset will stay constant.
/// </remarks>
public int EndOffset
{
get => StartOffset + Length;
set
{
var newLength = value - StartOffset;
if (newLength < 0)
throw new ArgumentOutOfRangeException(nameof(value), "EndOffset must be greater or equal to StartOffset");
Length = newLength;
}
}
/// <summary>
/// Gets/Sets the length of the segment.
/// </summary>
/// <remarks>
/// Setting the length will change the end offset, the start offset will stay constant.
/// </remarks>
public int Length
{
get => SegmentLength;
set
{
if (value < 0)
throw new ArgumentOutOfRangeException(nameof(value), "Length must not be negative");
if (SegmentLength != value)
{
SegmentLength = value;
OwnerTree?.UpdateAugmentedData(this);
OnSegmentChanged();
}
}
}
/// <summary>
/// This method gets called when the StartOffset/Length/EndOffset properties are set.
/// It is not called when StartOffset/Length/EndOffset change due to document changes
/// </summary>
protected virtual void OnSegmentChanged()
{
}
internal TextSegment LeftMost
{
get
{
var node = this;
while (node.Left != null)
node = node.Left;
return node;
}
}
internal TextSegment RightMost
{
get
{
var node = this;
while (node.Right != null)
node = node.Right;
return node;
}
}
/// <summary>
/// Gets the inorder successor of the node.
/// </summary>
internal TextSegment Successor
{
get
{
if (Right != null)
{
return Right.LeftMost;
}
var node = this;
TextSegment oldNode;
do
{
oldNode = node;
node = node.Parent;
// go up until we are coming out of a left subtree
} while (node != null && node.Right == oldNode);
return node;
}
}
/// <summary>
/// Gets the inorder predecessor of the node.
/// </summary>
internal TextSegment Predecessor
{
get
{
if (Left != null)
{
return Left.RightMost;
}
var node = this;
TextSegment oldNode;
do
{
oldNode = node;
node = node.Parent;
// go up until we are coming out of a right subtree
} while (node != null && node.Left == oldNode);
return node;
}
}
#if DEBUG
internal string ToDebugString()
{
return
$"[nodeLength={NodeLength} totalNodeLength={TotalNodeLength} distanceToMaxEnd={DistanceToMaxEnd} MaxEndOffset={StartOffset + DistanceToMaxEnd}]";
}
#endif
/// <inheritdoc/>
public override string ToString()
{
return $"[{GetType().Name} Offset={StartOffset} Length={Length} EndOffset={EndOffset}]";
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 3a70b5eaccc1e42a99eadc319fa45595
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 7289a765b886748bcb6d677f6977fc52
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,127 @@
// 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.Diagnostics;
using System.Linq;
using Unity.CodeEditor.Utils;
namespace Unity.CodeEditor.Document
{
/// <summary>
/// Provides ITextSourceVersion instances.
/// </summary>
internal class TextSourceVersionProvider
{
private Version _currentVersion;
/// <summary>
/// Creates a new TextSourceVersionProvider instance.
/// </summary>
internal TextSourceVersionProvider()
{
_currentVersion = new Version(this);
}
/// <summary>
/// Gets the current version.
/// </summary>
internal ITextSourceVersion CurrentVersion => _currentVersion;
/// <summary>
/// Replaces the current version with a new version.
/// </summary>
/// <param name="change">Change from current version to new version</param>
internal void AppendChange(TextChangeEventArgs change)
{
_currentVersion.Change = change ?? throw new ArgumentNullException(nameof(change));
_currentVersion.Next = new Version(_currentVersion);
_currentVersion = _currentVersion.Next;
}
[DebuggerDisplay("Version #{" + nameof(_id) + "}")]
private sealed class Version : ITextSourceVersion
{
// Reference back to the provider.
// Used to determine if two checkpoints belong to the same document.
private readonly TextSourceVersionProvider _provider;
// ID used for CompareAge()
private readonly int _id;
// the change from this version to the next version
internal TextChangeEventArgs Change;
public Version Next;
public Version(TextSourceVersionProvider provider)
{
_provider = provider;
}
public Version(Version prev)
{
_provider = prev._provider;
_id = unchecked(prev._id + 1);
}
public bool BelongsToSameDocumentAs(ITextSourceVersion other)
{
var o = other as Version;
return o != null && _provider == o._provider;
}
public int CompareAge(ITextSourceVersion other)
{
if (other == null)
throw new ArgumentNullException(nameof(other));
var o = other as Version;
if (o == null || _provider != o._provider)
throw new ArgumentException("Versions do not belong to the same document.");
// We will allow overflows, but assume that the maximum distance between checkpoints is 2^31-1.
// This is guaranteed on x86 because so many checkpoints don't fit into memory.
return Math.Sign(unchecked(_id - o._id));
}
public IEnumerable<TextChangeEventArgs> GetChangesTo(ITextSourceVersion other)
{
var result = CompareAge(other);
var o = (Version)other;
if (result < 0)
return GetForwardChanges(o);
if (result > 0)
return o.GetForwardChanges(this).Reverse().Select(c => c.Invert());
return Array.Empty<TextChangeEventArgs>();
}
private IEnumerable<TextChangeEventArgs> GetForwardChanges(Version other)
{
// Return changes from this(inclusive) to other(exclusive).
for (var node = this; node != other; node = node.Next)
{
yield return node.Change;
}
}
public int MoveOffsetTo(ITextSourceVersion other, int oldOffset, AnchorMovementType movement)
{
return GetChangesTo(other)
.Aggregate(oldOffset, (current, e) => e.GetNewOffset(current, movement));
}
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 17cae8c12182e4a88b5695b1b2eea5cd
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,453 @@
// 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.Globalization;
using System.Reflection;
namespace Unity.CodeEditor.Document
{
internal enum LogicalDirection
{
Backward,
Forward
}
/// <summary>
/// Specifies the mode for getting the next caret position.
/// </summary>
internal enum CaretPositioningMode
{
/// <summary>
/// Normal positioning (stop after every grapheme)
/// </summary>
Normal,
/// <summary>
/// Stop only on word borders.
/// </summary>
WordBorder,
/// <summary>
/// Stop only at the beginning of words. This is used for Ctrl+Left/Ctrl+Right.
/// </summary>
WordStart,
/// <summary>
/// Stop only at the beginning of words, and anywhere in the middle of symbols.
/// </summary>
WordStartOrSymbol,
/// <summary>
/// Stop only on word borders, and anywhere in the middle of symbols.
/// </summary>
WordBorderOrSymbol,
/// <summary>
/// Stop between every Unicode codepoint, even within the same grapheme.
/// This is used to implement deleting the previous grapheme when Backspace is pressed.
/// </summary>
EveryCodepoint
}
/// <summary>
/// Static helper methods for working with text.
/// </summary>
internal static partial class TextUtilities
{
#region GetControlCharacterName
// the names of the first 32 ASCII characters = Unicode C0 block
private static readonly string[] C0Table = {
"NUL", "SOH", "STX", "ETX", "EOT", "ENQ", "ACK", "BEL", "BS", "HT",
"LF", "VT", "FF", "CR", "SO", "SI", "DLE", "DC1", "DC2", "DC3",
"DC4", "NAK", "SYN", "ETB", "CAN", "EM", "SUB", "ESC", "FS", "GS",
"RS", "US"
};
// DEL (ASCII 127) and
// the names of the control characters in the C1 block (Unicode 128 to 159)
private static readonly string[] DelAndC1Table = {
"DEL",
"PAD", "HOP", "BPH", "NBH", "IND", "NEL", "SSA", "ESA", "HTS", "HTJ",
"VTS", "PLD", "PLU", "RI", "SS2", "SS3", "DCS", "PU1", "PU2", "STS",
"CCH", "MW", "SPA", "EPA", "SOS", "SGCI", "SCI", "CSI", "ST", "OSC",
"PM", "APC"
};
/// <summary>
/// Gets the name of the control character.
/// For unknown characters, the unicode codepoint is returned as 4-digit hexadecimal value.
/// </summary>
internal static string GetControlCharacterName(char controlCharacter)
{
int num = controlCharacter;
if (num < C0Table.Length)
return C0Table[num];
if (num >= 127 && num <= 159)
return DelAndC1Table[num - 127];
return num.ToString("x4", CultureInfo.InvariantCulture);
}
#endregion
#region GetWhitespace
/// <summary>
/// Gets all whitespace (' ' and '\t', but no newlines) after offset.
/// </summary>
/// <param name="textSource">The text source.</param>
/// <param name="offset">The offset where the whitespace starts.</param>
/// <returns>The segment containing the whitespace.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")]
internal static ISegment GetWhitespaceAfter(ITextSource textSource, int offset)
{
if (textSource == null)
throw new ArgumentNullException(nameof(textSource));
int pos;
for (pos = offset; pos < textSource.TextLength; pos++)
{
char c = textSource.GetCharAt(pos);
if (c != ' ' && c != '\t')
break;
}
return new SimpleSegment(offset, pos - offset);
}
/// <summary>
/// Gets all whitespace (' ' and '\t', but no newlines) before offset.
/// </summary>
/// <param name="textSource">The text source.</param>
/// <param name="offset">The offset where the whitespace ends.</param>
/// <returns>The segment containing the whitespace.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")]
internal static ISegment GetWhitespaceBefore(ITextSource textSource, int offset)
{
if (textSource == null)
throw new ArgumentNullException(nameof(textSource));
int pos;
for (pos = offset - 1; pos >= 0; pos--)
{
char c = textSource.GetCharAt(pos);
if (c != ' ' && c != '\t')
break;
}
pos++; // go back the one character that isn't whitespace
return new SimpleSegment(pos, offset - pos);
}
/// <summary>
/// Gets the leading whitespace segment on the document line.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters",
Justification = "Parameter cannot be ITextSource because it must belong to the DocumentLine")]
internal static ISegment GetLeadingWhitespace(TextDocument document, DocumentLine documentLine)
{
if (documentLine == null)
throw new ArgumentNullException(nameof(documentLine));
return GetWhitespaceAfter(document, documentLine.Offset);
}
/// <summary>
/// Gets the trailing whitespace segment on the document line.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters",
Justification = "Parameter cannot be ITextSource because it must belong to the DocumentLine")]
internal static ISegment GetTrailingWhitespace(TextDocument document, DocumentLine documentLine)
{
if (documentLine == null)
throw new ArgumentNullException(nameof(documentLine));
ISegment segment = GetWhitespaceBefore(document, documentLine.EndOffset);
// If the whole line consists of whitespace, we consider all of it as leading whitespace,
// so return an empty segment as trailing whitespace.
if (segment.Offset == documentLine.Offset)
return new SimpleSegment(documentLine.EndOffset, 0);
else
return segment;
}
#endregion
#region GetSingleIndentationSegment
/// <summary>
/// Gets a single indentation segment starting at <paramref name="offset"/> - at most one tab
/// or <paramref name="indentationSize"/> spaces.
/// </summary>
/// <param name="textSource">The text source.</param>
/// <param name="offset">The offset where the indentation segment starts.</param>
/// <param name="indentationSize">The size of an indentation unit. See <see cref="TextEditorOptions.IndentationSize"/>.</param>
/// <returns>The indentation segment.
/// If there is no indentation character at the specified <paramref name="offset"/>,
/// an empty segment is returned.</returns>
internal static ISegment GetSingleIndentationSegment(ITextSource textSource, int offset, int indentationSize)
{
if (textSource == null)
throw new ArgumentNullException(nameof(textSource));
int pos = offset;
while (pos < textSource.TextLength)
{
char c = textSource.GetCharAt(pos);
if (c == '\t')
{
if (pos == offset)
return new SimpleSegment(offset, 1);
else
break;
}
else if (c == ' ')
{
if (pos - offset >= indentationSize)
break;
}
else
{
break;
}
// continue only if c==' ' and (pos-offset)<tabSize
pos++;
}
return new SimpleSegment(offset, pos - offset);
}
#endregion
#region GetCharacterClass
/// <summary>
/// Gets whether the character is whitespace, part of an identifier, or line terminator.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "c")]
internal static CharacterClass GetCharacterClass(char c)
{
if (c == '\r' || c == '\n')
return CharacterClass.LineTerminator;
if (c == '_')
return CharacterClass.IdentifierPart;
return GetCharacterClass(GetUnicodeCategory(c));
}
private static CharacterClass GetCharacterClass(char highSurrogate, char lowSurrogate)
{
if (char.IsSurrogatePair(highSurrogate, lowSurrogate))
{
return GetCharacterClass(GetUnicodeCategoryString(highSurrogate.ToString() + lowSurrogate, 0));
}
// malformed surrogate pair
return CharacterClass.Other;
}
private static readonly Func<char, UnicodeCategory> GetUnicodeCategory = (Func<char, UnicodeCategory>)typeof(char)
.GetRuntimeMethod("GetUnicodeCategory", new[] { typeof(char) })
.CreateDelegate(typeof(Func<char, UnicodeCategory>));
private static readonly Func<string, int, UnicodeCategory> GetUnicodeCategoryString = (Func<string, int, UnicodeCategory>)typeof(char)
.GetRuntimeMethod("GetUnicodeCategory", new[] { typeof(string), typeof(int) })
.CreateDelegate(typeof(Func<string, int, UnicodeCategory>));
private static CharacterClass GetCharacterClass(UnicodeCategory c)
{
switch (c)
{
case UnicodeCategory.SpaceSeparator:
case UnicodeCategory.LineSeparator:
case UnicodeCategory.ParagraphSeparator:
case UnicodeCategory.Control:
return CharacterClass.Whitespace;
case UnicodeCategory.UppercaseLetter:
case UnicodeCategory.LowercaseLetter:
case UnicodeCategory.TitlecaseLetter:
case UnicodeCategory.ModifierLetter:
case UnicodeCategory.OtherLetter:
case UnicodeCategory.DecimalDigitNumber:
return CharacterClass.IdentifierPart;
case UnicodeCategory.NonSpacingMark:
case UnicodeCategory.SpacingCombiningMark:
case UnicodeCategory.EnclosingMark:
return CharacterClass.CombiningMark;
default:
return CharacterClass.Other;
}
}
#endregion
#region GetNextCaretPosition
/// <summary>
/// Gets the next caret position.
/// </summary>
/// <param name="textSource">The text source.</param>
/// <param name="offset">The start offset inside the text source.</param>
/// <param name="direction">The search direction (forwards or backwards).</param>
/// <param name="mode">The mode for caret positioning.</param>
/// <returns>The offset of the next caret position, or -1 if there is no further caret position
/// in the text source.</returns>
/// <remarks>
/// This method is NOT equivalent to the actual caret movement when using VisualLine.GetNextCaretPosition.
/// In real caret movement, there are additional caret stops at line starts and ends. This method
/// treats linefeeds as simple whitespace.
/// </remarks>
internal static int GetNextCaretPosition(ITextSource textSource, int offset, LogicalDirection direction, CaretPositioningMode mode)
{
if (textSource == null)
throw new ArgumentNullException(nameof(textSource));
switch (mode)
{
case CaretPositioningMode.Normal:
case CaretPositioningMode.EveryCodepoint:
case CaretPositioningMode.WordBorder:
case CaretPositioningMode.WordBorderOrSymbol:
case CaretPositioningMode.WordStart:
case CaretPositioningMode.WordStartOrSymbol:
break; // OK
default:
throw new ArgumentException("Unsupported CaretPositioningMode: " + mode, nameof(mode));
}
if (direction != LogicalDirection.Backward
&& direction != LogicalDirection.Forward)
{
throw new ArgumentException("Invalid LogicalDirection: " + direction, nameof(direction));
}
int textLength = textSource.TextLength;
if (textLength <= 0)
{
// empty document? has a normal caret position at 0, though no word borders
if (IsNormal(mode))
{
if (offset > 0 && direction == LogicalDirection.Backward) return 0;
if (offset < 0 && direction == LogicalDirection.Forward) return 0;
}
return -1;
}
while (true)
{
int nextPos = (direction == LogicalDirection.Backward) ? offset - 1 : offset + 1;
// return -1 if there is no further caret position in the text source
// we also need this to handle offset values outside the valid range
if (nextPos < 0 || nextPos > textLength)
return -1;
// check if we've run against the textSource borders.
// a 'textSource' usually isn't the whole document, but a single VisualLineElement.
if (nextPos == 0)
{
// at the document start, there's only a word border
// if the first character is not whitespace
if (IsNormal(mode) || !char.IsWhiteSpace(textSource.GetCharAt(0)))
return nextPos;
}
else if (nextPos == textLength)
{
// at the document end, there's never a word start
if (mode != CaretPositioningMode.WordStart && mode != CaretPositioningMode.WordStartOrSymbol)
{
// at the document end, there's only a word border
// if the last character is not whitespace
if (IsNormal(mode) || !char.IsWhiteSpace(textSource.GetCharAt(textLength - 1)))
return nextPos;
}
}
else
{
char charBefore = textSource.GetCharAt(nextPos - 1);
char charAfter = textSource.GetCharAt(nextPos);
// Don't stop in the middle of a surrogate pair
if (!char.IsSurrogatePair(charBefore, charAfter))
{
CharacterClass classBefore = GetCharacterClass(charBefore);
CharacterClass classAfter = GetCharacterClass(charAfter);
// get correct class for characters outside BMP:
if (char.IsLowSurrogate(charBefore) && nextPos >= 2)
{
classBefore = GetCharacterClass(textSource.GetCharAt(nextPos - 2), charBefore);
}
if (char.IsHighSurrogate(charAfter) && nextPos + 1 < textLength)
{
classAfter = GetCharacterClass(charAfter, textSource.GetCharAt(nextPos + 1));
}
if (StopBetweenCharacters(mode, classBefore, classAfter))
{
return nextPos;
}
}
}
// we'll have to continue searching...
offset = nextPos;
}
}
private static bool IsNormal(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool StopBetweenCharacters(CaretPositioningMode mode, CharacterClass charBefore, CharacterClass charAfter)
{
if (mode == CaretPositioningMode.EveryCodepoint)
return true;
// Don't stop in the middle of a grapheme
if (charAfter == CharacterClass.CombiningMark)
return false;
// Stop after every grapheme in normal mode
if (mode == CaretPositioningMode.Normal)
return true;
if (charBefore == charAfter)
{
if (charBefore == CharacterClass.Other &&
(mode == CaretPositioningMode.WordBorderOrSymbol || mode == CaretPositioningMode.WordStartOrSymbol))
{
// With the "OrSymbol" modes, there's a word border and start between any two unknown characters
return true;
}
}
else
{
// this looks like a possible border
// if we're looking for word starts, check that this is a word start (and not a word end)
// if we're just checking for word borders, accept unconditionally
if (!((mode == CaretPositioningMode.WordStart || mode == CaretPositioningMode.WordStartOrSymbol)
&& (charAfter == CharacterClass.Whitespace || charAfter == CharacterClass.LineTerminator)))
{
return true;
}
}
return false;
}
#endregion
}
/// <summary>
/// Classifies a character as whitespace, line terminator, part of an identifier, or other.
/// </summary>
internal enum CharacterClass
{
/// <summary>
/// The character is not whitespace, line terminator or part of an identifier.
/// </summary>
Other,
/// <summary>
/// The character is whitespace (but not line terminator).
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")]
Whitespace,
/// <summary>
/// The character can be part of an identifier (Letter, digit or underscore).
/// </summary>
IdentifierPart,
/// <summary>
/// The character is line terminator (\r or \n).
/// </summary>
LineTerminator,
/// <summary>
/// The character is a unicode combining mark that modifies the previous character.
/// Corresponds to the Unicode designations "Mn", "Mc" and "Me".
/// </summary>
CombiningMark
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: ee168e8444b3b420eba9eff487b036ca
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,78 @@
// 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.Utils;
namespace Unity.CodeEditor.Document
{
/// <summary>
/// This class stacks the last x operations from the undostack and makes
/// one undo/redo operation from it.
/// </summary>
internal sealed class UndoOperationGroup : IUndoableOperationWithContext
{
private readonly IUndoableOperation[] _undolist;
internal UndoOperationGroup(Deque<IUndoableOperation> stack, int numops)
{
if (stack == null) {
throw new ArgumentNullException(nameof(stack));
}
Debug.Assert(numops > 0 , "UndoOperationGroup : numops should be > 0");
Debug.Assert(numops <= stack.Count);
_undolist = new IUndoableOperation[numops];
for (var i = 0; i < numops; ++i) {
_undolist[i] = stack.PopBack();
}
}
public void Undo()
{
foreach (var t in _undolist)
{
t.Undo();
}
}
public void Undo(UndoStack stack)
{
foreach (var t in _undolist)
{
stack.RunUndo(t);
}
}
public void Redo()
{
for (var i = _undolist.Length - 1; i >= 0; --i) {
_undolist[i].Redo();
}
}
public void Redo(UndoStack stack)
{
for (var i = _undolist.Length - 1; i >= 0; --i) {
stack.RunRedo(_undolist[i]);
}
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 420fb70569c5a44e19076a23cf7a7cce
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,472 @@
// 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.ComponentModel;
using System.Diagnostics;
using Unity.CodeEditor.Utils;
namespace Unity.CodeEditor.Document
{
/// <summary>
/// Undo stack implementation.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
internal sealed class UndoStack : INotifyPropertyChanged
{
/// undo stack is listening for changes
internal const int StateListen = 0;
/// undo stack is reverting/repeating a set of changes
internal const int StatePlayback = 1;
// undo stack is reverting/repeating a set of changes and modifies the document to do this
internal const int StatePlaybackModifyDocument = 2;
/// state is used for checking that noone but the UndoStack performs changes
/// during Undo events
internal int State { get; set; } = StateListen;
private readonly Deque<IUndoableOperation> _undostack = new Deque<IUndoableOperation>();
private readonly Deque<IUndoableOperation> _redostack = new Deque<IUndoableOperation>();
private int _sizeLimit = int.MaxValue;
private int _undoGroupDepth;
private int _actionCountInUndoGroup;
private int _optionalActionCount;
private bool _allowContinue;
#region IsOriginalFile implementation
// implements feature request SD2-784 - File still considered dirty after undoing all changes
/// <summary>
/// Number of times undo must be executed until the original state is reached.
/// Negative: number of times redo must be executed until the original state is reached.
/// Special case: int.MinValue == original state is unreachable
/// </summary>
private int _elementsOnUndoUntilOriginalFile;
/// <summary>
/// Gets whether the document is currently in its original state (no modifications).
/// </summary>
internal bool IsOriginalFile { get; private set; } = true;
private void RecalcIsOriginalFile()
{
var newIsOriginalFile = (_elementsOnUndoUntilOriginalFile == 0);
if (newIsOriginalFile != IsOriginalFile)
{
IsOriginalFile = newIsOriginalFile;
NotifyPropertyChanged("IsOriginalFile");
}
}
/// <summary>
/// Marks the current state as original. Discards any previous "original" markers.
/// </summary>
internal void MarkAsOriginalFile()
{
_elementsOnUndoUntilOriginalFile = 0;
RecalcIsOriginalFile();
}
/// <summary>
/// Discards the current "original" marker.
/// </summary>
internal void DiscardOriginalFileMarker()
{
_elementsOnUndoUntilOriginalFile = int.MinValue;
RecalcIsOriginalFile();
}
private void FileModified(int newElementsOnUndoStack)
{
if (_elementsOnUndoUntilOriginalFile == int.MinValue)
return;
_elementsOnUndoUntilOriginalFile += newElementsOnUndoStack;
if (_elementsOnUndoUntilOriginalFile > _undostack.Count)
_elementsOnUndoUntilOriginalFile = int.MinValue;
// don't call RecalcIsOriginalFile(): wait until end of undo group
}
#endregion
/// <summary>
/// Gets if the undo stack currently accepts changes.
/// Is false while an undo action is running.
/// </summary>
internal bool AcceptChanges => State == StateListen;
/// <summary>
/// Gets if there are actions on the undo stack.
/// Use the PropertyChanged event to listen to changes of this property.
/// </summary>
internal bool CanUndo => _undostack.Count > 0;
/// <summary>
/// Gets if there are actions on the redo stack.
/// Use the PropertyChanged event to listen to changes of this property.
/// </summary>
internal bool CanRedo => _redostack.Count > 0;
/// <summary>
/// Gets/Sets the limit on the number of items on the undo stack.
/// </summary>
/// <remarks>The size limit is enforced only on the number of stored top-level undo groups.
/// Elements within undo groups do not count towards the size limit.</remarks>
internal int SizeLimit
{
get => _sizeLimit;
set
{
if (value < 0)
ThrowUtil.CheckNotNegative(value, "value");
if (_sizeLimit != value)
{
_sizeLimit = value;
NotifyPropertyChanged("SizeLimit");
if (_undoGroupDepth == 0)
EnforceSizeLimit();
}
}
}
private void EnforceSizeLimit()
{
Debug.Assert(_undoGroupDepth == 0);
while (_undostack.Count > _sizeLimit)
_undostack.PopFront();
while (_redostack.Count > _sizeLimit)
_redostack.PopFront();
}
/// <summary>
/// If an undo group is open, gets the group descriptor of the current top-level
/// undo group.
/// If no undo group is open, gets the group descriptor from the previous undo group.
/// </summary>
/// <remarks>The group descriptor can be used to join adjacent undo groups:
/// use a group descriptor to mark your changes, and on the second action,
/// compare LastGroupDescriptor and use <see cref="StartContinuedUndoGroup"/> if you
/// want to join the undo groups.</remarks>
internal object LastGroupDescriptor { get; private set; }
/// <summary>
/// Starts grouping changes.
/// Maintains a counter so that nested calls are possible.
/// </summary>
internal void StartUndoGroup()
{
StartUndoGroup(null);
}
/// <summary>
/// Starts grouping changes.
/// Maintains a counter so that nested calls are possible.
/// </summary>
/// <param name="groupDescriptor">An object that is stored with the undo group.
/// If this is not a top-level undo group, the parameter is ignored.</param>
internal void StartUndoGroup(object groupDescriptor)
{
if (_undoGroupDepth == 0)
{
_actionCountInUndoGroup = 0;
_optionalActionCount = 0;
LastGroupDescriptor = groupDescriptor;
}
_undoGroupDepth++;
//Util.LoggingService.Debug("Open undo group (new depth=" + undoGroupDepth + ")");
}
/// <summary>
/// Starts grouping changes, continuing with the previously closed undo group if possible.
/// Maintains a counter so that nested calls are possible.
/// If the call to StartContinuedUndoGroup is a nested call, it behaves exactly
/// as <see cref="StartUndoGroup()"/>, only top-level calls can continue existing undo groups.
/// </summary>
/// <param name="groupDescriptor">An object that is stored with the undo group.
/// If this is not a top-level undo group, the parameter is ignored.</param>
internal void StartContinuedUndoGroup(object groupDescriptor = null)
{
if (_undoGroupDepth == 0)
{
_actionCountInUndoGroup = (_allowContinue && _undostack.Count > 0) ? 1 : 0;
_optionalActionCount = 0;
LastGroupDescriptor = groupDescriptor;
}
_undoGroupDepth++;
//Util.LoggingService.Debug("Continue undo group (new depth=" + undoGroupDepth + ")");
}
/// <summary>
/// Stops grouping changes.
/// </summary>
internal void EndUndoGroup()
{
if (_undoGroupDepth == 0) throw new InvalidOperationException("There are no open undo groups");
_undoGroupDepth--;
//Util.LoggingService.Debug("Close undo group (new depth=" + undoGroupDepth + ")");
if (_undoGroupDepth == 0)
{
Debug.Assert(State == StateListen || _actionCountInUndoGroup == 0);
_allowContinue = true;
if (_actionCountInUndoGroup == _optionalActionCount)
{
// only optional actions: don't store them
for (var i = 0; i < _optionalActionCount; i++)
{
_undostack.PopBack();
}
_allowContinue = false;
}
else if (_actionCountInUndoGroup > 1)
{
// combine all actions within the group into a single grouped action
_undostack.PushBack(new UndoOperationGroup(_undostack, _actionCountInUndoGroup));
FileModified(-_actionCountInUndoGroup + 1 + _optionalActionCount);
}
//if (state == StateListen) {
EnforceSizeLimit();
RecalcIsOriginalFile(); // can raise event
//}
}
}
/// <summary>
/// Throws an InvalidOperationException if an undo group is current open.
/// </summary>
private void ThrowIfUndoGroupOpen()
{
if (_undoGroupDepth != 0)
{
_undoGroupDepth = 0;
throw new InvalidOperationException("No undo group should be open at this point");
}
if (State != StateListen)
{
throw new InvalidOperationException("This method cannot be called while an undo operation is being performed");
}
}
private List<TextDocument> _affectedDocuments;
internal void RegisterAffectedDocument(TextDocument document)
{
if (_affectedDocuments == null)
_affectedDocuments = new List<TextDocument>();
if (!_affectedDocuments.Contains(document))
{
_affectedDocuments.Add(document);
document.BeginUpdate();
}
}
private void CallEndUpdateOnAffectedDocuments()
{
if (_affectedDocuments != null)
{
foreach (var doc in _affectedDocuments)
{
doc.EndUpdate();
}
_affectedDocuments = null;
}
}
/// <summary>
/// Call this method to undo the last operation on the stack
/// </summary>
internal void Undo()
{
ThrowIfUndoGroupOpen();
if (_undostack.Count > 0)
{
// disallow continuing undo groups after undo operation
LastGroupDescriptor = null; _allowContinue = false;
// fetch operation to undo and move it to redo stack
var uedit = _undostack.PopBack();
_redostack.PushBack(uedit);
State = StatePlayback;
try
{
RunUndo(uedit);
}
finally
{
State = StateListen;
FileModified(-1);
CallEndUpdateOnAffectedDocuments();
}
RecalcIsOriginalFile();
if (_undostack.Count == 0)
NotifyPropertyChanged("CanUndo");
if (_redostack.Count == 1)
NotifyPropertyChanged("CanRedo");
}
}
internal void RunUndo(IUndoableOperation op)
{
if (op is IUndoableOperationWithContext opWithCtx)
opWithCtx.Undo(this);
else
op.Undo();
}
/// <summary>
/// Call this method to redo the last undone operation
/// </summary>
internal void Redo()
{
ThrowIfUndoGroupOpen();
if (_redostack.Count > 0)
{
LastGroupDescriptor = null;
_allowContinue = false;
var uedit = _redostack.PopBack();
_undostack.PushBack(uedit);
State = StatePlayback;
try
{
RunRedo(uedit);
}
finally
{
State = StateListen;
FileModified(1);
CallEndUpdateOnAffectedDocuments();
}
RecalcIsOriginalFile();
if (_redostack.Count == 0)
NotifyPropertyChanged("CanRedo");
if (_undostack.Count == 1)
NotifyPropertyChanged("CanUndo");
}
}
internal void RunRedo(IUndoableOperation op)
{
if (op is IUndoableOperationWithContext opWithCtx)
opWithCtx.Redo(this);
else
op.Redo();
}
/// <summary>
/// Call this method to push an UndoableOperation on the undostack.
/// The redostack will be cleared if you use this method.
/// </summary>
internal void Push(IUndoableOperation operation)
{
Push(operation, false);
}
/// <summary>
/// Call this method to push an UndoableOperation on the undostack.
/// However, the operation will be only stored if the undo group contains a
/// non-optional operation.
/// Use this method to store the caret position/selection on the undo stack to
/// prevent having only actions that affect only the caret and not the document.
/// </summary>
internal void PushOptional(IUndoableOperation operation)
{
if (_undoGroupDepth == 0)
throw new InvalidOperationException("Cannot use PushOptional outside of undo group");
Push(operation, true);
}
private void Push(IUndoableOperation operation, bool isOptional)
{
if (operation == null)
{
throw new ArgumentNullException(nameof(operation));
}
if (State == StateListen && _sizeLimit > 0)
{
var wasEmpty = _undostack.Count == 0;
var needsUndoGroup = _undoGroupDepth == 0;
if (needsUndoGroup) StartUndoGroup();
_undostack.PushBack(operation);
_actionCountInUndoGroup++;
if (isOptional)
_optionalActionCount++;
else
FileModified(1);
if (needsUndoGroup) EndUndoGroup();
if (wasEmpty)
NotifyPropertyChanged("CanUndo");
ClearRedoStack();
}
}
/// <summary>
/// Call this method, if you want to clear the redo stack
/// </summary>
internal void ClearRedoStack()
{
if (_redostack.Count != 0)
{
_redostack.Clear();
NotifyPropertyChanged("CanRedo");
// if the "original file" marker is on the redo stack: remove it
if (_elementsOnUndoUntilOriginalFile < 0)
_elementsOnUndoUntilOriginalFile = int.MinValue;
}
}
/// <summary>
/// Clears both the undo and redo stack.
/// </summary>
internal void ClearAll()
{
ThrowIfUndoGroupOpen();
_actionCountInUndoGroup = 0;
_optionalActionCount = 0;
if (_undostack.Count != 0)
{
LastGroupDescriptor = null;
_allowContinue = false;
_undostack.Clear();
NotifyPropertyChanged("CanUndo");
}
ClearRedoStack();
}
internal void Push(TextDocument document, DocumentChangeEventArgs e)
{
if (State == StatePlayback)
throw new InvalidOperationException("Document changes during undo/redo operations are not allowed.");
if (State == StatePlaybackModifyDocument)
State = StatePlayback; // allow only 1 change per expected modification
else
Push(new DocumentChangeOperation(document, e));
}
/// <summary>
/// Is raised when a property (CanUndo, CanRedo) changed.
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string propertyName)
{
var args = new PropertyChangedEventArgs(propertyName);
PropertyChanged?.Invoke(this, args);
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: fdc8bc956a06142009aad60c2e917c9b
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,105 @@
// 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.Document
{
/// <summary>
/// Allows registering a line tracker on a TextDocument using a weak reference from the document to the line tracker.
/// </summary>
internal sealed class WeakLineTracker : ILineTracker
{
private TextDocument _textDocument;
private readonly WeakReference _targetObject;
private WeakLineTracker(TextDocument textDocument, ILineTracker targetTracker)
{
_textDocument = textDocument;
_targetObject = new WeakReference(targetTracker);
}
/// <summary>
/// Registers the <paramref name="targetTracker"/> as line tracker for the <paramref name="textDocument"/>.
/// A weak reference to the target tracker will be used, and the WeakLineTracker will deregister itself
/// when the target tracker is garbage collected.
/// </summary>
internal static WeakLineTracker Register(TextDocument textDocument, ILineTracker targetTracker)
{
if (textDocument == null)
throw new ArgumentNullException(nameof(textDocument));
if (targetTracker == null)
throw new ArgumentNullException(nameof(targetTracker));
var wlt = new WeakLineTracker(textDocument, targetTracker);
textDocument.LineTrackers.Add(wlt);
return wlt;
}
/// <summary>
/// Deregisters the weak line tracker.
/// </summary>
internal void Deregister()
{
if (_textDocument != null)
{
_textDocument.LineTrackers.Remove(this);
_textDocument = null;
}
}
void ILineTracker.BeforeRemoveLine(DocumentLine line)
{
if (_targetObject.Target is ILineTracker targetTracker)
targetTracker.BeforeRemoveLine(line);
else
Deregister();
}
void ILineTracker.SetLineLength(DocumentLine line, int newTotalLength)
{
if (_targetObject.Target is ILineTracker targetTracker)
targetTracker.SetLineLength(line, newTotalLength);
else
Deregister();
}
void ILineTracker.LineInserted(DocumentLine insertionPos, DocumentLine newLine)
{
if (_targetObject.Target is ILineTracker targetTracker)
targetTracker.LineInserted(insertionPos, newLine);
else
Deregister();
}
void ILineTracker.RebuildDocument()
{
if (_targetObject.Target is ILineTracker targetTracker)
targetTracker.RebuildDocument();
else
Deregister();
}
void ILineTracker.ChangeComplete(DocumentChangeEventArgs e)
{
if (_targetObject.Target is ILineTracker targetTracker)
targetTracker.ChangeComplete(e);
else
Deregister();
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 5ace82b9e549646ee8414b4ac05f7a3c
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 69545da8115b7fd459252e2795b975da
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -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:

Some files were not shown because too many files have changed in this diff Show More