Пример #1
0
        private void CreateStub(int position, ITextChange change)
        {
            string text = this._view.TextSnapshot.ToString();
            using (ITextEdit editor = this._view.TextBuffer.CreateEdit())
            {
                try
                {
                    this.tabs = StubUtils.GetIndention(position, this._view.TextSnapshot, true);
                    string summaryString = StubUtils.Options.MultiLineSummary ? NewLine() : "";
                    string parameters = getFunctionParameters(position);
                    string returnTag = getReturnTag(position);
                    string commentBody = summaryString + parameters + returnTag;
                    string autoComment = this.tabs + "/**" + commentBody;
                    if (!String.IsNullOrEmpty(commentBody))
                    {
                        autoComment += Environment.NewLine + this.tabs;
                    }

                    autoComment += " */";

                    int lineStart = this._view.TextSnapshot.GetLineFromPosition(position).Start.Position;
                    Span firstLineSpan = new Span(lineStart, change.NewSpan.End - lineStart);
                    editor.Replace(firstLineSpan, autoComment);
                    ITextSnapshotLine prevLine = this._view.TextSnapshot.GetLineFromPosition(position);

                    var after = editor.Apply();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(errorMsgPrefix + ex.Message);
                }
            }
        }
Пример #2
0
        private void CreateNewCommentLine(ITextChange change)
        {
            using (ITextEdit editor = this._view.TextBuffer.CreateEdit())
            {
                try
                {
                    ITextSnapshotLine line     = this._view.TextSnapshot.GetLineFromPosition(change.OldEnd);
                    string            lineText = line.GetText();
                    string            nextLine = this._view.TextSnapshot.GetLineFromLineNumber(line.LineNumber + 1).GetText();
                    if (commentLineStart.IsMatch(lineText) && (commentLineStart.IsMatch(nextLine) || change.OldEnd != line.End.Position))
                    {
                        int asteriskIndex = lineText.IndexOf('*');
                        //Only add a new comment line if the newline char is after the triple slash
                        //(how Visual Studio in C# works)
                        if ((line.Start.Position + asteriskIndex) > change.OldEnd)
                        {
                            return;
                        }

                        int tabsStopIndex = -1;
                        if (asteriskIndex >= 0 || lineText.Contains("/**"))
                        {
                            // There's no slash, or its open-comment line, so it's a jsdoc comment. We need asteriskIndex here.
                            tabsStopIndex = asteriskIndex;
                        }

                        string newTabs = tabsStopIndex >= 0 ? lineText.Substring(0, tabsStopIndex) : "";
                        newTabs = newTabs.Replace('/', ' ');
                        editor.Replace(change.NewSpan, Environment.NewLine + newTabs + "* ");
                        editor.Apply();
                    }
                }
                catch (Exception) { }
            }
        }
        private void OnTextChange(ITextChange textChange)
        {
            int index = 0;

            // Move past the keys that don't matter
            while (index < _adornmentCache.Count && _adornmentCache[index].Position < textChange.OldPosition)
            {
                index++;
            }

            if (textChange.Delta < 0)
            {
                // Remove the items which were in the deleted
                while (index < _adornmentCache.Count && _adornmentCache[index].Position < textChange.OldEnd)
                {
                    _adornmentCache.RemoveAt(index);
                }
            }

            // Now adjust everything after the possible delete by the new value
            while (index < _adornmentCache.Count)
            {
                var old = _adornmentCache[index];
                _adornmentCache[index] = new AdornmentData(old.Position + textChange.Delta, old.Adornment);
                index++;
            }
        }
Пример #4
0
        public static List <string> GetLines(this ITextChange change)
        {
            List <string> lines        = new List <string>();
            var           changeLength = change.NewText.Length;

            if (changeLength > 0)
            {
                StringBuilder sb      = new StringBuilder();
                int           currInd = 0;
                do
                {
                    sb.Append(change.NewText[currInd]);
                    if (change.NewText[currInd] == '\n')
                    {
                        lines.Add(sb.ToString());
                        sb.Clear();
                    }
                }while (++currInd < changeLength);

                if (sb.Length > 0)
                {
                    lines.Add(sb.ToString());
                }
            }
            return(lines);
        }
        public void onTextChanged(ITextChange change)
        {
            if (recordingInProgress)
            {
                int currentPos = change.NewPosition;
                if (currentPos != pos)
                {
                    writeString();
                    setNewCursorPosition(currentPos);
                }

                String newText = change.NewText;
                String oldText = change.OldText;

                if (oldText.Length == 0)
                {
                    buffer += newText;
                    pos += newText.Length;

                    if (pos != change.NewEnd)
                    {
                        writeString();
                        setNewCursorPosition(change.NewEnd);
                    }
                }
            }
        }
Пример #6
0
        private void CreateNewCommentLine(ITextChange change)
        {
            using (ITextEdit editor = this._view.TextBuffer.CreateEdit())
            {
                try
                {
                    ITextSnapshotLine line = this._view.TextSnapshot.GetLineFromPosition(change.OldEnd);
                    string lineText = line.GetText();
                    string nextLine = this._view.TextSnapshot.GetLineFromLineNumber(line.LineNumber + 1).GetText();
                    if (commentLineStart.IsMatch(lineText) && (commentLineStart.IsMatch(nextLine) || change.OldEnd != line.End.Position))
                    {
                        int asteriskIndex = lineText.IndexOf('*');
                        //Only add a new comment line if the newline char is after the triple slash
                        //(how Visual Studio in C# works)
                        if ((line.Start.Position + asteriskIndex) > change.OldEnd)
                            return;

                        int tabsStopIndex = -1;
                        if (asteriskIndex >= 0 || lineText.Contains("/**"))
                        {
                            // There's no slash, or its open-comment line, so it's a jsdoc comment. We need asteriskIndex here.
                            tabsStopIndex = asteriskIndex;
                        }

                        string newTabs = tabsStopIndex >= 0 ? lineText.Substring(0, tabsStopIndex) : "";
                        newTabs = newTabs.Replace('/', ' ');
                        editor.Replace(change.NewSpan, Environment.NewLine + newTabs + "* ");
                        editor.Apply();
                    }
                }
                catch (Exception) { }
            }
        }
Пример #7
0
        private void CreateNewCommentLine(ITextChange change)
        {
            using (ITextEdit editor = this._view.TextBuffer.CreateEdit())
            {
                try
                {
                    ITextSnapshotLine line = this._view.TextSnapshot.GetLineFromPosition(change.OldEnd);
                    string lineText = line.GetText();
                    string nextLine = this._view.TextSnapshot.GetLineFromLineNumber(line.LineNumber + 1).GetText();
                    if (lineText.Trim().StartsWith("///") && (nextLine.Trim().StartsWith("///") || change.OldEnd != line.End.Position))
                    {
                        int slashIndex = lineText.IndexOf('/');
                        //Only add a new comment line if the newline char is after the triple slash
                        //(how Visual Studio in C# works)
                        if ((line.Start.Position + 3 + slashIndex) > change.OldEnd)
                            return;

                        string newTabs = lineText.Substring(0, slashIndex);
                        editor.Replace(change.NewSpan, Environment.NewLine + newTabs + "/// ");
                        editor.Apply();
                    }
                }
                catch (Exception) { }
            }
        }
        public void TryCloseTag(ITextChange textChange, IList <TextManipulation> manipulations)
        {
            var currentTag = _state.ParseCurrentTagName();

            if (textChange.NewText == "/" && !string.IsNullOrEmpty(currentTag) && currentTag != "/")
            {
                var  text = _text.Span;
                int  pos  = _state.ParserPos;
                char c    = ' ';
                while (char.IsWhiteSpace(c) && text.Length > pos + 1)
                {
                    pos++;
                    c = text[pos];
                }

                bool tagAlreadyClosed = c == '>';
                if (!tagAlreadyClosed)
                {
                    manipulations.Add(TextManipulation.Insert(_position + 1, $">"));
                }
                else
                {
                    var closingTagPos = FindClosingTag(currentTag, pos + 1);
                    if (closingTagPos != null)
                    {
                        manipulations.Add(TextManipulation.Insert(_position + 1, $">"));
                        manipulations.Add(TextManipulation.Delete(_position + 1, closingTagPos.Value - _position));
                    }
                }
            }
        }
        private bool PeviewTextTypedIs(ITextChange change, string character)
        {
            int    i        = change.OldEnd;
            string lineText = this.view.TextSnapshot.GetLineFromPosition(i - 1).GetText();

            return(lineText.EndsWith(character));
        }
Пример #10
0
        public void ApplyTextChange(ITextSnapshot before, ITextSnapshot after, ITextChange change)
        {
            List <TrackingToken> forRemoval = GetInvalidated(before, change);
            // Some of the tokens marked for removal must be deleted before applying a new version,
            // because otherwise some trackingtokens will have broken spans
            int i = 0;

            for (; i < forRemoval.Count; i++)
            {
                tree.Remove(forRemoval[i]);
            }
            CurrentSnapshot = after;
            IList <TrackingToken> updated = Rescan(forRemoval, before, change.Delta);

            for (; i < forRemoval.Count; i++)
            {
                tree.Remove(forRemoval[i]);
            }
            foreach (var token in updated)
            {
                tree.Add(token);
            }
            RaiseTokensChanged(updated);
            CheckChanges(change);
        }
Пример #11
0
        /// <summary>
        /// Converts list of text changes in a text buffer to a collection of
        /// changes that are relative one to another.
        /// </summary>
        /// <param name="changes">Sorted collection of changes</param>
        /// <returns>Collection of relative changes</returns>
        public static List <TextChangeEventArgs> ConvertToRelative(TextContentChangedEventArgs changeInfo)
        {
            IList <ITextChange> changes = changeInfo.Changes;
            var          list           = new List <TextChangeEventArgs>(changes.Count);
            ITextChange  previousChange = null;
            TextProvider oldText        = new TextProvider(changeInfo.Before, true);
            TextProvider newText        = new TextProvider(changeInfo.After, true);

            for (int i = 0; i < changes.Count; i++)
            {
                var change = changes[i];

                if (previousChange != null)
                {
                    if (previousChange.OldEnd > change.OldPosition || previousChange.NewEnd > change.NewPosition)
                    {
                        throw new ArgumentException("List of changes must not overlap", "changes");
                    }
                }

                var textChange = new TextChangeEventArgs(change.NewPosition, change.OldPosition, change.OldLength, change.NewLength, oldText, newText);
                list.Add(textChange);

                previousChange = change;
            }

            return(list);
        }
Пример #12
0
        private void CreateNewCommentLine(ITextChange change)
        {
            using (ITextEdit editor = this._view.TextBuffer.CreateEdit())
            {
                try
                {
                    ITextSnapshotLine line     = this._view.TextSnapshot.GetLineFromPosition(change.OldEnd);
                    string            lineText = line.GetText();
                    string            nextLine = this._view.TextSnapshot.GetLineFromLineNumber(line.LineNumber + 1).GetText();
                    if (lineText.Trim().StartsWith("///") && (nextLine.Trim().StartsWith("///") || change.OldEnd != line.End.Position))
                    {
                        int slashIndex = lineText.IndexOf('/');
                        //Only add a new comment line if the newline char is after the triple slash
                        //(how Visual Studio in C# works)
                        if ((line.Start.Position + 3 + slashIndex) > change.OldEnd)
                        {
                            return;
                        }

                        string newTabs = lineText.Substring(0, slashIndex);
                        editor.Replace(change.NewSpan, Environment.NewLine + newTabs + "/// ");
                        editor.Apply();
                    }
                }
                catch (Exception) { }
            }
        }
Пример #13
0
        /// <summary>
        /// Builds the comment stub and inserts it into the editor.
        /// </summary>
        /// <param name="position">The position of the last slash.</param>
        private void CreateStub(int position, ITextChange change)
        {
            string text = this._view.TextSnapshot.ToString();

            using (ITextEdit editor = this._view.TextBuffer.CreateEdit())
            {
                try
                {
                    this.tabs = StubUtils.GetIndention(position, this._view.TextSnapshot);
                    string summaryTag  = generateSummaryTag();
                    string parameters  = getFunctionParameters(position);
                    string returnTag   = getReturnTag(position);
                    string autoComment = summaryTag + parameters + returnTag;

                    int  lineStart     = this._view.TextSnapshot.GetLineFromPosition(position).Start.Position;
                    var  caretPosition = autoComment.IndexOf(StubUtils.CaretPlaceholder);
                    Span firstLineSpan = new Span(lineStart, change.NewSpan.End - lineStart);
                    autoComment = autoComment.Replace(StubUtils.CaretPlaceholder, "");

                    editor.Replace(firstLineSpan, autoComment);
                    ITextSnapshotLine prevLine = this._view.TextSnapshot.GetLineFromPosition(position);

                    StubUtils.MoveCaretAfterChange(this._view, this.editor, lineStart + caretPosition);

                    var after = editor.Apply();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(errorMsgPrefix + ex.Message);
                }
            }
        }
 public int IndexOf(ITextChange item) {
     for (int i = 0; i < _changes.Length; i++) {
         if (_changes[i] == item) {
             return i;
         }
     }
     return -1;
 }
Пример #15
0
 private void HandleChange(ITextChange c)
 {
     /*
      * ITextEdit edit = this.view.TextBuffer.CreateEdit();
      * edit.Insert(c.NewEnd-1, "!");
      * edit.Apply();
      */
 }
        private void CreateMethodComment(ITextChange change)
        {
            int    position = change.NewEnd;
            string text     = this.view.TextSnapshot.ToString();

            using (ITextEdit editor = this.view.TextBuffer.CreateEdit())
            {
                try
                {
                    this.tabs = StubUtils.GetIndention(position, this.view.TextSnapshot);
                    string summaryString = StubUtils.Options.MultiLineSummary ? NewLine() : "";


                    string parameters = GetFunctionParameters(position);
                    string returnTag  = GetReturnTag(position);


                    string commentBody = summaryString + parameters + returnTag;
                    string autoComment = this.tabs + "/**" + commentBody;
                    if (!String.IsNullOrEmpty(commentBody))
                    {
                        autoComment += Environment.NewLine + this.tabs;
                    }

                    autoComment += " */";


                    int  lineStart     = this.view.TextSnapshot.GetLineFromPosition(position).Start.Position;
                    Span firstLineSpan = new Span(lineStart, change.NewSpan.End - lineStart);
                    editor.Replace(firstLineSpan, autoComment);

                    ITextSnapshot after = editor.Apply();

                    ////Move the caret back at the comment description

                    //int lineNumber = after.GetLineNumberFromPosition(change.NewPosition);
                    //var lineSnapShotPoint = after.GetLineFromLineNumber(lineNumber).End;
                    //this.view.Caret.MoveTo(lineSnapShotPoint);

                    //view.Caret.MoveTo(
                    //    view.GetTextViewLineContainingBufferPosition(
                    //        after.GetLineFromPosition(
                    //            after.GetText().IndexOf(autoComment)).Start));


                    //view.Caret.MoveTo(
                    //    view.GetTextViewLineContainingBufferPosition(
                    //        view.TextSnapshot.GetLineFromPosition(
                    //            view.TextSnapshot.GetText().IndexOf(fn)).Start));
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ERROR_MSG_PREFIX + ex.Message);
                }
            }
        }
 private void SourceTextChanged(object sender, TextContentChangedEventArgs e)
 {
     if (this.enabled && e.Changes.Count > 0)
     {
         ITextChange  firstChange = e.Changes[0];
         ITextChange  lastChange  = e.Changes[e.Changes.Count - 1];
         SnapshotSpan changedSpan = new SnapshotSpan(e.After, Span.FromBounds(firstChange.NewSpan.Start, lastChange.NewSpan.End));
         UpdateAfterChange(changedSpan);
     }
 }
Пример #18
0
 private void CompileIfWhitespace(ITextChange c)
 {
     if (c.Delta == 1)
     {
         // we do nothing if there's just one letter typed (no space or CR)
         byte[] bytes = System.Text.Encoding.ASCII.GetBytes(c.NewText);
         if (bytes != null && bytes[0] != 13 && bytes[0] != 32) return;
     }
     timer.stop(); // this will call Compile()
 }
Пример #19
0
        // Returns spans corresponding to the changes that occurred between startVersion and endVersion
        public static bool GetChangedExtent(this ITextVersion oldVersion, ITextVersion newVersion, out Span?oldSpan, out Span?newSpan)
        {
            oldSpan = null;
            newSpan = null;

            if (oldVersion.VersionNumber > newVersion.VersionNumber)
            {
                // They've asked for information about an earlier snapshot, not supported
                Debug.Assert(false);
                return(false);
            }

            int newEnd   = Int32.MinValue;
            int position = Int32.MaxValue;
            int deltaLen = 0;

            while (oldVersion != newVersion)
            {
                INormalizedTextChangeCollection changes = oldVersion.Changes;
                if (changes.Count > 0)
                {
                    ITextChange firstChange    = changes[0];
                    ITextChange lastChange     = changes[changes.Count - 1];
                    int         changeDeltaLen = lastChange.NewEnd - lastChange.OldEnd;

                    deltaLen += changeDeltaLen;

                    position = Math.Min(position, firstChange.NewPosition);

                    if (newEnd < lastChange.OldEnd)
                    {
                        newEnd = lastChange.NewEnd;
                    }
                    else
                    {
                        newEnd += changeDeltaLen;
                    }
                }

                oldVersion = oldVersion.Next;
            }

            if (newEnd < position)
            {
                // There weren't any changes between the versions, return a null TextChangeExtent
                return(false);
            }

            int oldEnd = newEnd - deltaLen;

            oldSpan = Span.FromBounds(position, oldEnd);
            newSpan = Span.FromBounds(position, newEnd);

            return(true);
        }
Пример #20
0
        private void SynchronizeStartAndEndTag(ITextChange textChange, List <TextManipulation> maniplations)
        {
            if (!textChange.NewText.All(n => char.IsLetterOrDigit(n) || XmlNameSpecialCharacters.Contains(n)))
            {
                return;
            }

            string startTag      = _state.ParseCurrentTagName();
            int?   maybeTagStart = _state.CurrentValueStart;

            if (maybeTagStart == null)
            {
                return;
            }

            int startPos = maybeTagStart.Value; // add 1 to take opening < into account

            if (startTag.EndsWith("/"))
            {
                return; // start tag is self-closing
            }
            if (textChange.NewPosition < startPos || textChange.NewPosition > startPos + startTag.Length)
            {
                return; //we are not editing tag name
            }

            XmlParser searchEndTag = _state.Clone();

            if (searchEndTag.SeekClosingTag())
            {
                string endTag = searchEndTag.ParseCurrentTagName();
                if (endTag[0] != '/')
                {
                    return;
                }

                maybeTagStart = searchEndTag.CurrentValueStart;
                if (maybeTagStart == null)
                {
                    return;
                }

                int endPos = maybeTagStart.Value; // add 1 to take opening < into account

                // reverse change to start tag
                startTag = textChange.ReverseOn(startTag, startPos);

                bool isTheSameTag = endTag.Length > 0 && endTag.Substring(1) == startTag;
                if (isTheSameTag)
                {
                    maniplations.AddRange(textChange.AsManipulations(endPos - startPos));
                }
            }
        }
Пример #21
0
 public int IndexOf(ITextChange item)
 {
     for (int i = 0; i < _changes.Length; i++)
     {
         if (_changes[i] == item)
         {
             return(i);
         }
     }
     return(-1);
 }
 private static TextChangeRange CreateTextChangeRange(ITextChange change, bool forward)
 {
     if (forward)
     {
         return(new TextChangeRange(new TextSpan(change.OldSpan.Start, change.OldSpan.Length), change.NewLength));
     }
     else
     {
         return(new TextChangeRange(new TextSpan(change.NewSpan.Start, change.NewSpan.Length), change.OldLength));
     }
 }
        public static IEnumerable <TextManipulation> AsManipulations(this ITextChange textChange, int offset = 0)
        {
            if (!string.IsNullOrEmpty(textChange.OldText))
            {
                yield return(TextManipulation.Delete(textChange.OldPosition + offset + 1, textChange.OldText.Length));
            }

            if (!string.IsNullOrEmpty(textChange.NewText))
            {
                yield return(TextManipulation.Insert(textChange.NewPosition + offset + 1, textChange.NewText));
            }
        }
Пример #24
0
 private static bool PriorTo(ITextChange denormalizedChange, ITextChange normalizedChange, int accumulatedDelta, int accumulatedNormalizedDelta)
 {
     // notice that denormalizedChange.OldPosition == denormalizedChange.NewPosition
     if ((denormalizedChange.OldLength != 0) && (normalizedChange.OldLength != 0))
     {
         // both deletions
         return(denormalizedChange.OldPosition <= normalizedChange.NewPosition - accumulatedDelta - accumulatedNormalizedDelta);
     }
     else
     {
         return(denormalizedChange.OldPosition < normalizedChange.NewPosition - accumulatedDelta - accumulatedNormalizedDelta);
     }
 }
Пример #25
0
 private void DumpChange(ITextChange c)
 {
     System.Text.StringBuilder s = new System.Text.StringBuilder();
     s.AppendLine(">>>>> HandleChange:");
     s.Append("Delta=").Append(c.Delta).Append("   LineCountDelta=").Append(c.LineCountDelta).AppendLine();
     s.Append("Position=").Append(c.OldPosition).Append('>').Append(c.NewPosition).AppendLine();
     s.Append("Length=").Append(c.OldLength).Append('>').Append(c.NewLength).AppendLine();
     s.Append("End=").Append(c.OldEnd).Append('>').Append(c.NewEnd).AppendLine();
     s.Append("Span=").Append(c.OldSpan).Append('>').Append(c.NewSpan).AppendLine();
     s.Append("Text=\"").Append(c.OldText).Append("\">\"").Append(c.NewText).AppendLine("\"");
     s.Append("<<<<<<<<<<");
     System.Console.WriteLine(s.ToString());
 }
Пример #26
0
 private void CompileIfWhitespace(ITextChange c)
 {
     if (c.Delta == 1)
     {
         // we do nothing if there's just one letter typed (no space or CR)
         byte[] bytes = System.Text.Encoding.ASCII.GetBytes(c.NewText);
         if (bytes != null && bytes[0] != 13 && bytes[0] != 32)
         {
             return;
         }
     }
     timer.stop(); // this will call Compile()
 }
 /// <summary>
 /// TextChange reversal is required to compare original text (before change)
 /// </summary>
 /// <param name="textChangeOffset">
 /// As text change is scoped in document this param allows to apply it to short strings, ie. tag names
 /// </param>
 public static string ReverseOn(this ITextChange textChange, string input, int textChangeOffset = 0)
 {
     if (!string.IsNullOrEmpty(textChange.NewText))
     {
         var start = textChange.NewPosition - textChangeOffset;
         input = input.Remove(start, Math.Min(input.Length - start, textChange.NewText.Length));
     }
     if (!string.IsNullOrEmpty(textChange.OldText))
     {
         input = input.Insert(textChange.OldPosition - textChangeOffset, textChange.OldText);
     }
     return(input);
 }
Пример #28
0
        private static bool ContainsTemplateMarkup(ITextChange change)
        {
            bool recalc = false;

            foreach (var tag in _templateTags)
            {
                if (change.NewText.Contains(tag))
                {
                    recalc = true;
                    break;
                }
            }
            return(recalc);
        }
Пример #29
0
 private void TextBuffer_Changed(object sender, TextContentChangedEventArgs e)
 {
     if (!isChangingText)
     {
         isChangingText = true;
         if (e.Changes != null)
         {
             for (int i = e.Changes.Count - 1; i >= 0; i--)
             {
                 change = e.Changes[i];
                 HandleChange();
             }
         }
     }
 }
Пример #30
0
 private void CheckChanges(ITextChange change)
 {
     Span[] expected = lexer.Run(new [] { CurrentSnapshot.GetText() }, 0).Select(x => x.Span).ToArray();
     Span[] actual = GetTokens(new Span(0, CurrentSnapshot.Length)).Select(x => x.GetSpan(CurrentSnapshot)).ToArray();
     var wrong = expected.Zip(actual, (_1, _2) => new { _1, _2 }).FirstOrDefault(x => x._1 != x._2);
     if(wrong != null)
     {
         Utils.DebugPrintToOutput(
             "Parser state mismatch.\nExpected span: {0} `{1}`\nActual span: {2} `{3}`",
             wrong._1,
             CurrentSnapshot.GetText(wrong._1),
             wrong._2,
             CurrentSnapshot.GetText(wrong._2));
     }
 }
Пример #31
0
        public static FileChange Convert(ITextChange change)
        {
            var newLength = change.NewLength;
            var oldLength = change.OldLength;

            if (oldLength == 0 && newLength > 0)
            {
                return(new FileChange.Insert(change.OldPosition, change.NewText));
            }
            if (oldLength > 0 && newLength == 0)
            {
                return(new FileChange.Delete(Convert(change.OldSpan)));
            }

            return(new FileChange.Replace(Convert(change.OldSpan), change.NewText));
        }
Пример #32
0
        private void CheckChanges(ITextChange change)
        {
            Span[] expected = lexer.Run(new [] { CurrentSnapshot.GetText() }, 0).Select(x => x.Span).ToArray();
            Span[] actual   = GetTokens(new Span(0, CurrentSnapshot.Length)).Select(x => x.GetSpan(CurrentSnapshot)).ToArray();
            var    wrong    = expected.Zip(actual, (_1, _2) => new { _1, _2 }).FirstOrDefault(x => x._1 != x._2);

            if (wrong != null)
            {
                Utils.DebugPrintToOutput(
                    "Parser state mismatch.\nExpected span: {0} `{1}`\nActual span: {2} `{3}`",
                    wrong._1,
                    CurrentSnapshot.GetText(wrong._1),
                    wrong._2,
                    CurrentSnapshot.GetText(wrong._2));
            }
        }
Пример #33
0
        internal static SnapshotSpan?GetPasteSpan(ITextSnapshot prePasteSnapshot, ITextSnapshot postPasteSnapshot)
        {
            INormalizedTextChangeCollection changes = prePasteSnapshot.Version.Changes;

            if (changes != null && changes.Count > 0)
            {
                ITextChange firstChange = changes[0];
                ITextChange lastChange  = changes[changes.Count - 1];

                SnapshotSpan newSpan = new SnapshotSpan(postPasteSnapshot, Span.FromBounds(firstChange.NewPosition, lastChange.NewEnd));

                return(newSpan);
            }

            return(null);
        }
Пример #34
0
        public StringRebuilder ApplyChangesToStringRebuilder(INormalizedTextChangeCollection normalizedChanges, StringRebuilder source)
        {
            var doppelganger = this.GetDoppelgangerBuilder();

            if (doppelganger != null)
            {
                return(doppelganger);
            }

            for (int i = normalizedChanges.Count - 1; (i >= 0); --i)
            {
                ITextChange change = normalizedChanges[i];
                source = source.Replace(change.OldSpan, TextChange.NewStringRebuilder(change));
            }

            return(source);
        }
Пример #35
0
 public void ApplyTextChange(ITextSnapshot before, ITextSnapshot after, ITextChange change)
 {
     List<TrackingToken> forRemoval = GetInvalidated(before, change);
     // Some of the tokens marked for removal must be deleted before applying a new version,
     // because otherwise some trackingtokens will have broken spans
     int i = 0;
     for (; i < forRemoval.Count; i++)
         tree.Remove(forRemoval[i]);
     CurrentSnapshot = after;
     IList<TrackingToken> updated = Rescan(forRemoval, before, change.Delta);
     for (; i < forRemoval.Count; i++)
         tree.Remove(forRemoval[i]);
     foreach (var token in updated)
         tree.Add(token);
     RaiseTokensChanged(updated);
     CheckChanges(change);
 }
        private static TextDocumentContentChangeEvent ConvertChange(
            ITextSnapshot before,
            ITextChange change)
        {
            var line      = before.GetLineFromPosition(change.OldPosition);
            var character = change.OldPosition - line.Start.Position;
            var length    = change.OldSpan.Length;

            return(new TextDocumentContentChangeEvent
            {
                Range = new Range
                {
                    Start = new Position(line.LineNumber, character),
                    End = new Position(line.LineNumber, character + length)
                },
                Text = change.NewText
            });
        }
Пример #37
0
        public static StringRebuilder ChangeNewSubText(ITextChange change, int start, int length)
        {
            var textChange = change as TextChange;

            if (textChange != null)
            {
                return(textChange._newText.GetSubText(new Span(start, length)));
            }

            var change3 = change as ITextChange3;

            if (change3 != null)
            {
                return(StringRebuilder.Create(change3.GetNewText(new Span(start, length))));
            }

            return(StringRebuilder.Create(change.NewText.Substring(start, length)));
        }
Пример #38
0
        public static string ChangeNewSubstring(ITextChange change, int start, int length)
        {
            var textChange = change as TextChange;

            if (textChange != null)
            {
                return(textChange._newText.GetText(new Span(start, length)));
            }

            var change3 = change as ITextChange3;

            if (change3 != null)
            {
                return(change3.GetNewText(new Span(start, length)));
            }

            return(change.NewText.Substring(start, length));
        }
 public void Setup()
 {
     _textChangeMock = Substitute.For<ITextChange>();
 }
 public void Insert(int index, ITextChange item) {
     throw new NotImplementedException();
 }
 public bool Remove(ITextChange item)
 {
     return false;
 }
 public void Add(ITextChange item) {
     throw new NotImplementedException();
 }
Пример #43
0
 private List<TrackingToken> GetInvalidated(ITextSnapshot oldSnapshot, ITextChange change)
 {
     return tree.GetInvalidatedBy(oldSnapshot, change.OldSpan);
 }
Пример #44
0
 private void HandleChange(ITextChange c)
 {
     /*
     ITextEdit edit = this.view.TextBuffer.CreateEdit();
     edit.Insert(c.NewEnd-1, "!");
     edit.Apply();
      */
 }
 public bool Contains(ITextChange item)
 {
     throw new NotImplementedException();
 }
 public void Add(ITextChange item)
 {
  }
 public void CopyTo(ITextChange[] array, int arrayIndex)
 {
     throw new NotImplementedException();
 }
Пример #48
0
        /// <summary>
        /// Builds the comment stub and inserts it into the editor.
        /// </summary>
        /// <param name="position">The position of the last slash.</param>
        private void CreateStub(int position, ITextChange change)
        {
            string text = this._view.TextSnapshot.ToString();
            using (ITextEdit editor = this._view.TextBuffer.CreateEdit())
            {
                try
                {
                    this.tabs = StubUtils.GetIndention(position, this._view.TextSnapshot);
                    string summaryTag = generateSummaryTag();
                    string parameters = getFunctionParameters(position);
                    string returnTag = getReturnTag(position);
                    string autoComment = summaryTag + parameters + returnTag;

                    int lineStart = this._view.TextSnapshot.GetLineFromPosition(position).Start.Position;
                    Span firstLineSpan = new Span(lineStart, change.NewSpan.End - lineStart);
                    editor.Replace(firstLineSpan, autoComment);
                    ITextSnapshotLine prevLine = this._view.TextSnapshot.GetLineFromPosition(position);

                    var after = editor.Apply();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(errorMsgPrefix + ex.Message);
                }
            }
        }
 private static TextChangeRange CreateTextChangeRange(ITextChange change, bool forward)
 {
     if (forward)
     {
         return new TextChangeRange(new TextSpan(change.OldSpan.Start, change.OldSpan.Length), change.NewLength);
     }
     else
     {
         return new TextChangeRange(new TextSpan(change.NewSpan.Start, change.NewSpan.Length), change.OldLength);
     }
 }
            private bool ShouldClearTrackingSession(ITextChange change)
            {
                AssertIsForeground();
                ISyntaxFactsService syntaxFactsService;
                if (!TryGetSyntaxFactsService(out syntaxFactsService))
                {
                    return true;
                }

                // The editor will replace virtual space with spaces and/or tabs when typing on a 
                // previously blank line. Trim these characters from the start of change.NewText. If 
                // the resulting change is empty (the user just typed a <space>), clear the session.
                var changedText = change.OldText + change.NewText.TrimStart(' ', '\t');
                if (changedText.IsEmpty())
                {
                    return true;
                }

                return changedText.Any(c => !IsTrackableCharacter(syntaxFactsService, c));
            }
 public void Insert(int index, ITextChange item)
 {
 }
Пример #52
0
 private void DumpChange(ITextChange c)
 {
     System.Text.StringBuilder s = new System.Text.StringBuilder();
     s.AppendLine(">>>>> HandleChange:");
     s.Append("Delta=").Append(c.Delta).Append("   LineCountDelta=").Append(c.LineCountDelta).AppendLine();
     s.Append("Position=").Append(c.OldPosition).Append('>').Append(c.NewPosition).AppendLine();
     s.Append("Length=").Append(c.OldLength).Append('>').Append(c.NewLength).AppendLine();
     s.Append("End=").Append(c.OldEnd).Append('>').Append(c.NewEnd).AppendLine();
     s.Append("Span=").Append(c.OldSpan).Append('>').Append(c.NewSpan).AppendLine();
     s.Append("Text=\"").Append(c.OldText).Append("\">\"").Append(c.NewText).AppendLine("\"");
     s.Append("<<<<<<<<<<");
     System.Console.WriteLine(s.ToString());
 }
 public bool Remove(ITextChange item) {
     throw new NotImplementedException();
 }
 public int IndexOf(ITextChange item)
 {
     return 0;
 }
Пример #55
0
        private static bool ShouldWrap(
            GeneralOptions options,
            ITextChange change,
            ITextSnapshotLine line,
            LineCommentInfo info,
            out int commentWrapLength)
        {
            commentWrapLength = -1;

            if (info == null || (!info.CommentOnly && !options.CodeWrapEnabled))
            {
                return false;
            }

            // For now, we're only supporting single-line comments.
            if (info.Style != CommentStyle.SingleLine)
            {
                return false;
            }

            // If we just typed whitespace at the *end* of the line, don't do
            // any wrapping yet.  (It will cause us to trim the trailing space,
            // which would makeeverythingruntogetherlikethis!  It also makes
            // newline handling weird.)
            if ((change.Delta > 0) &&
                ((change.NewSpan.End >= line.End) && (change.NewSpan.End <= line.EndIncludingLineBreak)) &&
                change.NewText.All(c => Whitespace.Contains(c)))
            {
                return false;
            }

            commentWrapLength = options.AutoWrapColumn - info.ContentColumnStart;

            // There's some minimum length after which wrapping becomes
            // pointless...
            if (commentWrapLength < options.MinimumWrapWidth)
            {
                return false;
            }

            return true;
        }