/// <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(); } } }
static void DeleteExistingDefinition(ITextSnapshot snapshot, Parser.Result result) { DTE2 dte = Global.GetDTE2(); ITextEdit edit = snapshot.TextBuffer.CreateEdit(); try { ITextSnapshotLine currentLine; for (int i = result.StartLine - 1; i <= result.EndLine - 1; i++) { currentLine = snapshot.GetLineFromLineNumber(i); edit.Delete(currentLine.Start.Position, currentLine.LengthIncludingLineBreak); } //remove separating empty line if found if (snapshot.LineCount > result.EndLine) { currentLine = snapshot.GetLineFromLineNumber(result.EndLine); if (string.IsNullOrWhiteSpace(currentLine.GetText())) { edit.Delete(currentLine.Start.Position, currentLine.LengthIncludingLineBreak); } } edit.Apply(); } catch { edit.Cancel(); } dte.ActiveDocument.Save(); }
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(); } }
public override bool Unindent() { if (_startPoint.LineNumber == _endPoint.LineNumber) { return(_startPoint.RemovePreviousIndent()); } using (ITextEdit edit = TextBuffer.AdvancedTextBuffer.CreateEdit()) { ITextSnapshot snapshot = TextBuffer.AdvancedTextBuffer.CurrentSnapshot; for (int i = _startPoint.LineNumber; i <= _endPoint.LineNumber; i++) { ITextSnapshotLine line = snapshot.GetLineFromLineNumber(i); if ((line.Length > 0) && (_endPoint.CurrentPosition != line.Start)) { if (snapshot[line.Start] == '\t') { if (!edit.Delete(new Span(line.Start, 1))) { return(false); } } else { int spacesToRemove = 0; for (; (line.Start + spacesToRemove < snapshot.Length) && (spacesToRemove < _editorOptions.GetTabSize()); spacesToRemove++) { if (snapshot[line.Start + spacesToRemove] != ' ') { break; } } if (spacesToRemove > 0) { if (!edit.Delete(new Span(line.Start, spacesToRemove))) { return(false); } } } } } edit.Apply(); if (edit.Canceled) { return(false); } } return(true); }
/// <summary> /// Rollback all modified text in the document except specified <see cref="IDiffChange"/>. /// </summary> /// <param name="diffChange">Information about a specific difference between two sequences.</param> private void RollbackAllButThisChange(IDiffChange diffChange) { ITextEdit edit = _textView.TextBuffer.CreateEdit(); Span viewSpan; try { string modifiedRegionText = _marginCore.GetModifiedText(diffChange, false); string originalText = _marginCore.GetOriginalText(); edit.Delete(0, edit.Snapshot.Length); edit.Insert(0, originalText); ApplyEdit(edit, "Undo Modified Text"); edit = _textView.TextBuffer.CreateEdit(); ITextSnapshotLine startLine = edit.Snapshot.GetLineFromLineNumber(diffChange.OriginalStart); ITextSnapshotLine endLine = edit.Snapshot.GetLineFromLineNumber(diffChange.OriginalEnd); int start = startLine.Start.Position; int length = endLine.EndIncludingLineBreak.Position - start; switch (diffChange.ChangeType) { case DiffChangeType.Insert: edit.Insert(start, modifiedRegionText); viewSpan = new Span(start, modifiedRegionText.Length); break; case DiffChangeType.Delete: edit.Delete(start, length); viewSpan = new Span(start, 0); break; case DiffChangeType.Change: edit.Replace(start, length, modifiedRegionText); viewSpan = new Span(start, modifiedRegionText.Length); break; default: throw new InvalidEnumArgumentException(); } ApplyEdit(edit, "Restore Modified Region"); } catch (Exception) { edit.Cancel(); throw; } var viewSnapshotSpan = new SnapshotSpan(_textView.TextSnapshot, viewSpan); _textView.ViewScroller.EnsureSpanVisible(viewSnapshotSpan, EnsureSpanVisibleOptions.AlwaysCenter); }
/// <summary> /// Removes the comment markers from a set of spans /// </summary> static void UncommentSpans(ITextEdit edit, IEnumerable <SnapshotSpan> commentedSpans) { int beginCommentLength = OpenComment.Length; int endCommentLength = CloseComment.Length; foreach (var commentSpan in commentedSpans) { edit.Delete(commentSpan.Start, beginCommentLength); edit.Delete(commentSpan.End - endCommentLength, endCommentLength); } }
/// <summary> /// Unindent the given box selection /// </summary> /// <remarks> /// This is fairly close to the normal text range unindenting logic, except that it also /// unindents an empty selection at the endline, which the normal text range ignores. /// </remarks> private bool BoxUnindent() { using (ITextEdit edit = TextBuffer.AdvancedTextBuffer.CreateEdit()) { ITextSnapshot snapshot = TextBuffer.AdvancedTextBuffer.CurrentSnapshot; int startLineNumber = GetStartPoint().LineNumber; int endLineNumber = GetEndPoint().LineNumber; for (int i = startLineNumber; i <= endLineNumber; i++) { ITextSnapshotLine line = snapshot.GetLineFromLineNumber(i); if (line.Length > 0) { if (snapshot[line.Start] == '\t') { if (!edit.Delete(new Span(line.Start, 1))) { return(false); } } else { int spacesToRemove = 0; for (; (line.Start + spacesToRemove < snapshot.Length) && (spacesToRemove < _editorOptions.GetTabSize()); spacesToRemove++) { if (snapshot[line.Start + spacesToRemove] != ' ') { break; } } if (spacesToRemove > 0) { if (!edit.Delete(new Span(line.Start, spacesToRemove))) { return(false); } } } } } edit.Apply(); if (edit.Canceled) { return(false); } } return(true); }
/// <summary> /// Attempt to uncomment a span of text using a particular block comment format. /// </summary> /// <param name="span">The span of text to uncomment.</param> /// <param name="edit">The <see cref="ITextEdit"/> instance to use for applying changes.</param> /// <param name="format">The block comment format to use for uncommenting the code.</param> /// <param name="result">Upon return, a <see cref="VirtualSnapshotSpan"/> containing the uncommented /// code.</param> /// <returns> /// <para><see langword="true"/> if the span of text was uncommented using the specified block comment /// <paramref name="format"/>.</para> /// <para>-or-</para> /// <para>false if the span of text was not a complete block comment with the specified /// <paramref name="format"/>.</para> /// </returns> /// <exception cref="ArgumentNullException">If <paramref name="edit"/> is <see langword="null"/>.</exception> protected virtual bool TryUncommentBlock(VirtualSnapshotSpan span, ITextEdit edit, BlockCommentFormat format, out VirtualSnapshotSpan result) { if (edit == null) { throw new ArgumentNullException(nameof(edit)); } if (format == null) { throw new ArgumentNullException(nameof(format)); } string blockStart = format.StartText; string blockEnd = format.EndText; int startLen = span.Start.Position.GetContainingLine().Length; int endLen = span.End.Position.GetContainingLine().Length; TrimSpan(ref span); //special case no selection, try and uncomment the current line. if (span.IsEmpty) { VirtualSnapshotPoint start = new VirtualSnapshotPoint(span.Start.Position.GetContainingLine().Start + ScanToNonWhitespaceChar(span.Start.Position.GetContainingLine())); VirtualSnapshotPoint end = span.IsInVirtualSpace ? span.End : new VirtualSnapshotPoint(span.End.Position.GetContainingLine().End); span = new VirtualSnapshotSpan(start, end); } // Check that comment start and end blocks are possible. if ((span.Start.Position - span.Start.Position.GetContainingLine().Start) + blockStart.Length <= startLen && (span.End.Position - span.End.Position.GetContainingLine().Start) - blockStart.Length >= 0) { string startText = span.Snapshot.GetText(span.Start.Position, blockStart.Length); if (startText.Equals(blockStart, StringComparison.Ordinal)) { SnapshotSpan linespan = span.SnapshotSpan; linespan = new SnapshotSpan(span.End.Position - blockEnd.Length, span.End.Position); string endText = linespan.GetText(); if (endText.Equals(blockEnd, StringComparison.Ordinal)) { //yes, block comment selected; remove it edit.Delete(linespan); edit.Delete(span.Start.Position, blockStart.Length); result = new VirtualSnapshotSpan(span.SnapshotSpan); return(true); } } } result = default(VirtualSnapshotSpan); return(false); }
protected override void Modify(ITextEdit edit, ITextSnapshotLine line) { if (line.GetText().StartsWith("#")) { edit.Delete(line.Start, 1); } }
private void DeleteSpan(NormalizedSnapshotSpanCollection applicabilitySpans) { using (ITextUndoTransaction undoTransaction = _undoHistory.CreateTransaction("HTML Cut")) { _editorOperations.AddBeforeTextBufferChangePrimitive(); bool successfulEdit = true; using (ITextEdit edit = _textView.TextBuffer.CreateEdit()) { foreach (SnapshotSpan span in applicabilitySpans) { successfulEdit &= edit.Delete(span); } if (successfulEdit) { edit.Apply(); } } _editorOperations.AddAfterTextBufferChangePrimitive(); if (successfulEdit) { undoTransaction.Complete(); } } }
public override async void Invoke(CancellationToken cancellationToken) { try { await LibraryHelpers.UninstallAsync(_provider.ConfigFilePath, _provider.InstallationState.LibraryId, cancellationToken).ConfigureAwait(false); await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); using (ITextEdit edit = TextBuffer.CreateEdit()) { var arrayElement = _provider.LibraryObject.Parent as JSONArrayElement; var prev = arrayElement.PreviousSibling as JSONArrayElement; var next = arrayElement.NextSibling as JSONArrayElement; int start = TextBuffer.CurrentSnapshot.GetLineFromPosition(arrayElement.Start).Start; int end = TextBuffer.CurrentSnapshot.GetLineFromPosition(arrayElement.AfterEnd).EndIncludingLineBreak; if (next == null && prev?.Comma != null) { start = prev.Comma.Start; end = TextBuffer.CurrentSnapshot.GetLineFromPosition(arrayElement.AfterEnd).End; } edit.Delete(Span.FromBounds(start, end)); edit.Apply(); } } catch (Exception ex) { Logger.LogEvent(ex.ToString(), Microsoft.Web.LibraryManager.Contracts.LogLevel.Error); } }
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(); } } } }
/// <summary> /// Given a list of <see cref="ITrackingSpan"/>s, deletes them from the buffer. /// </summary> protected bool DeleteSpans(IList <ITrackingSpan> spans) { if (spans == null) { throw new ArgumentNullException(nameof(spans)); } ITextSnapshot mostRecentSnapshot = _cocoaTextView.TextSnapshot; using (ITextEdit textEdit = _cocoaTextView.TextBuffer.CreateEdit()) { foreach (ITrackingSpan span in spans) { if (!textEdit.Delete(span.GetSpan(mostRecentSnapshot))) { return(false); } } textEdit.Apply(); if (textEdit.Canceled) { return(false); } } return(true); }
internal void ComputeSourceEdits(FrugalList <TextChange> changes) { ITextEdit xedit = this.group.GetEdit((BaseBuffer)this.sourceBuffer); foreach (TextChange change in changes) { if (change.OldLength > 0) { IList <SnapshotSpan> sourceDeletionSpans = this.currentElisionSnapshot.MapToSourceSnapshots(new Span(change.OldPosition, change.OldLength)); foreach (SnapshotSpan sourceDeletionSpan in sourceDeletionSpans) { xedit.Delete(sourceDeletionSpan); } } if (change.NewLength > 0) { // change includes an insertion ReadOnlyCollection <SnapshotPoint> sourceInsertionPoints = this.currentElisionSnapshot.MapInsertionPointToSourceSnapshots(change.OldPosition, null); if (sourceInsertionPoints.Count == 1) { // the insertion point is unambiguous xedit.Insert(sourceInsertionPoints[0].Position, change.NewText); } else { // the insertion is at the boundary of source spans int[] insertionSizes = new int[sourceInsertionPoints.Count]; if (this.resolver != null) { this.resolver.FillInInsertionSizes(new SnapshotPoint(this.currentElisionSnapshot, change.OldPosition), sourceInsertionPoints, change.NewText, insertionSizes); } // if resolver was not provided, we just use zeros for the insertion sizes, which will push the entire insertion // into the last slot. int pos = 0; for (int i = 0; i < insertionSizes.Length; ++i) { // contend with any old garbage that the client passed back. int size = (i == insertionSizes.Length - 1) ? change.NewLength - pos : Math.Min(insertionSizes[i], change.NewLength - pos); if (size > 0) { xedit.Insert(sourceInsertionPoints[i].Position, TextChange.ChangeNewSubstring(change, pos, size)); pos += size; if (pos == change.NewLength) { break; // inserted text is used up, whether we've visited all of the insertionSizes or not } } } } } } this.editApplicationInProgress = true; }
private static void UnCommentRegion(SnapshotPoint start, SnapshotPoint end) { ITextSnapshot snapshot = start.Snapshot; using (ITextEdit edit = snapshot.TextBuffer.CreateEdit()) { for (int i = start.GetContainingLine().LineNumber; i <= end.GetContainingLine().LineNumber; i++) { ITextSnapshotLine currentLine = snapshot.GetLineFromLineNumber(i); string lineText = currentLine.GetText(); for (int j = 0; j < lineText.Length - 1; j++) { if (!char.IsWhiteSpace(lineText[j])) { if (lineText[j] == '/' && lineText[j + 1] == '/') { edit.Delete(currentLine.Start.Position + j, 2); break; } } } } edit.Apply(); } }
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"); } }
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); }
bool TryUncommentSingleLineComments(SnapshotSpan span, ITextEdit textEdit, List <ITrackingSpan> spansToSelect) { // First see if we're selecting any lines that have the single-line comment prefix. // If so, then we'll just remove the single-line comment prefix from those lines. bool textChanges = false; var firstAndLastLine = DetermineFirstAndLastLine(span); for (int lineNumber = firstAndLastLine.Item1.LineNumber; lineNumber <= firstAndLastLine.Item2.LineNumber; ++lineNumber) { var line = span.Snapshot.GetLineFromLineNumber(lineNumber); var lineText = line.GetText(); if (lineText.Trim().StartsWith(SyntaxFacts.SingleLineComment, StringComparison.Ordinal)) { textEdit.Delete(new Span(line.Start.Position + lineText.IndexOf(SyntaxFacts.SingleLineComment, StringComparison.Ordinal), SyntaxFacts.SingleLineComment.Length)); textChanges = true; } } // If we made any changes, select the entirety of the lines we change, so that subsequent invocations will // affect the same lines. if (!textChanges) { return(false); } spansToSelect.Add(span.Snapshot.CreateTrackingSpan( Span.FromBounds(firstAndLastLine.Item1.Start.Position, firstAndLastLine.Item2.End.Position), SpanTrackingMode.EdgeExclusive)); return(true); }
/// <summary> /// Handler for removed text by other editor /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void my_RemovedText(object sender, EditedTextEventArgs e) { if (e.File == filename) { lock (CoProNetwork.locker) { while (e.Seq != cb.ExpectedSequence)//if excpected id is the id i got { System.Threading.Monitor.Wait(CoProNetwork.locker); Debug.WriteLine("Recieved seq : " + e.Seq + " Expected seq : " + cb.ExpectedSequence); } trackDict[e.Editor] = m_textView.TextSnapshot.CreateTrackingPoint(e.Location, PointTrackingMode.Positive); uiDisp.Invoke(new Action(() => { ITextEdit edit = m_textView.TextBuffer.CreateEdit(); var curTrackPoint = trackDict[e.Editor]; edit.Delete(e.Location, int.Parse(e.Command.Split(';')[1])); mySideCalling = false; edit.Apply(); edit.Dispose(); })); System.Threading.Monitor.PulseAll(CoProNetwork.locker); } } }
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(); }
void TryUncommentContainingBlockComment(SnapshotSpan span, ITextEdit textEdit, List <ITrackingSpan> spansToSelect) { int positionOfStart; var positionOfEnd = -1; var spanText = span.GetText(); var trimmedSpanText = spanText.Trim(); // See if the selection includes just a block comment (plus whitespace) if (trimmedSpanText.StartsWith(SyntaxFacts.BlockCommentStart, StringComparison.Ordinal) && trimmedSpanText.EndsWith(SyntaxFacts.BlockCommentEnd, StringComparison.Ordinal)) { positionOfStart = span.Start + spanText.IndexOf(SyntaxFacts.BlockCommentStart, StringComparison.Ordinal); positionOfEnd = span.Start + spanText.LastIndexOf(SyntaxFacts.BlockCommentEnd, StringComparison.Ordinal); } else { // See if we are (textually) contained in a block comment. // This could allow a selection that spans multiple block comments to uncomment the beginning of // the first and end of the last. Oh well. positionOfStart = span.Snapshot.LastIndexOf(SyntaxFacts.BlockCommentStart, span.Start, caseSensitive: true); // If we found a start comment marker, make sure there isn't an end comment marker after it but before our span. if (positionOfStart >= 0) { var lastEnd = span.Snapshot.LastIndexOf(SyntaxFacts.BlockCommentEnd, span.Start, caseSensitive: true); if (lastEnd < positionOfStart) { positionOfEnd = span.Snapshot.IndexOf(SyntaxFacts.BlockCommentEnd, span.End, caseSensitive: true); } else if (lastEnd + SyntaxFacts.BlockCommentEnd.Length > span.End) { // The end of the span is *inside* the end marker, so searching backwards found it. positionOfEnd = lastEnd; } } } if (positionOfStart < 0 || positionOfEnd < 0) { return; } textEdit.Delete(new Span(positionOfStart, SyntaxFacts.BlockCommentStart.Length)); textEdit.Delete(new Span(positionOfEnd, SyntaxFacts.BlockCommentEnd.Length)); spansToSelect.Add(span.Snapshot.CreateTrackingSpan(Span.FromBounds(positionOfStart, positionOfEnd + SyntaxFacts.BlockCommentEnd.Length), SpanTrackingMode.EdgeExclusive)); }
public ITextSnapshot Delete(Span deleteSpan) { using (ITextEdit textEdit = CreateEdit()) { textEdit.Delete(deleteSpan); return(textEdit.Apply()); } }
public void Execute() { IWpfTextView textView = txtMgr.GetTextView(); ITextSnapshot snapshot = textView.TextSnapshot; if (snapshot != snapshot.TextBuffer.CurrentSnapshot) { return; } int selectionLastLineNumber = 0; int selectionFirstLineNumber = 0; if (!textView.Selection.IsEmpty) { selectionLastLineNumber = textView.Selection.End.Position.GetContainingLine().LineNumber; selectionFirstLineNumber = textView.Selection.Start.Position.GetContainingLine().LineNumber; } else { selectionFirstLineNumber = selectionLastLineNumber = textView.GetCaretLine().End.GetContainingLine().LineNumber; } textView.Selection.Clear(); try { using (ITextEdit edit = textView.TextBuffer.CreateEdit()) { for (int i = selectionLastLineNumber; i >= selectionFirstLineNumber; i--) { var line = textView.GetLine(i); edit.Delete(new Span(line.Start.Position, line.LengthIncludingLineBreak)); } edit.Apply(); } } catch { } ////ITextSnapshotLine currentLineContent = snapshot.GetLineFromPosition(textView.Caret.Position.BufferPosition); //ITextViewLine currentLineContent = textView.Caret.ContainingTextViewLine; //double initialStartPosition = textView.Caret.Left; //ITextEdit edit = snapshot.TextBuffer.CreateEdit(); //edit.Delete(currentLineContent.Start.Position, currentLineContent.LengthIncludingLineBreak); //edit.Apply(); //ITextSnapshotLine newCurrentLineContent = snapshot.GetLineFromPosition(textView.Caret.Position.BufferPosition); ////make a new selection //ITextViewLine line = textView.Caret.ContainingTextViewLine; //textView.Caret.MoveTo(line, initialStartPosition - 1); }
public void PreOverType(out bool handledCommand) { handledCommand = false; if (ClosingPoint == null) { return; } // Brace completion is not cancellable. var cancellationToken = CancellationToken.None; var snapshot = this.SubjectBuffer.CurrentSnapshot; var document = snapshot.GetOpenDocumentInCurrentContextWithChanges(); SnapshotPoint closingSnapshotPoint = ClosingPoint.GetPoint(snapshot); if (!HasForwardTyping && _session.AllowOverType(this, cancellationToken)) { SnapshotPoint?caretPos = this.GetCaretPosition(); Debug.Assert(caretPos.HasValue && caretPos.Value.Position < closingSnapshotPoint.Position); // ensure that we are within the session before clearing if (caretPos.HasValue && caretPos.Value.Position < closingSnapshotPoint.Position && closingSnapshotPoint.Position > 0) { using (ITextUndoTransaction undo = CreateUndoTransaction()) { _editorOperations.AddBeforeTextBufferChangePrimitive(); SnapshotSpan span = new SnapshotSpan(caretPos.Value, closingSnapshotPoint.Subtract(1)); using (ITextEdit edit = SubjectBuffer.CreateEdit()) { edit.Delete(span); if (edit.HasFailedChanges) { Debug.Fail("Unable to clear closing brace"); edit.Cancel(); undo.Cancel(); } else { handledCommand = true; edit.Apply(); MoveCaretToClosingPoint(); _editorOperations.AddAfterTextBufferChangePrimitive(); undo.Complete(); } } } } } }
protected virtual bool TryUncommentBlock(SnapshotSpan span, ITextEdit edit, BlockCommentFormat format, out SnapshotSpan result) { Contract.Requires <ArgumentNullException>(edit != null, "edit"); Contract.Requires <ArgumentNullException>(format != null, "format"); string blockStart = format.StartText; string blockEnd = format.EndText; int startLen = span.Start.GetContainingLine().Length; int endLen = span.End.GetContainingLine().Length; TrimSpan(ref span); //sp. case no selection, try and uncomment the current line. if (span.IsEmpty) { span = new SnapshotSpan(span.Start.GetContainingLine().Start + ScanToNonWhitespaceChar(span.Start.GetContainingLine()), span.End.GetContainingLine().End); } // Check that comment start and end blocks are possible. if ((span.Start - span.Start.GetContainingLine().Start) + blockStart.Length <= startLen && (span.End - span.End.GetContainingLine().Start) - blockStart.Length >= 0) { string startText = span.Snapshot.GetText(span.Start.Position, blockStart.Length); if (startText == blockStart) { SnapshotSpan linespan = span; linespan = new SnapshotSpan(span.End - blockEnd.Length, span.End); string endText = linespan.GetText(); if (endText == blockEnd) { //yes, block comment selected; remove it edit.Delete(linespan); edit.Delete(span.Start.Position, blockStart.Length); result = span; return(true); } } } result = default(SnapshotSpan); return(false); }
private void Rollback() { var snapshot = _hunkRangeInfo.Snapshot; if (snapshot != snapshot.TextBuffer.CurrentSnapshot) { return; } using (ITextEdit edit = snapshot.TextBuffer.CreateEdit()) { Span newSpan; if (_hunkRangeInfo.IsDeletion) { ITextSnapshotLine startLine = snapshot.GetLineFromLineNumber(_hunkRangeInfo.NewHunkRange.StartingLineNumber); newSpan = new Span(startLine.Start.Position, 0); } else { ITextSnapshotLine startLine = snapshot.GetLineFromLineNumber(_hunkRangeInfo.NewHunkRange.StartingLineNumber); ITextSnapshotLine endLine = snapshot.GetLineFromLineNumber(_hunkRangeInfo.NewHunkRange.StartingLineNumber + _hunkRangeInfo.NewHunkRange.NumberOfLines - 1); newSpan = Span.FromBounds(startLine.Start.Position, endLine.EndIncludingLineBreak.Position); } if (_hunkRangeInfo.IsAddition) { ITextSnapshotLine startLine = snapshot.GetLineFromLineNumber(_hunkRangeInfo.NewHunkRange.StartingLineNumber); ITextSnapshotLine endLine = snapshot.GetLineFromLineNumber(_hunkRangeInfo.NewHunkRange.StartingLineNumber + _hunkRangeInfo.NewHunkRange.NumberOfLines - 1); edit.Delete(Span.FromBounds(startLine.Start.Position, endLine.EndIncludingLineBreak.Position)); } else { string lineBreak = snapshot.GetLineFromLineNumber(0).GetLineBreakText(); if (string.IsNullOrEmpty(lineBreak)) { lineBreak = Environment.NewLine; } string originalText = string.Join(lineBreak, _hunkRangeInfo.OriginalText); if (_hunkRangeInfo.NewHunkRange.StartingLineNumber + _hunkRangeInfo.NewHunkRange.NumberOfLines != snapshot.LineCount) { originalText += lineBreak; } edit.Replace(newSpan, originalText); } edit.Apply(); // immediately hide the change _reverted = true; ShowPopup = false; IsVisible = false; } }
/// <summary> /// This function is the callback used to execute the command when the menu item is clicked. /// See the constructor to see how the menu item is associated with this function using /// OleMenuCommandService service and MenuCommand class. /// </summary> /// <param name="sender">Event sender.</param> /// <param name="e">Event args.</param> private void MenuItemCallback(object sender, EventArgs e) { DTE dte = (DTE)this.ServiceProvider.GetService(typeof(DTE)); dte.ActiveDocument.Save(); var fileName = dte.ActiveDocument.FullName; var selectedStatements = (List <Statement>)HelpFunctions.GetSelectedStatements(); if (selectedStatements.Count == 1 && selectedStatements[0] is UpdateStmt) { UpdateStmt curr = (UpdateStmt)selectedStatements[0]; var arg = ((ApplySuffix)((ExprRhs)curr.Rhss[0]).Expr).Args; Microsoft.Dafny.Type[] InTypes = getTypes(arg); var rets = curr.Lhss; Microsoft.Dafny.Type[] retTypes = getTypes(rets); Method m = HelpFunctions.FindMethod(fileName, ((NameSegment)((ApplySuffix)((ExprRhs)curr.Rhss[0]).Expr).Lhs).Name, InTypes, retTypes); edit = HelpFunctions.GetWpfView().TextBuffer.CreateEdit(); inline(curr, fileName, m); edit.Apply(); //////////////////////////////////// } else if (selectedStatements.Count == 0 && HelpFunctions.GetCurrentMethod() != null) { Method currMethod = HelpFunctions.GetCurrentMethod(); var program = HelpFunctions.GetProgram(fileName); var decls = program.Modules().SelectMany(m => m.TopLevelDecls).ToList(); var callables = ModuleDefinition.AllCallables(decls); edit = HelpFunctions.GetWpfView().TextBuffer.CreateEdit(); foreach (var curr in callables) { if (curr is Method) { var m = curr as Method; traverse(m.Body, currMethod); } } var textView = HelpFunctions.GetWpfView(); var start = currMethod.tok.pos; if (currMethod is Lemma) { start -= 6; } else { start -= 7; } var end = currMethod.BodyEndTok.pos + 1; edit.Delete(start, end - start); edit.Apply(); } //HelpFunctions.prettyPrint(fileName); }
private ITextEdit Fix(RobotsTxtLineSyntax line) { ITextBuffer buffer = line.Record.Document.Snapshot.TextBuffer; ITextSnapshotLine textLine = line.Span.Start.GetContainingLine(); ITextEdit edit = buffer.CreateEdit(); edit.Delete(textLine.ExtentIncludingLineBreak); return(edit); }
private void ChangeTechCallback(object sender, EventArgs e) { ITextBuffer buffer; int selStart, selEnd; string currentCode; bool emptySelection; if (GetBufferAndSelection(out buffer, out selStart, out selEnd, out currentCode, out emptySelection)) { ITextEdit edit = buffer.CreateEdit(); edit.Delete(selStart, selEnd - selStart); string text; if (emptySelection) { text = "#if " + GetSelectedTechnology() + Environment.NewLine + currentCode + "#else" + Environment.NewLine + currentCode; if (_includeEndIfComment) { text += "#endif" + GetSelectedTechnologyComment(); } else { text += "#endif"; } text += Environment.NewLine; } else { text = "#if " + GetSelectedTechnology() + Environment.NewLine + currentCode + Environment.NewLine + "#else" + Environment.NewLine + currentCode + Environment.NewLine; if (_includeEndIfComment) { text += "#endif" + GetSelectedTechnologyComment(); } else { text += "#endif"; } } edit.Insert(selStart, text); edit.Apply(); } }
/// <summary> /// 确认完成或者丢弃 /// </summary> private bool Complete(bool force) { if (_CurrentSession == null || !_CurrentSession.IsStarted) { return(false); } try { //如果用户没有选择并且主动丢弃 if (!_CurrentSession.SelectedCompletionSet.SelectionStatus.IsSelected && !force) { _CurrentSession.Dismiss(); return(false); } else { ITextEdit edit = _CurrentSession.TextView.TextBuffer.CreateEdit(); ITextSnapshot snapshot = edit.Snapshot; string inputtext = _CurrentSession.TextView.Caret.Position.BufferPosition.GetContainingLine().GetText(); var inputlist = Core.UsuallyCommon.SearchExtensions.GetStringSingleColumn(inputtext); var starttext = inputlist.LastOrDefault(); string lastChar = starttext.Substring(starttext.Length - 1, 1); starttext = starttext.Replace(lastChar, "").Trim(); int position = (starttext.LastIndexOf(" ") > 0) ? (starttext.Length + 1 - starttext.LastIndexOf(" ")) : (starttext.LastIndexOf("\t") > 0 ? (starttext.Length + 1 - starttext.LastIndexOf("\t")) : starttext.Length + 1); edit.Delete(_CurrentSession.TextView.Caret.Position.BufferPosition.Position - position, position); string text = _CurrentSession.SelectedCompletionSet.SelectionStatus.Completion.InsertionText; edit.Insert(_CurrentSession.TextView.Caret.Position.BufferPosition.Position - position, text); edit.Apply(); if (_CurrentSession != null) { _CurrentSession.Dismiss(); } return(true); } } catch (Exception ex) { DataServices.AddExexptionLogs(ex, "Complete 方法错误"); } return(true); }
internal void TrimTrailingWhitespace(ITextSnapshot snapshot, ITextEdit edit) { foreach (ITextSnapshotLine line in snapshot.Lines) { var text = line.GetText(); if (text != null) { int index = text.Length - 1; while (index >= 0 && char.IsWhiteSpace(text[index])) index--; if (index < text.Length - 1) edit.Delete(line.Start.Position + index + 1, text.Length - index - 1); } } }
private void ReplaceLines(ITextEdit edit, int startOldLine, int endOldLine, int startNewLine, int endNewLine) { int oldLineCount = endOldLine - startOldLine; int newLineCount = endNewLine - startNewLine; // replace one line at a time instead of all of the lines at once so that we preserve breakpoints int excessNewLineStart = startNewLine - startOldLine; for (int i = startOldLine; i < endOldLine && i < (endNewLine - startNewLine + startOldLine); i++) { edit.Replace( _snapshot.GetLineFromLineNumber(_startingReplacementLine + i).Extent, _newLines[startNewLine + i - startOldLine] ); excessNewLineStart = startNewLine + i - startOldLine + 1; } if (oldLineCount > newLineCount) { // we end up w/ less lines, we need to delete some text edit.Delete( Span.FromBounds( _snapshot.GetLineFromLineNumber(_startingReplacementLine + endOldLine - (oldLineCount - newLineCount)).Start.Position, _snapshot.GetLineFromLineNumber(_startingReplacementLine + endOldLine - 1).EndIncludingLineBreak.Position ) ); } else if (oldLineCount < newLineCount) { // we end up w/ more lines, we need to insert some text edit.Insert( _snapshot.GetLineFromLineNumber(_startingReplacementLine + endOldLine - 1).EndIncludingLineBreak, string.Join( _view.Options.GetNewLineCharacter(), _newLines, excessNewLineStart, endNewLine - excessNewLineStart ) + _view.Options.GetNewLineCharacter() ); } }
/// <summary> /// Undoes an insert operation. /// </summary> /// <param name="model">The model.</param> private void UndoInsert(DocumentModel doc, OpInsertMessage model, ITextEdit edit) { //doc.BlockEvent = true; var span = new Span(model.Index, model.Content.Length); edit.Delete(span); }
private static void DeleteCommentChars(ITextEdit edit, ITextSnapshotLine curLine) { var text = curLine.GetText(); for (int j = 0; j < text.Length; j++) { if (!Char.IsWhiteSpace(text[j])) { if (text.Substring(j, 2) == "//") { edit.Delete(curLine.Start.Position + j, 2); } break; } } }
/// <summary> /// Attempt to uncomment a span of text using any of a collection of line comment formats. /// </summary> /// <param name="span">The span of text to uncomment.</param> /// <param name="edit">The <see cref="ITextEdit"/> instance to use for applying changes.</param> /// <param name="formats">The line comment formats to use for attempting to uncomment the code.</param> /// <param name="result">Upon return, a <see cref="VirtualSnapshotSpan"/> containing the uncommented /// code.</param> /// <returns> /// <para><see langword="true"/> if one or more lines of the span of text were successfully uncommented using /// one of the specified line comment <paramref name="formats"/>.</para> /// <para>-or-</para> /// <para><see langword="false"/> if none of the lines in the span of text could be uncommented using any of the /// specified <paramref name="formats"/>.</para> /// </returns> /// <exception cref="ArgumentNullException"> /// <para>If <paramref name="edit"/> is <see langword="null"/>.</para> /// <para>-or-</para> /// <para>If <paramref name="formats"/> is <see langword="null"/>.</para> /// </exception> /// <exception cref="ArgumentException">If <paramref name="formats"/> contains any <see langword="null"/> /// values.</exception> protected virtual bool TryUncommentLines(VirtualSnapshotSpan span, ITextEdit edit, ReadOnlyCollection<LineCommentFormat> formats, out VirtualSnapshotSpan result) { Contract.Requires<ArgumentNullException>(edit != null, "edit"); Contract.Requires<ArgumentNullException>(formats != null, "formats"); Contract.Requires(Contract.ForAll(formats, i => i != null)); if (span.End.Position.GetContainingLine().LineNumber > span.Start.Position.GetContainingLine().LineNumber && span.End.Position == span.End.Position.GetContainingLine().Start) { VirtualSnapshotPoint start = span.Start; VirtualSnapshotPoint end = new VirtualSnapshotPoint(span.Snapshot.GetLineFromLineNumber(span.End.Position.GetContainingLine().LineNumber - 1).Start); if (end < start) start = end; span = new VirtualSnapshotSpan(start, end); } // Remove line comments bool containedComments = false; for (int line = span.Start.Position.GetContainingLine().LineNumber; line <= span.End.Position.GetContainingLine().LineNumber; line++) { int i = ScanToNonWhitespaceChar(span.Snapshot.GetLineFromLineNumber(line)); string text = span.Snapshot.GetLineFromLineNumber(line).GetText(); foreach (var format in formats) { int clen = format.StartText.Length; if ((text.Length > i + clen) && text.Substring(i, clen).Equals(format.StartText, StringComparison.Ordinal)) { // remove line comment. edit.Delete(span.Snapshot.GetLineFromLineNumber(line).Start.Position + i, clen); containedComments = true; break; } } } span = new VirtualSnapshotSpan(new SnapshotSpan(span.Start.Position.GetContainingLine().Start, span.End.Position.GetContainingLine().End)); result = span; return containedComments; }
private static void DeleteFirstCommentChar(ITextEdit edit, ITextSnapshotLine curLine) { var text = curLine.GetText(); for (int j = 0; j < text.Length; j++) { if (!Char.IsWhiteSpace(text[j])) { if (text[j] == '#') { edit.Delete(curLine.Start.Position + j, 1); } break; } } }
protected virtual SnapshotSpan UncommentLines(SnapshotSpan span, ITextEdit edit, ReadOnlyCollection<LineCommentFormat> formats) { Contract.Requires<ArgumentNullException>(edit != null, "edit"); Contract.Requires<ArgumentNullException>(formats != null, "formats"); Contract.Requires(Contract.ForAll(formats, i => i != null)); if (span.End.GetContainingLine().LineNumber > span.Start.GetContainingLine().LineNumber && span.End == span.End.GetContainingLine().Start) { SnapshotPoint start = span.Start; SnapshotPoint end = span.Snapshot.GetLineFromLineNumber(span.End.GetContainingLine().LineNumber - 1).Start; if (end < start) start = end; span = new SnapshotSpan(start, end); } // Remove line comments for (int line = span.Start.GetContainingLine().LineNumber; line <= span.End.GetContainingLine().LineNumber; line++) { int i = ScanToNonWhitespaceChar(span.Snapshot.GetLineFromLineNumber(line)); string text = span.Snapshot.GetLineFromLineNumber(line).GetText(); foreach (var format in formats) { int clen = format.StartText.Length; if ((text.Length > i + clen) && text.Substring(i, clen) == format.StartText) { // remove line comment. edit.Delete(span.Snapshot.GetLineFromLineNumber(line).Start.Position + i, clen); break; } } } span = new SnapshotSpan(span.Start.GetContainingLine().Start, span.End.GetContainingLine().End); return span; }
protected virtual bool TryUncommentBlock(SnapshotSpan span, ITextEdit edit, BlockCommentFormat format, out SnapshotSpan result) { Contract.Requires<ArgumentNullException>(edit != null, "edit"); Contract.Requires<ArgumentNullException>(format != null, "format"); string blockStart = format.StartText; string blockEnd = format.EndText; int startLen = span.Start.GetContainingLine().Length; int endLen = span.End.GetContainingLine().Length; TrimSpan(ref span); //sp. case no selection, try and uncomment the current line. if (span.IsEmpty) { span = new SnapshotSpan(span.Start.GetContainingLine().Start + ScanToNonWhitespaceChar(span.Start.GetContainingLine()), span.End.GetContainingLine().End); } // Check that comment start and end blocks are possible. if ((span.Start - span.Start.GetContainingLine().Start) + blockStart.Length <= startLen && (span.End - span.End.GetContainingLine().Start) - blockStart.Length >= 0) { string startText = span.Snapshot.GetText(span.Start.Position, blockStart.Length); if (startText == blockStart) { SnapshotSpan linespan = span; linespan = new SnapshotSpan(span.End - blockEnd.Length, span.End); string endText = linespan.GetText(); if (endText == blockEnd) { //yes, block comment selected; remove it edit.Delete(linespan); edit.Delete(span.Start.Position, blockStart.Length); result = span; return true; } } } result = default(SnapshotSpan); return false; }
/// <summary> /// Performs a delete in a document. /// </summary> /// <param name="model">The model.</param> private void Delete(DocumentModel doc, OpDeleteMessage model, ITextEdit edit) { //doc.BlockEvent = true; var len = model.End - model.Index; if (len > doc.View.TextBuffer.CurrentSnapshot.Length) { len = edit.Snapshot.Length; } var span = new Span(model.Index, len); edit.Delete(span); }