private void CleanUpEndLocation(ITrackingSpan?endTrackingSpan) { if (endTrackingSpan != null) { // Find the empty comment and remove it... var endSnapshotSpan = endTrackingSpan.GetSpan(SubjectBuffer.CurrentSnapshot); SubjectBuffer.Delete(endSnapshotSpan.Span); // Remove the whitespace before the comment if necessary. If whitespace is removed, // then remember the indentation depth so we can appropriately position the caret // in virtual space when the session is ended. var line = SubjectBuffer.CurrentSnapshot.GetLineFromPosition(endSnapshotSpan.Start.Position); var lineText = line.GetText(); if (lineText.Trim() == string.Empty) { _indentCaretOnCommit = true; var document = this.SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document != null) { var lineFormattingOptions = SubjectBuffer.GetLineFormattingOptions(EditorOptionsService, explicitFormat: false); _indentDepth = lineText.GetColumnFromLineOffset(lineText.Length, lineFormattingOptions.TabSize); } else { // If we don't have a document, then just guess the typical default TabSize value. _indentDepth = lineText.GetColumnFromLineOffset(lineText.Length, tabSize: 4); } SubjectBuffer.Delete(new Span(line.Start.Position, line.Length)); _ = SubjectBuffer.CurrentSnapshot.GetSpan(new Span(line.Start.Position, 0)); } } }
void SetTextStyle(Object sender, EventArgs e, String decoration) { ITextBuffer _mybuffer = CurrentUDNDocView.TextEditorView.TextBuffer; ITextSelection _selection = CurrentUDNDocView.TextEditorView.Selection; var start = _selection.Start.Position.Position; var end = _selection.End.Position.Position; var preceedingCharacter = _mybuffer.CurrentSnapshot.GetText(start - 1, 1); if (preceedingCharacter != decoration.Substring(preceedingCharacter.Length - 1, 1)) { if (_selection.Start.Position == _selection.End.Position) { _mybuffer.Insert(_selection.Start.Position, decoration); } else { _mybuffer.Insert(_selection.Start.Position, decoration); _mybuffer.Insert(_selection.End.Position, decoration); } CurrentUDNDocView.TextEditorView.Selection.Select( new SnapshotSpan(CurrentUDNDocView.TextEditorView.TextSnapshot, start + decoration.Length, end - start), false); } else { _mybuffer.Delete(new Span(start - decoration.Length, decoration.Length)); _mybuffer.Delete(new Span(end - decoration.Length, decoration.Length)); } }
public void Delete1() { Create("the quick brown fox"); _textBuffer.Insert(0, "ab"); _textBuffer.Delete(new Span(1, 1)); Assert.Null(_lastChange); Assert.Equal(TextChange.NewInsert("a"), _tracker.CurrentChange.Value); }
public void TrackReplace3() { Create("foo"); _mapRaw.SetLocalMark(new SnapshotPoint(_textBuffer.CurrentSnapshot, 2), 'a'); _textBuffer.Delete(new Span(0, 3)); var opt = _mapRaw.GetLocalMark(_textBuffer, 'a'); Assert.IsTrue(opt.IsSome()); var data = opt.Value; Assert.IsTrue(data.IsInVirtualSpace); Assert.AreEqual(0, data.Position.Position); }
public bool Delete(ITextRange range) { var snapshot = _textBuffer.CurrentSnapshot; var newSnapshot = _textBuffer.Delete(range.ToSpan()); return(newSnapshot.Version.VersionNumber > snapshot.Version.VersionNumber); }
private void DeleteAllEntries() { using (EditTextBuffer()) { _entries.RemoveAll(); _historyTextBuffer?.Delete(new Span(0, _historyTextBuffer.CurrentSnapshot.Length)); } }
/// <summary> /// Inserts a final new line for the given <see cref="ITextBuffer"/> based on /// whether the option to insert it is enabled in the current set of <see cref="IEditorOptions"/> applicable to the buffer /// </summary> /// <param name="buffer">The <see cref="ITextBuffer"/> in which the final new line has to be inserted in</param> /// <param name="editorOptions">The current set of <see cref="IEditorOptions"/> applicable to the buffer</param> /// <returns>Whether the operation on the buffer succeded or not</returns> public static bool TryInsertFinalNewLine(ITextBuffer buffer, IEditorOptions editorOptions) { var currentSnapshot = buffer.CurrentSnapshot; var lineCount = currentSnapshot.LineCount; var lastLine = currentSnapshot.GetLineFromLineNumber(lineCount - 1); ITextSnapshot changedSnapshot = null; if (lastLine.Start.Position != lastLine.EndIncludingLineBreak.Position) // Check if final new line is not already present { var IsTrimTrailingWhitespacesSetExplicitlyToFalse = editorOptions.IsOptionDefined <bool>(DefaultOptions.TrimTrailingWhiteSpaceOptionId, true) && !editorOptions.GetOptionValue <bool>(DefaultOptions.TrimTrailingWhiteSpaceOptionId); if (!IsTrimTrailingWhitespacesSetExplicitlyToFalse && !HasAnyNonWhitespaceCharacters(lastLine)) // Last Line contains only of whitespace and trim trailing whitespaces is set to false { var spanToDelete = lastLine.ExtentIncludingLineBreak; changedSnapshot = buffer.Delete(spanToDelete); } else // Non empty last line or empty last line with trim trailing whitespaces set to false. Insert a new line after the current line { string lineBreakToInsert = GetNewLineCharacterToInsert(lastLine, editorOptions); var positionToInsertNewLine = lastLine.End.Position; changedSnapshot = buffer.Insert(positionToInsertNewLine, lineBreakToInsert); } // Edits were successfull if (changedSnapshot != null && currentSnapshot != changedSnapshot) { return(true); } return(false); } return(true); }
private void DeleteSelectedTrackingSpans() { var selectedEntries = _entries.GetSelectedEntries(); using (EditTextBuffer()) { foreach (var entry in selectedEntries) { var snapshot = _historyTextBuffer.CurrentSnapshot; SnapshotPoint startPoint, endPoint; if (entry.Previous != null) { startPoint = entry.Previous.Span.GetEndPoint(snapshot); endPoint = entry.Span.GetEndPoint(snapshot); } else { startPoint = entry.Span.GetStartPoint(snapshot); endPoint = entry.Next?.Span.GetStartPoint(snapshot) ?? entry.Span.GetEndPoint(snapshot); } var span = new SnapshotSpan(startPoint, endPoint); _historyTextBuffer.Delete(span); } } }
private static (double elapsedMs, double allocatedMemory, double gcCollectionsCount) Test( string[] codeToWrite, ITextBuffer textBuffer, TeXCommentTagger teXCommentTagger, Stopwatch watch, bool taggingEnabled) { textBuffer.Delete(new Span(0, textBuffer.CurrentSnapshot.Length)); var totalMemory = GC.GetTotalMemory(true); var gcCount = GcCount(); watch.Restart(); for (int i = 0; i < codeToWrite.Length; i++) { textBuffer.Insert(textBuffer.CurrentSnapshot.Length, codeToWrite[i]); var spans = new NormalizedSnapshotSpanCollection(textBuffer.CurrentSnapshot, new Span(0, textBuffer.CurrentSnapshot.Length)); if (taggingEnabled) { var tags = teXCommentTagger.GetTags(spans); var count = 0; foreach (var tag in tags) { ++count; } } } return(watch.ElapsedMilliseconds, GC.GetTotalMemory(false) - totalMemory, GcCount() - gcCount); }
private void RemoveLine() { var line = _buffer.CurrentSnapshot.GetLineFromPosition(_item.Start); Span span = new Span(line.Start.Position - 1, line.Length + 1); _buffer.Delete(span); }
private static void RemoveChars(ITextBuffer textBuffer, int start, bool backspace, int count) { int offset = backspace ? -1 : 0; for (int i = 0; i < count; i++) { start += offset; textBuffer.Delete(new Span(start, 1)); } }
public static void DeletePackageMember(this JSONMember item, ITextBuffer buffer) { if (item.NextSibling != null && item.NextSibling.Text == "}" && item.PreviousSibling != null) { JSONMember prev = item.PreviousSibling as JSONMember; if (prev != null && prev.Comma != null) { Span comma = new Span(prev.Comma.Start, prev.Comma.Length); buffer.Delete(comma); } } var line = buffer.CurrentSnapshot.GetLineFromPosition(item.Start); Span lineSpan = new Span(line.Start.Position - 1, line.Length + 1); buffer.Delete(lineSpan); }
public void Edit_DeleteLinesAndUndo() { Create("foo", "bar", "baz", "qux"); var tlc = Create(_textBuffer, 1, 0); AssertPoint(tlc, 1, 0); using (var undoTransaction = _undoHistory.CreateTransaction("delete")) { _textBuffer.Delete(_textBuffer.GetLineRange(1, 2).ExtentIncludingLineBreak.Span); undoTransaction.Complete(); } Assert.Equal(new[] { "foo", "qux" }, _textBuffer.GetLines()); Assert.True(tlc.Point.IsNone()); Assert.True(tlc.VirtualPoint.IsNone()); _undoHistory.Undo(1); Assert.Equal(new[] { "foo", "bar", "baz", "qux" }, _textBuffer.GetLines()); AssertPoint(tlc, 1, 0); }
private void Clear() { SetReadOnlyRegionType(ReadOnlyRegionType.None); ITextBuffer textBuffer = WpfTextView.TextBuffer; textBuffer.Delete(new Span(0, textBuffer.CurrentSnapshot.Length)); inputLineStart = null; }
public void Caching() { Create("#if", "#endif", "#if", "#endif"); var blocks = _matchingTokenUtil.GetDirectiveBlocks(_textBuffer.CurrentSnapshot); Assert.Equal(2, blocks.Count); _textBuffer.Delete(_textBuffer.GetLineRange(2, 3).ExtentIncludingLineBreak); blocks = _matchingTokenUtil.GetDirectiveBlocks(_textBuffer.CurrentSnapshot); Assert.Equal(1, blocks.Count); }
private static void RemoveChars(ITextBuffer textBuffer, int start, bool backspace, int count) { int offset = backspace ? -1 : 0; for (int i = 0; i < count; i++) { start += offset; textBuffer.Delete(new Span(start, 1)); } }
public static void DeletePackageMember(this JSONMember item, ITextBuffer buffer) { if (item.NextSibling != null && item.NextSibling.Text == "}" && item.PreviousSibling != null) { JSONMember prev = item.PreviousSibling as JSONMember; if (prev != null && prev.Comma != null) { Span comma = new Span(prev.Comma.Start, prev.Comma.Length); buffer.Delete(comma); } } var line = buffer.CurrentSnapshot.GetLineFromPosition(item.Start); Span lineSpan = new Span(line.Start.Position - 1, line.Length + 1); buffer.Delete(lineSpan); }
private bool HandleWordDeleteCommand( ITextBuffer subjectBuffer, ITextView view, bool deleteToStart ) { if (_renameService.ActiveSession == null) { return(false); } var caretPoint = view.GetCaretPoint(subjectBuffer); if (caretPoint.HasValue) { if ( _renameService.ActiveSession.TryGetContainingEditableSpan( caretPoint.Value, out var span ) ) { int start = caretPoint.Value; int end = caretPoint.Value; if (!view.Selection.IsEmpty) { var selectedSpans = view.Selection.GetSnapshotSpansOnBuffer(subjectBuffer); if (selectedSpans.Count == 1 && span.Contains(selectedSpans.Single().Span)) { // We might want to delete past the caret's active position if there's a selection start = selectedSpans.Single().Start; end = selectedSpans.Single().End; } else { // we're outside of an editable span, so let this command go to the next handler return(false); } } subjectBuffer.Delete( deleteToStart ? Span.FromBounds(span.Start, end) : Span.FromBounds(start, span.End) ); return(true); } } return(false); }
private void CleanUpEndLocation(ITrackingSpan endTrackingSpan) { if (endTrackingSpan != null) { // Find the empty comment and remove it... var endSnapshotSpan = endTrackingSpan.GetSpan(SubjectBuffer.CurrentSnapshot); SubjectBuffer.Delete(endSnapshotSpan.Span); // Remove the whitespace before the comment if necessary. If whitespace is removed, // then remember the indentation depth so we can appropriately position the caret // in virtual space when the session is ended. var line = SubjectBuffer.CurrentSnapshot.GetLineFromPosition(endSnapshotSpan.Start.Position); var lineText = line.GetText(); if (lineText.Trim() == string.Empty) { indentCaretOnCommit = true; indentDepth = lineText.Length; SubjectBuffer.Delete(new Span(line.Start.Position, line.Length)); endSnapshotSpan = SubjectBuffer.CurrentSnapshot.GetSpan(new Span(line.Start.Position, 0)); } } }
public void Clear() { SetReadOnlyRegionType(ReadOnlyRegionType.None); ITextBuffer textBuffer = WpfTextView.TextBuffer; textBuffer.Delete(new Span(0, textBuffer.CurrentSnapshot.Length)); // Dispose existing incompleted input line _inputLineStart = null; // Raise event ConsoleCleared.Raise(this); }
public static void ApplyTextChange(ITextBuffer textBuffer, int start, int oldLength, int newLength, string newText) { if (oldLength == 0 && newText.Length > 0) { textBuffer.Insert(start, newText); } else if (oldLength > 0 && newText.Length > 0) { textBuffer.Replace(new Span(start, oldLength), newText); } else { textBuffer.Delete(new Span(start, oldLength)); } }
public static void refreshHighlighting(string file) { ITextSnapshot currentSnapShot = FileUtilities.Instance.GetIWpfTextView(file).TextSnapshot; if (currentSnapShot != null && currentSnapShot.Length > 0 && currentSnapShot.ContentType.TypeName == "StaDynLanguage") { ITextBuffer currentBuffer = currentSnapShot.TextBuffer; foreach (ITextSnapshotLine line in currentBuffer.CurrentSnapshot.Lines) { currentBuffer.Insert(line.Start.Position, " "); currentBuffer.Delete(new Span(line.Start.Position, 1)); // line.Snapshot.TextBuffer.Delete(new Span(0, 1)); } } }
private void ReloadDocuments(List <EnvDTE.Window> doclist) { var activeDoc = _applicationObject.ActiveDocument.Name; foreach (EnvDTE.Window window in doclist) { window.SetFocus(); SetFileAttributes(window); ITextBuffer _buffer = CurrentUDNDocView.TextEditorView.TextBuffer; ITextSnapshot _snap = CurrentUDNDocView.TextEditorView.TextSnapshot; var text = _snap.GetText(new Span(0, _snap.Length)); _buffer.Delete(new Span(0, _snap.Length)); _buffer.Insert(0, text); window.Document.Save(); } SetLastActiveWindow(activeDoc); }
public static void ApplyTextChange(ITextBuffer textBuffer, int start, int oldLength, int newLength, string newText) { TextChange tc = new TextChange(); tc.OldRange = new TextRange(start, oldLength); tc.NewRange = new TextRange(start, newLength); tc.OldTextProvider = new TextProvider(textBuffer.CurrentSnapshot); if (oldLength == 0 && newText.Length > 0) { textBuffer.Insert(start, newText); } else if (oldLength > 0 && newText.Length > 0) { textBuffer.Replace(new Span(start, oldLength), newText); } else { textBuffer.Delete(new Span(start, oldLength)); } }
public static void ApplyTextChange(ITextBuffer textBuffer, int start, int oldLength, int newLength, string newText) { TextChange tc = new TextChange(); tc.OldRange = new TextRange(start, oldLength); tc.NewRange = new TextRange(start, newLength); tc.OldTextProvider = new TextProvider(textBuffer.CurrentSnapshot); if (oldLength == 0 && newText.Length > 0) { textBuffer.Insert(start, newText); } else if (oldLength > 0 && newText.Length > 0) { textBuffer.Replace(new Span(start, oldLength), newText); } else { textBuffer.Delete(new Span(start, oldLength)); } }
public void WriteBackspace() { if (_inputLineStart == null) // If not in input mode, need unlock to enable output { SetReadOnlyRegionType(ReadOnlyRegionType.None); } // Delete last character from input buffer. ITextBuffer textBuffer = WpfTextView.TextBuffer; if (textBuffer.CurrentSnapshot.Length > 0) { textBuffer.Delete(new Span(textBuffer.CurrentSnapshot.Length - 1, 1)); } // Ensure caret visible (scroll) WpfTextView.Caret.EnsureVisible(); if (_inputLineStart == null) // If not in input mode, need lock again { SetReadOnlyRegionType(ReadOnlyRegionType.All); } }
public CommitResult TryCommit(IAsyncCompletionSession session, ITextBuffer buffer, CompletionItem item, char typedChar, CancellationToken token) { if (item.Properties.TryGetProperty(ReplAsyncCompletionSource.ProtocolItemKey, out Microsoft.VisualStudio.LanguageServer.Protocol.CompletionItem completionItem) && item.Properties.TryGetProperty(ReplAsyncCompletionSource.TriggerPointKey, out SnapshotPoint triggerLocation)) { // Tab and Enter characters should also commit. if (typedChar != '\t' && typedChar != '\n') { bool isCommitCharacter = false; if (completionItem.CommitCharacters != null && completionItem.CommitCharacters.Length != 0) { // If there are commit characters set for the particular completion item, then it should take precedence. foreach (var completionItemCommitCharacter in completionItem.CommitCharacters) { if (completionItemCommitCharacter.Length > 0 && completionItemCommitCharacter[0] == typedChar) { isCommitCharacter = true; break; } } if (!isCommitCharacter) { return(new CommitResult(isHandled: false, behavior: CommitBehavior.CancelCommit)); } } // TODO: Review if this should be removed if server passes in CommitTriggers for each CompletionItem. This is in place to unblock VC headless VS demo for build 2019 if (!isCommitCharacter && this.typicalDimissChars.Contains(typedChar)) { // If we got here it means the completion item has not specificed commit characters and we want to dismiss the commit and the intellisense session because it's a dismiss character. return(CommitResult.Handled); } } if (completionItem.TextEdit != null || completionItem.AdditionalTextEdits != null) { // Completion text edits are computed when the completion session is first triggered. The lines typed // after the completion session was started need to be deleted to revert the document to its original state. var caretPositionAtBuffer = session.TextView.GetCaretPointAtSubjectBuffer(buffer); if (caretPositionAtBuffer.HasValue) { var deleteTextLength = caretPositionAtBuffer.Value.Position - triggerLocation.Position; if (deleteTextLength > 0) { var deleteSpan = new Span(triggerLocation.Position, deleteTextLength); buffer.Delete(deleteSpan); } if (completionItem.TextEdit != null) { LspEditorUtilities.ApplyTextEdit(completionItem.TextEdit, triggerLocation.Snapshot, buffer); } else if (completionItem.InsertText != null) { buffer.Replace(session.ApplicableToSpan.GetSpan(buffer.CurrentSnapshot), completionItem.InsertText); } if (completionItem.AdditionalTextEdits != null) { LspEditorUtilities.ApplyTextEdits(completionItem.AdditionalTextEdits, triggerLocation.Snapshot, buffer); } return(CommitResult.Handled); } } } return(CommitResult.Unhandled); }
public void Delete(ITextRange range) => _textBuffer.Delete(range.ToSpan());
public CommitResult TryCommit(IAsyncCompletionSession session, ITextBuffer buffer, CompletionItem item, char typedChar, CancellationToken token) { if (item.Properties.TryGetProperty(AsyncCompletionSource.ProtocolItemKey, out LSP.CompletionItem protocolItem) && item.Properties.TryGetProperty(AsyncCompletionSource.TriggerPointKey, out SnapshotPoint triggerLocation)) { var commitArray = protocolItem.CommitCharacters ?? new string[] { }; // Commit chars are normally empty // Tab, Enter and programmatical command should always commit regardless of commit characters on individual items. if (typedChar != '\0' && typedChar != '\t' && typedChar != '\n' && commitArray != null) { bool commitCharacterFound = false; for (var n = 0; n < commitArray.Length; n++) { var commitString = commitArray[n]; if (!string.IsNullOrEmpty(commitString) && commitString[0] == typedChar) { commitCharacterFound = true; } } if (!commitCharacterFound) { return(new CommitResult(isHandled: false, behavior: CommitBehavior.CancelCommit)); } } // Contract with Roslyn: if an item has no insert text and no text edit, // attempt to resolve it to get these values. // We don't call resolve for all items because it's a network call on a typing hot path. if (protocolItem.InsertText == null && protocolItem.TextEdit == null && item.Properties.TryGetProperty(ResolvePropertyKey, out Func <LSP.CompletionItem, CancellationToken, Task <LSP.CompletionItem> > resolver) && resolver != null) { try { ThreadHelper.JoinableTaskFactory.Run(async() => { await this.ResolveCompletionItemAsync(item, token); }); } catch (Exception ex) when(!(ex is OperationCanceledException)) { // We have not received the resolved item due to an error. return(new CommitResult(isHandled: false, behavior: CommitBehavior.CancelCommit)); } if (token.IsCancellationRequested) { // We have not received the resolved item due to a timeout. return(new CommitResult(isHandled: false, behavior: CommitBehavior.CancelCommit)); } } if (protocolItem.TextEdit != null || protocolItem.AdditionalTextEdits != null) { // Completion text edits are computed when the completion session is first triggered. The lines typed // after the completion session was started need to be deleted to revert the document to its original state. var caretPositionAtBuffer = session.TextView.GetCaretPointAtSubjectBuffer(buffer); if (caretPositionAtBuffer.HasValue) { var deleteTextLength = caretPositionAtBuffer.Value.Position - triggerLocation.Position; if (deleteTextLength > 0) { var deleteSpan = new Span(triggerLocation.Position, deleteTextLength); buffer.Delete(deleteSpan); } if (protocolItem.TextEdit != null) { Utilities.ApplyTextEdit(protocolItem.TextEdit, triggerLocation.Snapshot, buffer); } else if (protocolItem.InsertText != null) { buffer.Replace(session.ApplicableToSpan.GetSpan(buffer.CurrentSnapshot), protocolItem.InsertText); } else if (protocolItem.Label != null) { buffer.Replace(session.ApplicableToSpan.GetSpan(buffer.CurrentSnapshot), protocolItem.Label); } if (protocolItem.AdditionalTextEdits != null) { Utilities.ApplyTextEdits(protocolItem.AdditionalTextEdits, triggerLocation.Snapshot, buffer); } this.textView.Caret.EnsureVisible(); this.ExecuteCompletionCommand(languageClient, protocolItem, token); return(CommitResult.Handled); } } this.ExecuteCompletionCommand(languageClient, protocolItem, token); } return(CommitResult.Unhandled); }