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,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: