/// <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) { // 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; } // There is something to write on the console, so replace the current text in the // input line with the content of the history. lock (textLines) { // The input line starts by definition at the end of the text marker // used to mark the read only region. TextSpan[] span = new TextSpan[1]; Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure( textStream.ReadOnlyMarker.GetCurrentSpan(span)); // Get the last position in the buffer. int lastLine; int lastIndex; Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure( textLines.GetLastLineIndex(out lastLine, out lastIndex)); // Now replace all this text with the text returned by the history. System.Runtime.InteropServices.GCHandle textHandle = GCHandle.Alloc(historyEntry, GCHandleType.Pinned); try { Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure( textLines.ReplaceLines(span[0].iEndLine, span[0].iEndIndex, lastLine, lastIndex, textHandle.AddrOfPinnedObject(), historyEntry.Length, null)); } finally { // Free the memory inside the finally block to avoid memory leaks. textHandle.Free(); } } }
public void InsertRange(int start, IList <string> lines) { // If the set of lines is empty we can exit now if ((null == lines) || (lines.Count == 0)) { hasMerged = true; return; } if (start < 0) { throw new ArgumentOutOfRangeException("start"); } int insertLine = start; int insertIndex = 0; // Verify that the insertion point is inside the buffer. int totalLines = LineCount; if (insertLine > totalLines) { insertLine = totalLines; } // Create the text to add to the buffer. StringBuilder builder = new StringBuilder(); if ((insertLine == totalLines) && (totalLines > 0)) { insertLine = totalLines - 1; ErrorHandler.ThrowOnFailure(textBuffer.GetLengthOfLine(insertLine, out insertIndex)); builder.AppendLine(); } foreach (string line in lines) { builder.AppendLine(line); } // Lock the buffer before changing its content. ErrorHandler.ThrowOnFailure(textBuffer.LockBuffer()); try { // Get the text to insert and pin it so that we can pass it as pointer // to the buffer's functions. string text = builder.ToString(); GCHandle handle = GCHandle.Alloc(text, GCHandleType.Pinned); try { TextSpan[] span = new TextSpan[1]; ErrorHandler.ThrowOnFailure(textBuffer.ReplaceLines(insertLine, insertIndex, insertLine, insertIndex, handle.AddrOfPinnedObject(), text.Length, span)); hasMerged = true; } finally { // Free the memory. handle.Free(); } } finally { // Make sure that the buffer is unlocked also in case of exception. textBuffer.UnlockBuffer(); } }
private void SetText(string text) { try { FrameXmlDesignerLoader.ValidateOnWrite(text); } catch (Exception ex) { // TODO: show error in the Error List Trace.WriteLine(ex); } int endLine, endCol; textLines.GetLastLineIndex(out endLine, out endCol); int len = (text == null) ? 0 : text.Length; //fix location of the string IntPtr pText = Marshal.StringToCoTaskMemAuto(text); try { textLines.ReplaceLines(0, 0, endLine, endCol, pText, len, null); } finally { Marshal.FreeCoTaskMem(pText); } }
private static void CopyFileToBuffer(string sourceFilename, IVsTextLines buffer) { ArgumentValidation.CheckForEmptyString(sourceFilename, "sourceFileName"); ArgumentValidation.CheckForNullReference(buffer, "buffer"); var spanDst = GetBufferSpan(buffer); var pContent = IntPtr.Zero; try { var content = RdtManager.Instance.ReadFromFile(sourceFilename); pContent = Marshal.StringToHGlobalAuto(content); buffer.ReplaceLines( spanDst.iStartLine, spanDst.iStartIndex, spanDst.iEndLine, spanDst.iEndIndex, pContent, content.Length, new[] { new TextSpan() }); } finally { if (pContent != IntPtr.Zero) { Marshal.FreeHGlobal(pContent); } } }
public bool DocumentInsertLine(int line, string text) { IVsTextLines VsTxtlines = TextLines; if (VsTxtlines == null || line < 1) { return(false); } bool Result = false; text += "\r\n"; TextSpan[] span = new TextSpan[1]; GCHandle handle = GCHandle.Alloc(text, GCHandleType.Pinned); try { line -= 1; Int32 result = VsTxtlines.ReplaceLines(line, 0, line, 0, handle.AddrOfPinnedObject(), text.Length, span); if (result == VSConstants.S_OK) { Result = true; } } finally { handle.Free(); } return(Result); }
/// <summary> /// Replaces given IVsTextLines with given MemoryStream content /// </summary> /// <param name="stream"></param> /// <param name="textLines"></param> /// <param name="removeFromUndoStack">True if new undo units (created by this operation) should be removed</param> public static void SaveStreamToBuffer(MemoryStream stream, IVsTextLines textLines, bool removeFromUndoStack) { if (stream == null) { throw new ArgumentNullException("stream"); } if (textLines == null) { throw new ArgumentNullException("textLines"); } byte[] buffer = stream.ToArray(); string text = Encoding.UTF8.GetString(buffer, 3, buffer.Length - 3); // get ResX file text int lastLine, lastLineIndex; int hr = textLines.GetLastLineIndex(out lastLine, out lastLineIndex); Marshal.ThrowExceptionForHR(hr); TextSpan[] spans = null; // replace current buffer text with new text hr = textLines.ReplaceLines(0, 0, lastLine, lastLineIndex, Marshal.StringToBSTR(text), text.Length, spans); Marshal.ThrowExceptionForHR(hr); if (removeFromUndoStack) { IOleUndoManager manager; // previous operation created undo unit - remove it hr = textLines.GetUndoManager(out manager); Marshal.ThrowExceptionForHR(hr); manager.RemoveTopFromUndoStack(1); } }
/// <summary> /// Flushes the pending data. /// </summary> public override void Flush() { // If there is no data in the buffer, then there is nothing to do. if (0 == usedBuffer) { // Make sure that the read-only region is correct and exit. ExtendReadOnlyRegion(); return; } string text = null; // We have to use a StreamReader in order to work around problems with the // encoding of the data sent in, but in order to build the reader we need // a memory stream to read the data in the buffer. using (MemoryStream s = new MemoryStream(byteBuffer, 0, usedBuffer)) { // Now we can build the reader from the memory stream. using (StreamReader reader = new StreamReader(s)) { // At the end we can get the text. text = reader.ReadToEnd(); } } // Now the buffer is empty. usedBuffer = 0; // The text is always added at the end of the buffer. int lastLine; int lastColumn; Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure( textLines.GetLastLineIndex(out lastLine, out lastColumn)); // Lock the buffer before changing its content. Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure( textLines.LockBuffer()); try { GCHandle handle = GCHandle.Alloc(text, GCHandleType.Pinned); try { TextSpan[] span = new TextSpan[1]; Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure( textLines.ReplaceLines(lastLine, lastColumn, lastLine, lastColumn, handle.AddrOfPinnedObject(), text.Length, span)); } finally { handle.Free(); } // Extend the read-only region of the buffer to include this text. ExtendReadOnlyRegion(); } finally { Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure( textLines.UnlockBuffer()); } }
/// <summary> /// Marks given result item with no-localization comment /// </summary> /// <returns>Length of no-localization comment (language specific)</returns> private int MarkAsNoLoc(IVsTextLines textLines, CodeStringResultItem resultItem) { int hr = textLines.ReplaceLines(resultItem.ReplaceSpan.iStartLine, resultItem.ReplaceSpan.iStartIndex, resultItem.ReplaceSpan.iStartLine, resultItem.ReplaceSpan.iStartIndex, Marshal.StringToBSTR(resultItem.NoLocalizationComment), resultItem.NoLocalizationComment.Length, new TextSpan[1]); Marshal.ThrowExceptionForHR(hr); return(resultItem.NoLocalizationComment.Length); }
/// <summary> /// Perform actual replacement of the string literal /// </summary> /// <returns>Length of the reference</returns> private int MoveToResource(IVsTextLines textLines, CodeStringResultItem resultItem, ReferenceString referenceText) { string newText = resultItem.GetReferenceText(referenceText); int hr = textLines.ReplaceLines(resultItem.ReplaceSpan.iStartLine, resultItem.ReplaceSpan.iStartIndex, resultItem.ReplaceSpan.iEndLine, resultItem.ReplaceSpan.iEndIndex, Marshal.StringToBSTR(newText), newText.Length, new TextSpan[] { resultItem.ReplaceSpan }); Marshal.ThrowExceptionForHR(hr); return(newText.Length); }
/// <summary> /// Overwrite the text in the buffer with the given text. /// </summary> private void SetText(string text) { int endLine, endCol; textBuffer.GetLastLineIndex(out endLine, out endCol); var len = (text == null) ? 0 : text.Length; //fix location of the string var pText = Marshal.StringToCoTaskMemAuto(text); try { textBuffer.ReplaceLines(0, 0, endLine, endCol, pText, len, null); } finally { Marshal.FreeCoTaskMem(pText); } }
private void Replace(string value) { int endLine, endCol; IVsTextLines lines = (IVsTextLines)textBuffer; lines.GetLastLineIndex(out endLine, out endCol); IntPtr pText = Marshal.StringToCoTaskMemAuto(value); try { lines.ReplaceLines(0, 0, endLine, endCol, pText, value.Length, null); } finally { Marshal.FreeCoTaskMem(pText); } }
internal static void ApplyChangesToOneFile( FileChange file, IVsTextLines textLines, bool createMarker, ChangeProposal changeToHighlight) { ArgumentValidation.CheckForNullReference(file, "file"); ArgumentValidation.CheckForNullReference(textLines, "textLines"); // Here we only work on text based ChangeProposal // Sort all ChangeProposal in one file by the offset. // After apply any change, the offset of next ChangeProposal will change. // We need to sort all the changes first, so it will be easy to recalculate // the new offset for next change. var sortedChanges = SortChanges(file); // Changes may cause the total line number of this file to be changed. // This variable is used to keep this line changes. var totalLineOffset = 0; // In one line, changes may cause column number of that line to be changed. // This variable is used to keep this column changes. var totalColumnOffset = 0; var pContent = IntPtr.Zero; // Store result TextSpan info var resultSpan = new[] { new TextSpan() }; foreach (var sortedChange in sortedChanges) { var change = sortedChange.Value; // If user choose to apply this change if (change.Included) { try { // If current change's StartLine is different from Last change's EndLine // reset the columnOffset if (resultSpan[0].iEndLine != change.StartLine + totalLineOffset) { totalColumnOffset = 0; } pContent = Marshal.StringToHGlobalAuto(change.NewValue); // Calculate the current change's offset by applying lineOffset // and columnOffset caused by previous changes var startLine = change.StartLine + totalLineOffset; var startColumn = change.StartColumn + totalColumnOffset; var endLine = change.EndLine + totalLineOffset; // Only apply columnOffset if current change's startLine is same as endLine var endColumn = change.EndColumn + (startLine == endLine ? totalColumnOffset : 0); textLines.ReplaceLines( startLine, startColumn, endLine, endColumn, pContent, change.NewValue.Length, resultSpan); // Add the line offset caused by this change to total lineOffset; var currentLineOffset = resultSpan[0].iEndLine - endLine; totalLineOffset += currentLineOffset; // Calculate the ColumnOffset after this change totalColumnOffset = resultSpan[0].iEndIndex - change.EndColumn; } finally { if (pContent != IntPtr.Zero) { Marshal.FreeHGlobal(pContent); } } } // Create Marker for this change's textspan. // If this change is the change to be highlighted, highlight it. if (createMarker) { var textChangeToHighlight = changeToHighlight as TextChangeProposal; var highlight = ((textChangeToHighlight != null) && (change.StartLine == textChangeToHighlight.StartLine) && (change.StartColumn == textChangeToHighlight.StartColumn)); CreateMarker(textLines, resultSpan[0], highlight); } } }
private static void UpdateServiceDefinition(IVsTextLines lines, string roleType, string projectName) { if (lines == null) { throw new ArgumentException("lines"); } int lastLine, lastIndex; string text; ErrorHandler.ThrowOnFailure(lines.GetLastLineIndex(out lastLine, out lastIndex)); ErrorHandler.ThrowOnFailure(lines.GetLineText(0, 0, lastLine, lastIndex, out text)); var doc = new XmlDocument(); doc.LoadXml(text); UpdateServiceDefinition(doc, roleType, projectName); var encoding = Encoding.UTF8; var userData = lines as IVsUserData; if (userData != null) { var guid = VSConstants.VsTextBufferUserDataGuid.VsBufferEncodingVSTFF_guid; object data; int cp; if (ErrorHandler.Succeeded(userData.GetData(ref guid, out data)) && (cp = (data as int? ?? (int)(data as uint? ?? 0)) & (int)__VSTFF.VSTFF_CPMASK) != 0) { try { encoding = Encoding.GetEncoding(cp); } catch (NotSupportedException) { } catch (ArgumentException) { } } } var sw = new StringWriterWithEncoding(encoding); doc.Save(XmlWriter.Create( sw, new XmlWriterSettings { Indent = true, IndentChars = " ", NewLineHandling = NewLineHandling.Entitize, Encoding = encoding } )); var sb = sw.GetStringBuilder(); var len = sb.Length; var pStr = Marshal.StringToCoTaskMemUni(sb.ToString()); try { ErrorHandler.ThrowOnFailure(lines.ReplaceLines(0, 0, lastLine, lastIndex, pStr, len, new TextSpan[1])); } finally { Marshal.FreeCoTaskMem(pStr); } }
public int ReplaceLines( int iStartLine, int iStartIndex, int iEndLine, int iEndIndex, IntPtr pszText, int iNewLen, TextSpan[] pChangedSpan) { return(_textBuffer.ReplaceLines(iStartLine, iStartIndex, iEndLine, iEndIndex, pszText, iNewLen, pChangedSpan)); }
public static void ReplaceAllText(this IVsTextLines lines, string newInput) { lines.GetLastLineIndex(out var lastLine, out var lastIndex); TextSpan[] _ = new TextSpan[0]; lines.ReplaceLines(0, 0, lastLine, lastIndex, Marshal.StringToHGlobalUni(newInput), newInput.Length, _); }