private void adjustWhiteSpace()
 {
     ThreadHelper.JoinableTaskFactory.Run(async delegate
     {
         await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
         var editSession = _buffer.CreateEdit();
         var changed     = false;
         try
         {
             var snapshot = editSession.Snapshot;
             if (_settings.InsertFinalNewline)
             {
                 var text = snapshot.GetText();
                 if (!text.EndsWith(Environment.NewLine))
                 {
                     var line = snapshot.GetLineFromLineNumber(snapshot.LineCount - 1);
                     editSession.Insert(line.End.Position, Environment.NewLine);
                     changed = true;
                 }
             }
             if (_settings.TrimTrailingWhiteSpace)
             {
                 foreach (var line in snapshot.Lines)
                 {
                     var text = line.GetText();
                     if (text.Length > 0)
                     {
                         var last = text[text.Length - 1];
                         if (last == ' ' || last == '\t')
                         {
                             text = text.TrimEnd();
                             editSession.Replace(line.Start.Position, line.Length, text);
                             changed = true;
                         }
                     }
                 }
             }
         }
         catch (Exception)
         {
             editSession.Cancel();
         }
         finally
         {
             if (changed)
             {
                 editSession.Apply();
             }
             else
             {
                 editSession.Cancel();
             }
         }
     });
 }
        public static void MakeEmptyEdit(this ITextBuffer textBuffer)
        {
            var bufferLength = textBuffer.CurrentSnapshot.Length;

            using var edit = textBuffer.CreateEdit(EditOptions.None, reiteratedVersionNumber: null, InviolableEditTag.Instance);
            edit.Insert(bufferLength, " ");
            edit.Apply();

            using var revertEdit = textBuffer.CreateEdit(EditOptions.None, reiteratedVersionNumber: null, InviolableEditTag.Instance);
            revertEdit.Delete(bufferLength, 1);
            revertEdit.Apply();
        }
Example #3
0
 public void Do()
 {
     if (!CanRedo)
     {
         throw new InvalidOperationException();
     }
     using (var ed = textBuffer.CreateEdit(EditOptions.None, info.AfterVersionNumber, editTag)) {
         foreach (var change in info.Collection)
         {
             ed.Replace(change.OldSpan, change.NewText);
         }
         ed.Apply();
     }
     canUndo = true;
 }
        /// Takes current text buffer and new text then builds list of changed
        /// regions and applies them to the buffer. This way we can avoid 
        /// destruction of bookmarks and other markers. Complete
        /// buffer replacement deletes all markers which causes 
        /// loss of bookmarks, breakpoints and other similar markers.
        public static void ApplyChange(
            ITextBuffer textBuffer,
            int position,
            int length,
            string newText,
            string transactionName,
            ISelectionTracker selectionTracker,
            int maxMilliseconds) {

            var snapshot = textBuffer.CurrentSnapshot;
            int oldLength = Math.Min(length, snapshot.Length - position);
            string oldText = snapshot.GetText(position, oldLength);

            var changes = TextChanges.BuildChangeList(oldText, newText, maxMilliseconds);
            if (changes != null && changes.Count > 0) {
                using (var selectionUndo = new SelectionUndo(selectionTracker, transactionName, automaticTracking: false)) {
                    using (ITextEdit edit = textBuffer.CreateEdit()) {
                        // Replace ranges in reverse so relative positions match
                        for (int i = changes.Count - 1; i >= 0; i--) {
                            TextChange tc = changes[i];
                            edit.Replace(tc.Position + position, tc.Length, tc.NewText);
                        }

                        edit.Apply();
                    }
                }
            }
        }
Example #5
0
        public bool ReplaceAll(ITextBuffer tb)
        {
            Contract.Assume(tb != null);

            var tra           = new TacticReplacerActor(tb);
            var isMoreMembers = tra.NextMemberInTld();
            var replaceStatus = TacticReplaceStatus.Success;
            var tedit         = tb.CreateEdit();

            try
            {
                while (isMoreMembers && (replaceStatus == TacticReplaceStatus.Success || replaceStatus == TacticReplaceStatus.NoTactic))
                {
                    var isMoreTactics = tra.NextTacticCallInMember();
                    while (isMoreTactics && (replaceStatus == TacticReplaceStatus.Success || replaceStatus == TacticReplaceStatus.NoTactic))
                    {
                        replaceStatus = tra.ReplaceSingleTacticCall(tedit);
                        isMoreTactics = tra.NextTacticCallInMember();
                    }
                    isMoreMembers = tra.NextMemberInTld();
                }

                if (replaceStatus == TacticReplaceStatus.Success || replaceStatus == TacticReplaceStatus.NoTactic)
                {
                    tedit.Apply();
                }
                else
                {
                    tedit.Dispose();
                }
            } catch { tedit.Dispose(); }
            return(NotifyOfReplacement(replaceStatus));
        }
        private void UpdateFromImport(PythonAst curAst, FromImportStatement fromImport)
        {
            NameExpression[] names   = new NameExpression[fromImport.Names.Count + 1];
            NameExpression[] asNames = fromImport.AsNames == null ? null : new NameExpression[fromImport.AsNames.Count + 1];
            NameExpression   newName = new NameExpression(Name);

            for (int i = 0; i < fromImport.Names.Count; i++)
            {
                names[i] = fromImport.Names[i];
            }
            names[fromImport.Names.Count] = newName;

            if (asNames != null)
            {
                for (int i = 0; i < fromImport.AsNames.Count; i++)
                {
                    asNames[i] = fromImport.AsNames[i];
                }
            }

            var newImport = new FromImportStatement((ModuleName)fromImport.Root, names, asNames, fromImport.IsFromFuture, fromImport.ForceAbsolute);

            curAst.CopyAttributes(fromImport, newImport);

            var newCode = newImport.ToCodeString(curAst);

            var span = fromImport.GetSpan(curAst);
            int leadingWhiteSpaceLength = (fromImport.GetLeadingWhiteSpace(curAst) ?? "").Length;

            using (var edit = _buffer.CreateEdit()) {
                edit.Delete(span.Start.Index - leadingWhiteSpaceLength, span.Length + leadingWhiteSpaceLength);
                edit.Insert(span.Start.Index, newCode);
                edit.Apply();
            }
        }
Example #7
0
        protected void ApplyReplacementText(ITextBuffer subjectBuffer, ITextUndoHistory undoHistory, object propagateSpansEditTag, IEnumerable <ITrackingSpan> spans, string replacementText)
        {
            // roll back to the initial state for the buffer after conflict resolution
            this.UndoTemporaryEdits(subjectBuffer, disconnect: false, undoConflictResolution: replacementText == string.Empty);

            using var transaction = undoHistory.CreateTransaction(GetUndoTransactionDescription(replacementText));
            using var edit        = subjectBuffer.CreateEdit(EditOptions.None, null, propagateSpansEditTag);

            foreach (var span in spans)
            {
                if (span.GetText(subjectBuffer.CurrentSnapshot) != replacementText)
                {
                    edit.Replace(span.GetSpan(subjectBuffer.CurrentSnapshot), replacementText);
                }
            }

            edit.ApplyAndLogExceptions();
            if (!edit.HasEffectiveChanges && !this.UndoStack.Any())
            {
                transaction.Cancel();
            }
            else
            {
                transaction.Complete();
            }
        }
Example #8
0
        /// <summary>
        /// Normalizes the given buffer to match the given newline string on every line
        /// </summary>
        /// <returns>True if the buffer was changed. False otherwise.</returns>
        public static bool NormalizeNewlines(this ITextBuffer buffer, string newlineString)
        {
            using (var edit = buffer.CreateEdit())
            {
                foreach (var line in edit.Snapshot.Lines)
                {
                    if (line.LineBreakLength != 0)
                    {
                        // Calling line.GetLineBreakText allocates a string. Since we only have 1 2-character newline to worry about
                        // we can do this without that allocation by comparing characters directly.
                        if (line.LineBreakLength != newlineString.Length || edit.Snapshot[line.End] != newlineString[0])
                        {
                            // Intentionally ignore failed replaces. We'll do the best effort change here.
                            edit.Replace(new Span(line.End, line.LineBreakLength), newlineString);
                        }
                    }
                }

                if (edit.HasEffectiveChanges)
                {
                    return(edit.Apply() != edit.Snapshot);
                }
                else
                {
                    // We didn't have to do anything
                    return(false);
                }
            }
        }
Example #9
0
        private ITextEdit FixByMoving(RobotsTxtLineSyntax line, RobotsTxtRecordSyntax record)
        {
            ITextBuffer buffer = line.Record.Document.Snapshot.TextBuffer;

            // default insertion point at record start
            SnapshotPoint insertionPoint = record.Span.Start;

            // find last User-agent line
            var last = record.Lines
                       .TakeWhile(l => l.NameToken.Value.Equals("User-agent", StringComparison.InvariantCultureIgnoreCase))
                       .LastOrDefault();

            if (last != null) // override insertion point
            {
                insertionPoint = last.Span.End.GetContainingLine().EndIncludingLineBreak;
            }

            // move line up
            ITextEdit edit = buffer.CreateEdit();

            edit.Insert(
                insertionPoint,
                line.Span.Start.GetContainingLine().GetTextIncludingLineBreak()
                );
            edit.Delete(line.Span.Start.GetContainingLine().ExtentIncludingLineBreak);

            return(edit);
        }
Example #10
0
        public bool Replace()
        {
            if (SearchTerm == null)
            {
                throw new InvalidOperationException();
            }
            if (SearchTerm.Length == 0)
            {
                throw new InvalidOperationException();
            }
            if (CurrentResult == null)
            {
                throw new InvalidOperationException();
            }
            if (ReplaceTerm == null)
            {
                throw new InvalidOperationException();
            }

            var          spanToUse = searchSpan?.GetSpan(CurrentResult.Value.Snapshot) ?? new SnapshotSpan(CurrentResult.Value.Snapshot, 0, CurrentResult.Value.Snapshot.Length);
            SnapshotSpan searchRange;

            if ((SearchOptions & FindOptions.SearchReverse) != 0)
            {
                Debug.Assert(spanToUse.Start <= CurrentResult.Value.End);
                if (spanToUse.Start > CurrentResult.Value.End)
                {
                    return(false);
                }
                searchRange = new SnapshotSpan(spanToUse.Start, CurrentResult.Value.End);
            }
            else
            {
                Debug.Assert(CurrentResult.Value.Start <= spanToUse.End);
                if (CurrentResult.Value.Start > spanToUse.End)
                {
                    return(false);
                }
                searchRange = new SnapshotSpan(CurrentResult.Value.Start, spanToUse.End);
            }

            string expandedReplacePattern;
            var    span = textSearchService2.FindForReplace(searchRange, SearchTerm, ReplaceTerm, SearchOptions, out expandedReplacePattern);

            if (span == null)
            {
                return(false);
            }
            using (var ed = buffer.CreateEdit()) {
                var currSpan = span.Value.TranslateTo(buffer.CurrentSnapshot, SpanTrackingMode.EdgeInclusive);
                if (!ed.Replace(currSpan.Span, expandedReplacePattern))
                {
                    return(false);
                }
                ed.Apply();
                // Don't check the snapshot returned by Apply() since we could've replaced a 0-length span with the
                // empty string if regex search was used. In that case, no new snapshot is created.
                return(!ed.Canceled);
            }
        }
Example #11
0
        private static void UpdateText(
            ImmutableArray <TextChange> textChanges,
            ITextBuffer buffer,
            ITextSnapshot oldSnapshot,
            SourceText oldText,
            EditOptions options
            )
        {
            using var edit = buffer.CreateEdit(
                      options,
                      reiteratedVersionNumber: null,
                      editTag: null
                      );
            if (CodeAnalysis.Workspace.TryGetWorkspace(oldText.Container, out var workspace))
            {
                var undoService = workspace.Services.GetRequiredService <ISourceTextUndoService>();
                undoService.BeginUndoTransaction(oldSnapshot);
            }

            foreach (var change in textChanges)
            {
                edit.Replace(change.Span.Start, change.Span.Length, change.NewText);
            }

            edit.ApplyAndLogExceptions();
        }
        static void Insert(IAsyncCompletionSession session, ITextBuffer buffer, string text, SnapshotSpan span)
        {
            var bufferEdit = buffer.CreateEdit();

            bufferEdit.Replace(span, text);
            bufferEdit.Apply();
        }
Example #13
0
        private static void MinimizeBuffers(ITextBuffer leftBuffer, ITextBuffer rightBuffer, ITextSnapshot startingVersion, int minPos, int maxPos)
        {
            // Remove the unchanged content from both buffers
            using (var edit = leftBuffer.CreateEdit()) {
                edit.Delete(0, minPos);
                edit.Delete(Span.FromBounds(maxPos, startingVersion.Length));
                edit.Apply();
            }

            using (var edit = rightBuffer.CreateEdit()) {
                edit.Delete(
                    0,
                    Tracking.TrackPositionForwardInTime(
                        PointTrackingMode.Negative,
                        minPos,
                        startingVersion.Version,
                        rightBuffer.CurrentSnapshot.Version
                        )
                    );

                edit.Delete(
                    Span.FromBounds(
                        Tracking.TrackPositionForwardInTime(
                            PointTrackingMode.Positive,
                            maxPos,
                            startingVersion.Version,
                            rightBuffer.CurrentSnapshot.Version
                            ),
                        rightBuffer.CurrentSnapshot.Length
                        )
                    );
                edit.Apply();
            }
        }
Example #14
0
        public static void SetTextContent(this ITextBuffer textBuffer, string textContent)
        {
            var edit = textBuffer.CreateEdit(EditOptions.DefaultMinimalChange, 0, null);

            edit.Replace(new Span(0, textBuffer.CurrentSnapshot.Length), textContent);
            edit.Apply();
        }
Example #15
0
            public void OnCharTyped(char @char)
            {
                // format on ':'
                if (@char == RobotsTxtSyntaxFacts.NameValueDelimiter)
                {
                    ITextBuffer buffer = _textView.TextBuffer;

                    SyntaxTree syntaxTree        = buffer.GetSyntaxTree();
                    RobotsTxtDocumentSyntax root = syntaxTree.Root as RobotsTxtDocumentSyntax;

                    // find in syntax tree
                    var caret = _textView.Caret.Position.BufferPosition;
                    RobotsTxtLineSyntax lineSyntax = root.Records
                                                     .SelectMany(r => r.Lines)
                                                     .FirstOrDefault(p => p.DelimiterToken.Span.Span.End == caret);

                    if (lineSyntax != null)
                    {
                        using (ITextUndoTransaction transaction = _undoHistory.CreateTransaction("Automatic Formatting"))
                        {
                            using (ITextEdit edit = buffer.CreateEdit())
                            {
                                // fix indent
                                // find property before
                                RobotsTxtLineSyntax before = lineSyntax.Record.Lines
                                                             .TakeWhile(p => p != lineSyntax)
                                                             .LastOrDefault();

                                // reference point
                                if (before != null)
                                {
                                    SnapshotPoint referencePoint = before.NameToken.Span.Span.Start;

                                    // compare
                                    ITextSnapshotLine referenceLine = referencePoint.GetContainingLine();
                                    ITextSnapshotLine line          = lineSyntax.DelimiterToken.Span.Span.End.GetContainingLine();

                                    SnapshotSpan referenceIndent = new SnapshotSpan(referenceLine.Start, referencePoint);
                                    SnapshotSpan indent          = new SnapshotSpan(line.Start, lineSyntax.NameToken.Span.Span.Start);

                                    if (indent.GetText() != referenceIndent.GetText())
                                    {
                                        edit.Replace(indent, referenceIndent.GetText());
                                    }
                                }

                                // remove white space before ':'
                                if (lineSyntax.NameToken.Span.Span.End != lineSyntax.DelimiterToken.Span.Span.Start)
                                {
                                    edit.Delete(new SnapshotSpan(lineSyntax.NameToken.Span.Span.End, lineSyntax.DelimiterToken.Span.Span.Start));
                                }

                                edit.Apply();
                            }

                            transaction.Complete();
                        }
                    }
                }
            }
        private ITextEdit Fix(RobotsTxtLineSyntax line)
        {
            ITextBuffer buffer = line.Record.Document.Snapshot.TextBuffer;

            string value = line.ValueToken.Value;

            // fix
            string newValue = value;

            // example: * -> /
            if (value == "*")
            {
                newValue = "/";
            }

            // example: /folder/* -> /folder/
            else if (value.EndsWith("/*"))
            {
                newValue = value.Remove(value.Length - 1);
            }

            ITextEdit edit = buffer.CreateEdit();

            edit.Replace(
                line.ValueToken.Span.Span,
                newValue
                );

            return(edit);
        }
Example #17
0
        /// <summary>
        /// Normalizes the given buffer to match the given whitespace stype.
        /// </summary>
        /// <returns>True if the buffer was changed. False otherwise.</returns>
        public static bool NormalizeLeadingWhitespace(this ITextBuffer buffer, int tabSize, bool useSpaces)
        {
            using (var edit = buffer.CreateEdit())
            {
                var whitespaceCache = new string[100];

                foreach (var line in edit.Snapshot.Lines)
                {
                    if (line.Length > 0)
                    {
                        AnalyzeWhitespace(line, tabSize, out int whitespaceCharacterLength, out int column);
                        if (column > 0)
                        {
                            var whitespace = GetWhitespace(whitespaceCache, tabSize, useSpaces, column);

                            if ((whitespace.Length != whitespaceCharacterLength) || !ComparePrefix(line, whitespace))
                            {
                                edit.Replace(new Span(line.Start, whitespaceCharacterLength), whitespace);
                            }
                        }
                    }
                }

                return(edit.Apply() != edit.Snapshot);
            }
        }
Example #18
0
        private void FormatSelection(ITextBuffer textBuffer, int insertionIndex, string insertionText)
        {
            Controller.TextViewData viewData = Controller.TextViewConnectionListener.GetTextViewDataForBuffer(textBuffer);
            ITextView textView = viewData.LastActiveView;

            using (ITextEdit textEdit = textBuffer.CreateEdit())
            {
                textEdit.Insert(insertionIndex, insertionText);
                textEdit.Apply();
            }

            IOleCommandTarget commandTarget = Shell.Package.GetGlobalService(typeof(Shell.Interop.SUIHostCommandDispatcher)) as IOleCommandTarget;

            SendFocusToEditor(textView);

            SnapshotSpan snapshotSpan = new SnapshotSpan(textView.TextSnapshot, insertionIndex, insertionText.Length + 1);

            textView.Selection.Select(snapshotSpan, false);

            Guid guidVSStd2K = VSConstants.VSStd2K;

            commandTarget.Exec(
                ref guidVSStd2K,
                (uint)VSConstants.VSStd2KCmdID.FORMATSELECTION,
                (uint)OLECMDEXECOPT.OLECMDEXECOPT_DODEFAULT,
                IntPtr.Zero,
                IntPtr.Zero);

            textView.Selection.Clear();
        }
Example #19
0
        private void StripWhiteSpace(ITextSnapshotLine line)
        {
            ITextSnapshot snapshot   = line.Snapshot;
            ITextBuffer   textBuffer = snapshot.TextBuffer;
            int           position   = line.Start.Position;

            while (position < line.End.Position && IsSpaceCharacter(snapshot[position]))
            {
                ++position;
            }
            int index = line.End.Position - 1;

            while (index > position && IsSpaceCharacter(snapshot[index]))
            {
                --index;
            }
            if (index == line.End.Position - 1 && position == line.Start.Position)
            {
                return;
            }
            using (ITextEdit edit = textBuffer.CreateEdit())
            {
                edit.Delete(Span.FromBounds(index + 1, line.End.Position));
                edit.Delete(Span.FromBounds(line.Start.Position, position));
                edit.Apply();
            }
        }
        /// <summary>
        /// Command handler for the history commands.
        /// The standard implementation of a console has a history function implemented when
        /// the user presses the UP or DOWN key.
        /// </summary>
        private void OnHistory(object sender, EventArgs e)
        {
            if (!completionBroker.IsCompletionActive(_textView))
            {
                // Get the command to figure out from the ID if we have to get the previous or the
                // next element in the history.
                OleMenuCommand command = sender as OleMenuCommand;
                if (null == command ||
                    command.CommandID.Guid != typeof(Microsoft.VisualStudio.VSConstants.VSStd2KCmdID).GUID)
                {
                    return;
                }
                string historyEntry = null;
                if (command.CommandID.ID == (int)Microsoft.VisualStudio.VSConstants.VSStd2KCmdID.UP)
                {
                    historyEntry = history.PreviousEntry();
                }
                else if (command.CommandID.ID == (int)Microsoft.VisualStudio.VSConstants.VSStd2KCmdID.DOWN)
                {
                    historyEntry = history.NextEntry();
                }
                if (string.IsNullOrEmpty(historyEntry))
                {
                    return;
                }

                int start = GetReadOnlyLength(mefTextBuffer.CurrentSnapshot);
                if (!mefTextBuffer.EditInProgress)
                {
                    var edit = mefTextBuffer.CreateEdit();
                    edit.Replace(new Span(start, mefTextBuffer.CurrentSnapshot.Length - start), historyEntry);
                    edit.Apply();
                }
            }
        }
        private void UpdateVendorValues(ParseItem item)
        {
            Declaration dec = item.FindType <Declaration>();

            if (dec != null && Cache.Contains(dec) && !dec.IsVendorSpecific())
            {
                // Find all vendor specifics that isn't the standard property.
                var matches = Cache.Where(d => d.IsValid && d != dec && d.Parent == dec.Parent && GetStandardName(d) == dec.PropertyName.Text && d.PropertyName.Text != dec.PropertyName.Text);

                // Undo sometimes messes with the positions, so we have to make this check before proceeding.
                if (!matches.Any() || dec.Text.Length < dec.Colon.AfterEnd - dec.Start || dec.Colon.AfterEnd < dec.Start)
                {
                    return;
                }

                string text = dec.Text.Substring(dec.Colon.AfterEnd - dec.Start, dec.AfterEnd - dec.Colon.AfterEnd);
                using (ITextEdit edit = _buffer.CreateEdit())
                {
                    foreach (Declaration match in matches.Reverse())
                    {
                        SnapshotSpan span = new SnapshotSpan(_buffer.CurrentSnapshot, match.Colon.AfterEnd, match.AfterEnd - match.Colon.AfterEnd);
                        if (span.GetText() != text)
                        {
                            edit.Replace(span, text);
                        }
                    }

                    edit.Apply();
                }
            }
        }
Example #22
0
        public void Edit(Project project)
        {
            string str = Path.Combine(ProjectExtensions.GetFullPath(project), "web.config");

            if (project.DTE.SourceControl.IsItemUnderSCC(str) && !project.DTE.SourceControl.IsItemCheckedOut(str) && !project.DTE.SourceControl.CheckOutItem(str))
            {
                return;
            }
            IEditorInterfaces orOpenDocument = this.VisualStudio.Editor.GetOrOpenDocument(str);

            Marshal.ThrowExceptionForHR(orOpenDocument.VsTextBuffer.Reload(1));
            ITextBuffer textBuffer = orOpenDocument.TextBuffer;

            using (ITextEdit textEdit = textBuffer.CreateEdit())
            {
                string editedText = this.GetEditedText(textEdit.Snapshot.GetText());
                if (editedText != null)
                {
                    textEdit.Replace(new Span(0, textBuffer.CurrentSnapshot.Length), editedText);
                    textEdit.Apply();
                    this.VisualStudio.Editor.FormatDocument(str);
                    Document document = project.DTE.Documents.Item(str);
                    document.Save("");
                }
            }
        }
Example #23
0
        /// <summary>
        /// Removes white space from both ends of a line.
        /// </summary>
        private void StripWhiteSpace(ITextSnapshotLine line)
        {
            ITextSnapshot snapshot = line.Snapshot;
            ITextBuffer   buffer   = snapshot.TextBuffer;

            int forwardIterator;
            int backwardIterator;

            // Detect spaces at the beginning
            forwardIterator = line.Start.Position;
            while (forwardIterator < line.End.Position && IsSpaceCharacter(snapshot[forwardIterator]))
            {
                ++forwardIterator;
            }

            // Detect spaces at the end
            backwardIterator = line.End.Position - 1;
            while (backwardIterator > forwardIterator && IsSpaceCharacter(snapshot[backwardIterator]))
            {
                --backwardIterator;
            }

            if ((backwardIterator != line.End.Position - 1) || (forwardIterator != line.Start.Position))
            {
                using (ITextEdit edit = buffer.CreateEdit())
                {
                    edit.Delete(Span.FromBounds(backwardIterator + 1, line.End.Position));
                    edit.Delete(Span.FromBounds(line.Start.Position, forwardIterator));

                    edit.Apply();
                }
            }
        }
        public sealed override void Apply(IEditorOptions options, ITextBuffer document, CancellationToken cancellationToken, ITextView textView = null)
        {
            FixNewlines(edits, options, document.CurrentSnapshot);

            var selections = textView != null?GetSelectionTrackingSpans(edits, document.CurrentSnapshot) : null;

            using var edit = document.CreateEdit();
            foreach (var change in edits)
            {
                switch (change.Kind)
                {
                case Kind.Insert:
                    edit.Insert(change.Span.Start, change.Text);
                    break;

                case Kind.Replace:
                    edit.Replace(change.Span.Start, change.Span.Length, change.Text);
                    break;

                case Kind.Delete:
                    edit.Delete(change.Span.Start, change.Span.Length);
                    break;
                }
            }
            edit.Apply();

            if (selections != null && selections.Count > 0)
            {
                ApplySelections(selections, textView);
            }
        }
        /// Takes current text buffer and new text then builds list of changed
        /// regions and applies them to the buffer. This way we can avoid
        /// destruction of bookmarks and other markers. Complete
        /// buffer replacement deletes all markers which causes
        /// loss of bookmarks, breakpoints and other similar markers.
        public static void ApplyChange(
            ITextBuffer textBuffer,
            int position,
            int length,
            string newText,
            string transactionName,
            ISelectionTracker selectionTracker,
            int maxMilliseconds)
        {
            var    snapshot  = textBuffer.CurrentSnapshot;
            int    oldLength = Math.Min(length, snapshot.Length - position);
            string oldText   = snapshot.GetText(position, oldLength);

            var changes = TextChanges.BuildChangeList(oldText, newText, maxMilliseconds);

            if (changes != null && changes.Count > 0)
            {
                using (var selectionUndo = new SelectionUndo(selectionTracker, transactionName, automaticTracking: false)) {
                    using (ITextEdit edit = textBuffer.CreateEdit()) {
                        // Replace ranges in reverse so relative positions match
                        for (int i = changes.Count - 1; i >= 0; i--)
                        {
                            TextChange tc = changes[i];
                            edit.Replace(tc.Position + position, tc.Length, tc.NewText);
                        }

                        edit.Apply();
                    }
                }
            }
        }
Example #26
0
        private void RemoveTrailingWhitespace(ITextBuffer buffer)
        {
            bool foundWhitespace = false;

            using (ITextEdit edit = buffer.CreateEdit())
            {
                ITextSnapshot snap = edit.Snapshot;

                foreach (ITextSnapshotLine line in snap.Lines)
                {
                    string text   = line.GetText();
                    int    length = text.Length;
                    while (--length >= 0 && Char.IsWhiteSpace(text[length]))
                    {
                        ;
                    }
                    if (length < text.Length - 1)
                    {
                        int start = line.Start.Position;
                        edit.Delete(start + length + 1, text.Length - length - 1);
                        foundWhitespace = true;
                    }
                }

                edit.Apply();
            }

            if (foundWhitespace)
            {
                Telemetry.TrackEvent("On save");
            }
        }
Example #27
0
        private void DeleteWhiteSpace(ITextBuffer textBuffer)
        {
            ITextEdit EditBuffer = textBuffer.CreateEdit();

            foreach (ITextSnapshotLine Line in EditBuffer.Snapshot.Lines)
            {
                string sLine = Line.GetText();
                int    i     = Line.Length;
                //If this line is empty then move on
                if (i == 0)
                {
                    continue;
                }
                //Start at the end of the line and find the starting index of the whitespace
                while (--i >= 0 && Char.IsWhiteSpace(sLine[i]))
                {
                }
                ;
                ++i;
                //If we found whitespace then remove it, this if check is unnecessary, but avoids us having to call Delete below unnecessarily
                if (i != Line.Length)
                {
                    EditBuffer.Delete(Line.Start.Position + i, Line.Length - i);
                }
            }
            EditBuffer.Apply();
        }
Example #28
0
 private static void UpdateText(ITextBuffer textBuffer, string text)
 {
     using (var edit = textBuffer.CreateEdit())
     {
         edit.Replace(0, textBuffer.CurrentSnapshot.Length, text);
         edit.Apply();
     }
 }
Example #29
0
 private static void UpdateText(ITextBuffer textBuffer, string text)
 {
     using (var edit = textBuffer.CreateEdit())
     {
         edit.Replace(0, textBuffer.CurrentSnapshot.Length, text);
         edit.Apply();
     }
 }
Example #30
0
        public static void SetText(this ITextBuffer buffer, params string[] lines)
        {
            var text = String.Join(Environment.NewLine, lines);
            var edit = buffer.CreateEdit(EditOptions.DefaultMinimalChange, 0, null);

            edit.Replace(new Span(0, buffer.CurrentSnapshot.Length), text);
            edit.Apply();
        }
 private static void ApplyEdits(ITextBuffer textBuffer, IList<Edit> edits)
 {
     using (var vsEdit = textBuffer.CreateEdit())
     {
         foreach (var edit in edits)
             vsEdit.Replace(edit.Start, edit.Length, edit.Text);
         vsEdit.Apply();
     }
 }
Example #32
0
        static void SetText(ITextBuffer textBuffer, string content)
        {
            content = content ?? "";

            using (var edit = textBuffer.CreateEdit(EditOptions.DefaultMinimalChange, reiteratedVersionNumber: null, editTag: 1)) {
                edit.Replace(0, textBuffer.CurrentSnapshot.Length, content);
                edit.Apply();
            }
        }
Example #33
0
        private static void NotifyBufferVersionUpdated(ITextBuffer textBuffer, long hostDocumentSyncVersion)
        {
            textBuffer.SetHostDocumentSyncVersion(hostDocumentSyncVersion);
            var edit = textBuffer.CreateEdit();

            // Content doesn't matter, we're just trying to create an edit that notifies listeners of a changed event.
            edit.Insert(0, "Test");
            edit.Apply();
        }
Example #34
0
        private static void ApplyChanges(ITextBuffer buffer, IList<TextChange> changes)
        {
            using (var edit = buffer.CreateEdit())
            {
                foreach (var change in changes)
                {
                    edit.Replace(change.Span.ToSpan(), change.NewText);
                }

                edit.Apply();
            }
        }
        /// <summary>
        /// Incrementally applies whitespace change to the buffer 
        /// having old and new tokens produced from the 'before formatting' 
        /// and 'after formatting' versions of the same text.
        /// </summary>
        /// <param name="textBuffer">Text buffer to apply changes to</param>
        /// <param name="newTextProvider">Text provider of the text fragment before formatting</param>
        /// <param name="newTextProvider">Text provider of the formatted text</param>
        /// <param name="oldTokens">Tokens from the 'before' text fragment</param>
        /// <param name="newTokens">Tokens from the 'after' text fragment</param>
        /// <param name="formatRange">Range that is being formatted in the text buffer</param>
        /// <param name="transactionName">Name of the undo transaction to open</param>
        /// <param name="selectionTracker">Selection tracker object that will save, track
        /// <param name="additionalAction">Action to perform after changes are applies by undo unit is not yet closed.</param>
        /// and restore selection after changes have been applied.</param>
        public static void ApplyChangeByTokens(
            ITextBuffer textBuffer,
            ITextProvider oldTextProvider,
            ITextProvider newTextProvider,
            IReadOnlyList<ITextRange> oldTokens,
            IReadOnlyList<ITextRange> newTokens,
            ITextRange formatRange,
            string transactionName,
            ISelectionTracker selectionTracker,
            IEditorShell editorShell,
            Action additionalAction = null) {

            Debug.Assert(oldTokens.Count == newTokens.Count);
            if (oldTokens.Count == newTokens.Count) {
                ITextSnapshot snapshot = textBuffer.CurrentSnapshot;
                using (CreateSelectionUndo(selectionTracker, editorShell, transactionName)) {
                    using (ITextEdit edit = textBuffer.CreateEdit()) {
                        if (oldTokens.Count > 0) {
                            // Replace whitespace between tokens in reverse so relative positions match
                            int oldEnd = oldTextProvider.Length;
                            int newEnd = newTextProvider.Length;
                            string oldText, newText;
                            for (int i = newTokens.Count - 1; i >= 0; i--) {
                                oldText = oldTextProvider.GetText(TextRange.FromBounds(oldTokens[i].End, oldEnd));
                                newText = newTextProvider.GetText(TextRange.FromBounds(newTokens[i].End, newEnd));
                                if (oldText != newText) {
                                    edit.Replace(formatRange.Start + oldTokens[i].End, oldEnd - oldTokens[i].End, newText);
                                }
                                oldEnd = oldTokens[i].Start;
                                newEnd = newTokens[i].Start;
                            }
                            newText = newTextProvider.GetText(TextRange.FromBounds(0, newEnd));
                            edit.Replace(formatRange.Start, oldEnd, newText);
                        } else {
                            string newText = newTextProvider.GetText(TextRange.FromBounds(0, newTextProvider.Length));
                            edit.Replace(formatRange.Start, formatRange.Length, newText);
                        }
                        edit.Apply();
                        additionalAction?.Invoke();
                    }
                }
            }
        }
        private void RemoveTrailingWhitespace(ITextBuffer buffer)
        {
            using (ITextEdit edit = buffer.CreateEdit())
            {
                ITextSnapshot snap = edit.Snapshot;

                foreach (ITextSnapshotLine line in snap.Lines)
                {
                    string text = line.GetText();
                    int length = text.Length;
                    while (--length >= 0 && Char.IsWhiteSpace(text[length])) ;
                    if (length < text.Length - 1)
                    {
                        int start = line.Start.Position;
                        edit.Delete(start + length + 1, text.Length - length - 1);
                    }
                }

                edit.Apply();
            }
        }
 private static void ReplaceContentsInsideTextBuffer(ITextBuffer textBuffer, string oldText, string newText)
 {
     ITextEdit edit = textBuffer.CreateEdit();
     edit.Replace(0, oldText.Length, newText);
     edit.Apply();
 }
        /// <summary>
        /// Attempts to run code cleanup on the specified generic document.
        /// </summary>
        /// <param name="document">The document for cleanup.</param>
        /// <param name="textBuffer">The text buffer for the document.</param>
        private void RunCodeCleanupGeneric(Document document, ITextBuffer textBuffer)
        {
            ITextDocument textDocument;

            var doc = (TextDocument)document.Object("TextDocument");
            textBuffer.Properties.TryGetProperty(typeof(ITextDocument), out textDocument);

            var path = doc.Parent.FullName;

            FileConfiguration settings;
            if (!ConfigLoader.TryLoad(path, out settings))
                return;

            using (ITextEdit edit = textBuffer.CreateEdit())
            {
                ITextSnapshot snapshot = edit.Snapshot;

                if (settings.Charset != null && textDocument != null)
                    FixDocumentCharset(textDocument, settings.Charset.Value);

                if (settings.TryKeyAsBool("trim_trailing_whitespace"))
                    TrimTrailingWhitespace(snapshot, edit);

                if (settings.TryKeyAsBool("insert_final_newline"))
                    InsertFinalNewline(snapshot, edit, settings.EndOfLine());

                var eol = settings.EndOfLine();
                FixLineEndings(snapshot, edit, eol);

                edit.Apply();
            }
        }
 // Stolen from Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.DocumentProvider.StandardTextDocument
 private static void UpdateText(SourceText newText, ITextBuffer buffer, EditOptions options)
 {
     using (ITextEdit textEdit = buffer.CreateEdit(options, null, null))
     {
         SourceText oldText = buffer.CurrentSnapshot.AsText();
         foreach (var current in newText.GetTextChanges(oldText))
         {
             textEdit.Replace(current.Span.Start, current.Span.Length, current.NewText);
         }
         textEdit.Apply();
     }
 }
            private static void UpdateText(SourceText newText, ITextBuffer buffer, EditOptions options)
            {
                using (var edit = buffer.CreateEdit(options, reiteratedVersionNumber: null, editTag: null))
                {
                    var oldSnapshot = buffer.CurrentSnapshot;
                    var oldText = oldSnapshot.AsText();
                    var changes = newText.GetTextChanges(oldText);

                    Workspace workspace = null;
                    if (Workspace.TryGetWorkspace(oldText.Container, out workspace))
                    {
                        var undoService = workspace.Services.GetService<ISourceTextUndoService>();
                        undoService.BeginUndoTransaction(oldSnapshot);
                    }

                    foreach (var change in changes)
                    {
                        edit.Replace(change.Span.Start, change.Span.Length, change.NewText);
                    }

                    edit.Apply();
                }
            }
        private static string GetFormattedText(ITextBuffer buffer, IList<TextChange> changes)
        {
            using (var edit = buffer.CreateEdit())
            {
                foreach (var change in changes)
                {
                    edit.Replace(change.Span.ToSpan(), change.NewText);
                }

                edit.Apply();
            }

            return buffer.CurrentSnapshot.GetText();
        }
Example #42
0
    public bool ReplaceAll(ITextBuffer tb) {
      Contract.Assume(tb != null);

      var tra = new TacticReplacerActor(tb);
      var isMoreMembers = tra.NextMemberInTld();
      var replaceStatus = TacticReplaceStatus.Success;
      var tedit = tb.CreateEdit();
      try
      {
        while (isMoreMembers && (replaceStatus == TacticReplaceStatus.Success || replaceStatus == TacticReplaceStatus.NoTactic))
        {
          var isMoreTactics = tra.NextTacticCallInMember();
          while (isMoreTactics && (replaceStatus == TacticReplaceStatus.Success || replaceStatus == TacticReplaceStatus.NoTactic))
          {
            replaceStatus = tra.ReplaceSingleTacticCall(tedit);
            isMoreTactics = tra.NextTacticCallInMember();
          }
          isMoreMembers = tra.NextMemberInTld();
        }

        if(replaceStatus==TacticReplaceStatus.Success || replaceStatus == TacticReplaceStatus.NoTactic)
          { tedit.Apply();} else { tedit.Dispose();}
      } catch { tedit.Dispose(); }
      return NotifyOfReplacement(replaceStatus);
    }
 private void AppendLineNoPromptInjection(ITextBuffer buffer)
 {
     using (var edit = buffer.CreateEdit(EditOptions.None, null, SuppressPromptInjectionTag))
     {
         edit.Insert(buffer.CurrentSnapshot.Length, _lineBreakString);
         edit.Apply();
     }
 }
            private static void UpdateText(SourceText newText, ITextBuffer buffer, EditOptions options)
            {
                using (var edit = buffer.CreateEdit(options, reiteratedVersionNumber: null, editTag: null))
                {
                    var oldText = buffer.CurrentSnapshot.AsText();
                    var changes = newText.GetTextChanges(oldText);

                    foreach (var change in changes)
                    {
                        edit.Replace(change.Span.Start, change.Span.Length, change.NewText);
                    }

                    edit.Apply();
                }
            }
Example #45
0
 private static ITextSnapshot ApplyChanges(ITextBuffer buffer, params TextChange[] changes)
 {
     using (var edit = buffer.CreateEdit())
     {
         foreach (var change in changes)
         {
             edit.Replace(change.Start, change.Length, change.Text);
         }
         return edit.Apply();
     }
 }
Example #46
0
        private static void UpdateFromImport(
            PythonAst curAst,
            ITextBuffer buffer,
            FromImportStatement fromImport,
            string name
        ) {
            NameExpression[] names = new NameExpression[fromImport.Names.Count + 1];
            NameExpression[] asNames = fromImport.AsNames == null ? null : new NameExpression[fromImport.AsNames.Count + 1];
            NameExpression newName = new NameExpression(name);
            for (int i = 0; i < fromImport.Names.Count; i++) {
                names[i] = fromImport.Names[i];
            }
            names[fromImport.Names.Count] = newName;

            if (asNames != null) {
                for (int i = 0; i < fromImport.AsNames.Count; i++) {
                    asNames[i] = fromImport.AsNames[i];
                }
            }

            var newImport = new FromImportStatement((ModuleName)fromImport.Root, names, asNames, fromImport.IsFromFuture, fromImport.ForceAbsolute);
            curAst.CopyAttributes(fromImport, newImport);

            var newCode = newImport.ToCodeString(curAst);

            var span = fromImport.GetSpan(curAst);
            int leadingWhiteSpaceLength = (fromImport.GetLeadingWhiteSpace(curAst) ?? "").Length;
            using (var edit = buffer.CreateEdit()) {
                edit.Delete(span.Start.Index - leadingWhiteSpaceLength, span.Length + leadingWhiteSpaceLength);
                edit.Insert(span.Start.Index, newCode);
                edit.Apply();
            }
        }