public string TextOfLine(int line, int endColumn, bool skipReadOnly) { string lineText = null; lock (textLines) { int startColumn = 0; if (skipReadOnly && (null != textStream.ReadOnlyMarker)) { TextSpan[] span = new TextSpan[1]; Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure( textStream.ReadOnlyMarker.GetCurrentSpan(span)); if (line < span[0].iEndLine) { return(null); } else if (line == span[0].iEndLine) { startColumn = span[0].iEndIndex; } } if (startColumn > endColumn) { return(null); } Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure( textLines.GetLineText(line, startColumn, line, endColumn, out lineText)); } return(lineText); }
/// <include file='doc\Colorizer.uex' path='docs/doc[@for="Colorizer.GetLineInfo"]/*' /> public virtual TokenInfo[] GetLineInfo(IVsTextLines buffer, int line, IVsTextColorState colorState) { int length; NativeMethods.ThrowOnFailure(buffer.GetLengthOfLine(line, out length)); if (length == 0) { return(null); } string text; NativeMethods.ThrowOnFailure(buffer.GetLineText(line, 0, line, length, out text)); int state; NativeMethods.ThrowOnFailure(colorState.GetColorStateAtStartOfLine(line, out state)); if (this.cachedLine == line && this.cachedLineText == text && this.cachedLineState == state && this.cachedLineInfo != null) { return(this.cachedLineInfo); } // recolorize the line, and cache the results this.cachedLineInfo = null; this.cachedLine = line; this.cachedLineText = text; this.cachedLineState = state; NativeMethods.ThrowOnFailure(GetColorInfo(text, length, state)); //now it should be in the cache return(this.cachedLineInfo); }
private void ExecuteQueryCommandExecute(object sender, EventArgs e) { try { var activeTextView = GetActiveTextView(); string queryToExecute; ErrorHandler.ThrowOnFailure(activeTextView.GetSelectedText(out queryToExecute)); if (string.IsNullOrEmpty(queryToExecute)) { IVsTextLines textLines = null; ErrorHandler.ThrowOnFailure(activeTextView.GetBuffer(out textLines)); int iLineCount; int iIndex; ErrorHandler.ThrowOnFailure(textLines.GetLastLineIndex(out iLineCount, out iIndex)); ErrorHandler.ThrowOnFailure(textLines.GetLineText(0, 0, iLineCount, iIndex, out queryToExecute)); } var bismInfoProvider = GetBismInfoProvider(); bismInfoProvider.SetUpdateEditorMargin(GetEditorMargin(activeTextView)); bismInfoProvider.ExecuteQuery(queryToExecute); } catch (Exception exc) { DisplayExceptionWindow(exc); } }
private static void addMarkersToDocument(IVsTextLines textLines) { int lineCount; textLines.GetLineCount(out lineCount); for (int i = 0; i < lineCount; ++i) { string text; int len; textLines.GetLengthOfLine(i, out len); textLines.GetLineText(i, 0, i, len, out text); string cmt = "//"; string issueKey = "PL-1357"; if (text == null || !text.Contains(cmt) || !text.Contains(issueKey)) { continue; } int cmtIdx = text.IndexOf(cmt); int idx = text.IndexOf(issueKey); if (idx < cmtIdx) { continue; } addMarker(textLines, i, idx, idx + issueKey.Length); } }
public static string GetAllText(this IVsTextLines lines) { lines.GetLastLineIndex(out var lastLine, out var lastIndex); lines.GetLineText(0, 0, lastLine, lastIndex, out var text); return(text); }
// used by intellisense mechanisms. public virtual TokenInfo[] GetLineInfo(int line, IVsTextColorState colorState) { int length; buffer.GetLengthOfLine(line, out length); string text; buffer.GetLineText(line, 0, line, length, out text); int state; colorState.GetColorStateAtStartOfLine(line, out state); if (this.cachedLine == line && this.cachedLineText == text && this.cachedLineState == state && this.cachedLineInfo != null) { return(this.cachedLineInfo); } // recolorize the line, and cache the results this.cachedLineInfo = null; this.cachedLine = line; this.cachedLineText = text; this.cachedLineState = state; GetColorInfo(text, length, state); //now it should be in the cache return(this.cachedLineInfo); }
public int PositionCaretForEditing(IVsTextLines pBuffer, [ComAliasName("Microsoft.VisualStudio.TextManager.Interop.TextSpan")] VsTextSpan[] ts) { // If the formatted location of the $end$ position (the inserted comment) was on an // empty line and indented, then we have already removed the white space on that line // and the navigation location will be at column 0 on a blank line. We must now // position the caret in virtual space. if (indentCaretOnCommit) { int lineLength; pBuffer.GetLengthOfLine(ts[0].iStartLine, out lineLength); string lineText; pBuffer.GetLineText(ts[0].iStartLine, 0, ts[0].iStartLine, lineLength, out lineText); if (lineText == string.Empty) { int endLinePosition; pBuffer.GetPositionOfLine(ts[0].iStartLine, out endLinePosition); TextView.TryMoveCaretToAndEnsureVisible(new VirtualSnapshotPoint(TextView.TextSnapshot.GetPoint(endLinePosition), indentDepth)); } } return(VSConstants.S_OK); }
private static string GetBufferContents(object docDataObj) { string text = null; IVsTextLines buffer = null; if (docDataObj is IVsTextLines) { buffer = (IVsTextLines)docDataObj; } else if (docDataObj is IVsTextBufferProvider) { IVsTextBufferProvider tp = (IVsTextBufferProvider)docDataObj; if (tp.GetTextBuffer(out buffer) != NativeMethods.S_OK) { buffer = null; } } if (buffer != null) { int endLine, endIndex; NativeMethods.ThrowOnFailure(buffer.GetLastLineIndex(out endLine, out endIndex)); NativeMethods.ThrowOnFailure(buffer.GetLineText(0, 0, endLine, endIndex, out text)); buffer = null; } return(text); }
internal static string Line(IVsTextLines vsTextLines, int index) { int length; vsTextLines.GetLengthOfLine(index, out length); string result; vsTextLines.GetLineText(index, 0, index, length, out result); return result; }
public List<TokenInfo> ParseLine(IVsTextLines textLines, int line, int maxTokens, out string lineOut) { int maxColumn; textLines.GetLengthOfLine(line, out maxColumn); textLines.GetLineText(line, 0, line, maxColumn, out lineOut); return Parse(lineOut, maxTokens); }
public string GetCharacterAtPosition(TextPoint positon) { IVsTextLines textLines = TextBufferAdapter; string charAtPos; textLines.GetLineText(positon.Line, positon.Index, positon.Line, positon.Index + 1, out charAtPos); return(charAtPos); }
public List <TokenInfo> ParseLine(IVsTextLines textLines, int line, int maxTokens, out string lineOut) { int maxColumn; textLines.GetLengthOfLine(line, out maxColumn); textLines.GetLineText(line, 0, line, maxColumn, out lineOut); return(Parse(lineOut, maxTokens)); }
/// <summary> /// Validates the breakpoint location. /// </summary> /// <param name="buffer">The buffer.</param> /// <param name="line">The line.</param> /// <param name="col">The col.</param> /// <param name="pCodeSpan">The TextSpans to update.</param> /// <returns></returns> public override int ValidateBreakpointLocation(IVsTextBuffer buffer, int line, int col, TextSpan[] pCodeSpan) { // Return noimpl by default int retval = VSConstants.E_NOTIMPL; if (pCodeSpan != null) { // Make sure the span is set to at least the current // position by default. pCodeSpan[0].iStartLine = line; pCodeSpan[0].iStartIndex = 0; pCodeSpan[0].iEndLine = line; pCodeSpan[0].iEndIndex = col; } if (buffer != null) { IVsTextLines textLines = buffer as IVsTextLines; if (textLines != null) { AsmHighlighterScanner scanner = AsmHighlighterScannerFactory.GetScanner(textLines); Scanner lexer = scanner.Lexer; int maxColumn; textLines.GetLengthOfLine(line, out maxColumn); string lineToParse; textLines.GetLineText(line, 0, line, maxColumn, out lineToParse); // Setup token scanner lexer.SetSource(lineToParse, 0); int state = 0; int start, end; AsmHighlighterToken token = (AsmHighlighterToken)lexer.GetNext(ref state, out start, out end); // Set Not a valid breakpoint retval = VSConstants.S_FALSE; switch (token) { case AsmHighlighterToken.INSTRUCTION: case AsmHighlighterToken.FPUPROCESSOR: case AsmHighlighterToken.SIMDPROCESSOR: if (pCodeSpan != null) { // Breakpoint covers the whole line (including comment) pCodeSpan[0].iEndIndex = maxColumn; } // Set valid breakpoint retval = VSConstants.S_OK; break; } } } return(retval); }
private static string GetAllText(IVsTextLines buffer) { if (buffer.GetLastLineIndex(out var endLine, out var endIndex) != VSConstants.S_OK || buffer.GetLineText(0, 0, endLine, endIndex, out var text) != VSConstants.S_OK) { text = null; } return(text); }
/// <summary> /// Gets the entire text from the buffer. /// </summary> private string GetAllText() { var span = new TextSpan(); textBuffer.GetLastLineIndex(out span.iEndLine, out span.iEndIndex); string text; textBuffer.GetLineText(span.iStartLine, span.iStartIndex, span.iEndLine, span.iEndIndex, out text); return(text); }
public static string GetText(this IVsTextLines buffer) { var entireSpan = buffer.CreateSpanForAllLines(); string text; buffer.GetLineText(entireSpan.iStartLine, entireSpan.iStartIndex, entireSpan.iEndLine, entireSpan.iEndIndex, out text); return(text); }
// »щет в исходном файле все блоки, обрамленные прагмой #line N / #line default private void SearchForCodeBlocks(IVsTextLines buffer) { ErrorHandler.ThrowOnFailure(buffer.LockBufferEx((uint)BufferLockFlags.BLF_READ)); try { int totalLines; ErrorHandler.ThrowOnFailure(buffer.GetLineCount(out totalLines)); var state = ParseState.WaitForBlockStart; var blockSpan = new TextSpanAndCookie(); for (int line = 0; line < totalLines; ++line) { int lineLen; ErrorHandler.ThrowOnFailure(buffer.GetLengthOfLine(line, out lineLen)); string lineText; ErrorHandler.ThrowOnFailure(buffer.GetLineText(line, 0, line, lineLen, out lineText)); if (state == ParseState.WaitForBlockStart) { var match = _linePragmaRegex.Match(lineText); if (match.Success) { blockSpan.ulHTMLCookie = uint.Parse(match.Groups[1].Value, NumberStyles.Integer, CultureInfo.InvariantCulture); blockSpan.CodeSpan = new TextSpan(); blockSpan.CodeSpan.iStartLine = line + 1; blockSpan.CodeSpan.iStartIndex = 0; state = ParseState.WaitForBlockEnd; } } else { if (lineText.Trim().StartsWith("#line default", StringComparison.InvariantCultureIgnoreCase)) { blockSpan.CodeSpan.iEndLine = line - 1; buffer.GetLengthOfLine(blockSpan.CodeSpan.iEndLine, out blockSpan.CodeSpan.iEndIndex); blocks.Add(blockSpan); blockSpan = new TextSpanAndCookie(); state = ParseState.WaitForBlockStart; } } } } finally { // Make sure that the buffer is always unlocked when we exit this function. buffer.UnlockBufferEx((uint)BufferLockFlags.BLF_READ); } }
public static string GetText(this IVsTextLines buffer) { int lastLine; int lastIndex; buffer.GetLastLineIndex(out lastLine, out lastIndex); string text; var ret = buffer.GetLineText(0, 0, lastLine, lastIndex, out text); return(text); }
internal static string GetTextFromVsTextLines(IVsTextLines vsTextLines) { int lines; int lastLineLength; VSErrorHandler.ThrowOnFailure(vsTextLines.GetLineCount(out lines)); VSErrorHandler.ThrowOnFailure(vsTextLines.GetLengthOfLine(lines - 1, out lastLineLength)); string text; VSErrorHandler.ThrowOnFailure(vsTextLines.GetLineText(0, 0, lines - 1, lastLineLength, out text)); return(text); }
static string GetText(IVsTextLines buffer) { // Create span for all lines: TextSpan entireSpan = new TextSpan(); buffer.GetLastLineIndex(out entireSpan.iEndLine, out entireSpan.iEndIndex); // Get text: string text; buffer.GetLineText(entireSpan.iStartLine, entireSpan.iStartIndex, entireSpan.iEndLine, entireSpan.iEndIndex, out text); return(text); }
public int PositionCaretForEditing(IVsTextLines pBuffer, [ComAliasName("Microsoft.VisualStudio.TextManager.Interop.TextSpan")] VsTextSpan[] ts) { // If the formatted location of the $end$ position (the inserted comment) was on an // empty line and indented, then we have already removed the white space on that line // and the navigation location will be at column 0 on a blank line. We must now // position the caret in virtual space. pBuffer.GetLengthOfLine(ts[0].iStartLine, out var lineLength); pBuffer.GetLineText(ts[0].iStartLine, 0, ts[0].iStartLine, lineLength, out var endLineText); pBuffer.GetPositionOfLine(ts[0].iStartLine, out var endLinePosition); PositionCaretForEditingInternal(endLineText, endLinePosition); return(VSConstants.S_OK); }
public override int Read() { if (Errored || CurrentLineIndex >= LineCount) { return(-1); } if (CurrentOffset >= LineSize) { CurrentLineIndex++; if (CurrentLineIndex >= LineCount) { return(-1); } if (TextLines.GetLengthOfLine(CurrentLineIndex, out LineSize) != VSConstants.S_OK) { Errored = true; return(-1); } } if (TextLines.GetLineText(CurrentLineIndex, CurrentOffset, CurrentLineIndex, CurrentOffset, out string c) == VSConstants.S_OK) { if (c.Length != 1) { Errored = true; return(-1); } CurrentOffset++; return((int)c[0]); } else { Errored = true; return(-1); } }
private string GetText() { int line, index; string buffer; if (textLines.GetLastLineIndex(out line, out index) != VSConstants.S_OK) { return(String.Empty); } if (textLines.GetLineText(0, 0, line, index, out buffer) != VSConstants.S_OK) { return(String.Empty); } return(buffer); }
public string GetText() { int totalLines; ErrorHandler.ThrowOnFailure(_textLines.GetLineCount(out totalLines)); if (totalLines > 0) { int lastLineLength; ErrorHandler.ThrowOnFailure(_textLines.GetLengthOfLine(totalLines - 1, out lastLineLength)); string text; ErrorHandler.ThrowOnFailure(_textLines.GetLineText(0, 0, totalLines - 1, lastLineLength, out text)); return(text); } return(""); }
/// <summary> /// Returns content of the given text buffer in a string /// </summary> public static string GetTextFrom(IVsTextLines textLines) { if (textLines == null) { throw new ArgumentNullException("textLines"); } int lastLine, lastLineIndex; int hr = textLines.GetLastLineIndex(out lastLine, out lastLineIndex); Marshal.ThrowExceptionForHR(hr); string textBuffer = ""; hr = textLines.GetLineText(0, 0, lastLine, lastLineIndex, out textBuffer); Marshal.ThrowExceptionForHR(hr); return(textBuffer); }
public string GetTextOfFileIfOpenInIde(string filePath) { IVsRunningDocumentTable rdt = _serviceProvider.GetService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable; IVsHierarchy hierarchy = null; uint itemid = 0; IntPtr docDataUnk = IntPtr.Zero; uint lockCookie = 0; int hr = rdt.FindAndLockDocument((uint)_VSRDTFLAGS.RDT_ReadLock, filePath, out hierarchy, out itemid, out docDataUnk, out lockCookie); try { if (hr == VSConstants.S_OK) { IVsTextLines textLines = Marshal.GetUniqueObjectForIUnknown(docDataUnk) as IVsTextLines; if (textLines != null) { string text = null; int endLine = 0; int endIndex = 0; hr = textLines.GetLastLineIndex(out endLine, out endIndex); Debug.Assert(hr == VSConstants.S_OK, "GetLastLineIndex did not return S_OK."); hr = textLines.GetLineText(0, 0, endLine, endIndex, out text); Debug.Assert(hr == VSConstants.S_OK, "GetLineText did not return S_OK."); return(text); } } return(null); } finally { if (lockCookie != 0) { rdt.UnlockDocument((uint)_VSRDTFLAGS.RDT_ReadLock, lockCookie); } } }
private void MarkTests(ConfiguredProject configuredCPPProject, IVsTextLines lines) { int lineNumber; lines.GetLineCount(out lineNumber); for (int i = 0; i < lineNumber; i++) { int linelength; lines.GetLengthOfLine(i, out linelength); if (linelength <= 0) { continue; } string codeLine; lines.GetLineText(i, 0, i, linelength, out codeLine); //TODO improve this so it deals with if the class declaration isn't the first thing on the line if (!codeLine.StartsWith("TEST") && !codeLine.StartsWith("GTEST")) { continue; } //extract the test group name and test name and combine them for the gtest filter string. int endOfBrackets = codeLine.IndexOf(')'); //TODO validate the next characters after the ) are a newline, curly bracket or a comment. int startOfBrackets = codeLine.IndexOf('(') + 1; //inside of brackets string name = codeLine.Substring(startOfBrackets, endOfBrackets - startOfBrackets); name = name.Replace(',', '.').Replace(" ", ""); IVsTextLineMarker[] marker = new IVsTextLineMarker[1]; int err = lines.CreateLineMarker(TestMarkerType.ID, i, 0, i, linelength, new GTestMarker(configuredCPPProject, name), marker); if (err != VSConstants.S_OK) { throw new Exception("Could not create marker"); } _markers.Add(marker); } }
private void SaveMeasuresAndCalculatedColumnsCommandExecute(object sender, EventArgs e) { try { var activeTextView = GetActiveTextView(); string viewText; IVsTextLines textLines = null; ErrorHandler.ThrowOnFailure(activeTextView.GetBuffer(out textLines)); int iLineCount; int iIndex; ErrorHandler.ThrowOnFailure(textLines.GetLastLineIndex(out iLineCount, out iIndex)); ErrorHandler.ThrowOnFailure(textLines.GetLineText(0, 0, iLineCount, iIndex, out viewText)); var bismInfoProvider = GetBismInfoProvider(); bismInfoProvider.SaveMeasuresAndCalcColumns(viewText); } catch (Exception exc) { DisplayExceptionWindow(exc); } }
/// <summary> /// performs lazy initialization to ensure our current code model is up-to-date. /// /// If we haven't yet created our CodeDom backing we'll create it for the 1st time. If we've /// created our backing, but some elements have been changed that we haven't yet reparsed /// then we'll reparse & merge any of the appropriate changes. /// </summary> private void Initialize() { if (ccu != null) { if (isDirty) { Reparse(); isDirty = false; } return; } IMergeDestination merger = MergeDestination; if (null == textBuffer) { using (FileStream fs = new FileStream(Name, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { if ((null == merger) && (null != parent)) { merger = new FileCodeMerger(parent); } ccu = provider.ParseMergable(new StreamReader(fs), merger); } } else { // Find the size of the buffer. int lastLine; int lastColumn; ErrorHandler.ThrowOnFailure(textBuffer.GetLastLineIndex(out lastLine, out lastColumn)); // Get the text in the buffer. string text; ErrorHandler.ThrowOnFailure(textBuffer.GetLineText(0, 0, lastLine, lastColumn, out text)); if (null == merger) { merger = new TextBufferMerger(textBuffer); } ccu = provider.ParseMergable(text, Name, merger); } }
private static void addMarkersToDocument(IVsTextLines textLines) { int lineCount; textLines.GetLineCount(out lineCount); for (int i = 0; i < lineCount; ++i) { string text; int len; textLines.GetLengthOfLine(i, out len); textLines.GetLineText(i, 0, i, len, out text); string cmt = "//"; string issueKey = "PL-1357"; if (text == null || !text.Contains(cmt) || !text.Contains(issueKey)) continue; int cmtIdx = text.IndexOf(cmt); int idx = text.IndexOf(issueKey); if (idx < cmtIdx) continue; addMarker(textLines, i, idx, idx + issueKey.Length); } }
/// <include file='doc\Colorizer.uex' path='docs/doc[@for="Colorizer.GetLineInfo"]/*' /> public virtual TokenInfo[] GetLineInfo(IVsTextLines buffer, int line, IVsTextColorState colorState) { int length; NativeMethods.ThrowOnFailure(buffer.GetLengthOfLine(line, out length)); if (length == 0) { return(null); } string text; NativeMethods.ThrowOnFailure(buffer.GetLineText(line, 0, line, length, out text)); int state; NativeMethods.ThrowOnFailure(colorState.GetColorStateAtStartOfLine(line, out state)); if (this.cachedLine == line && this.cachedLineText == text && this.cachedLineState == state && this.cachedLineInfo != null) { return(this.cachedLineInfo); } // recolorize the line, and cache the results this.cachedLineInfo = null; this.cachedLine = line; this.cachedLineText = text; this.cachedLineState = state; // GetColorInfo will update the cache. Note that here we don't use NativeMethods.ThrowOnFailure // because the return code is the current parsing state, not an HRESULT. GetColorInfo(text, length, state); //now it should be in the cache return(this.cachedLineInfo); }
public static List<EditSpan> ReformatCode(IVsTextLines pBuffer, TextSpan span, int tabSize) { string filePath = FilePathUtilities.GetFilePath(pBuffer); // Return dynamic scanner based on file extension List<EditSpan> changeList = new List<EditSpan>(); int nbLines; pBuffer.GetLineCount(out nbLines); string codeToFormat; int lastLine; int lastLineIndex; pBuffer.GetLastLineIndex(out lastLine, out lastLineIndex); pBuffer.GetLineText(0, 0, lastLine, lastLineIndex, out codeToFormat); NShaderScanner shaderScanner = NShaderScannerFactory.GetShaderScanner(filePath); Scanner lexer = shaderScanner.Lexer; lexer.SetSource(codeToFormat, 0); int spanStart; int spanEnd; pBuffer.GetPositionOfLineIndex(span.iStartLine, span.iStartIndex, out spanStart); pBuffer.GetPositionOfLineIndex(span.iEndLine, span.iEndIndex, out spanEnd); int state = 0; int start, end; ShaderToken token = (ShaderToken) lexer.GetNext(ref state, out start, out end); List<int> brackets = new List<int>(); List<int> delimiters = new List<int>(); // !EOL and !EOF int level = 0; int startCopy = 0; int levelParenthesis = 0; while (token != ShaderToken.EOF) { switch (token) { case ShaderToken.LEFT_PARENTHESIS: levelParenthesis++; break; case ShaderToken.RIGHT_PARENTHESIS: levelParenthesis--; if ( levelParenthesis < 0 ) { levelParenthesis = 0; } break; case ShaderToken.LEFT_BRACKET: level++; if (codeToFormat[start] == '{' && start >= spanStart && end <= spanEnd) { Match match = matchBraceStart.Match(codeToFormat, start); StringBuilder codeFormatted = new StringBuilder(); codeFormatted.Append("{\r\n"); int levelToIndentNext = level; if (match.Groups.Count == 2) { string matchStr = match.Groups[1].Value; levelToIndentNext--; } for (int i = 0; i < levelToIndentNext; i++) { for (int j = 0; j < tabSize; j++) { codeFormatted.Append(' '); } } if (match.Groups.Count == 2) { codeFormatted.Append("}\r\n"); } TextSpan editTextSpan = new TextSpan(); pBuffer.GetLineIndexOfPosition(start, out editTextSpan.iStartLine, out editTextSpan.iStartIndex); pBuffer.GetLineIndexOfPosition(startCopy + match.Index + match.Length, out editTextSpan.iEndLine, out editTextSpan.iEndIndex); changeList.Add(new EditSpan(editTextSpan, codeFormatted.ToString())); } break; case ShaderToken.RIGHT_BRACKET: level--; if (level < 0) { level = 0; } brackets.Add(start); break; case ShaderToken.DELIMITER: if (codeToFormat[start] == ';' && start >= spanStart && end <= spanEnd && levelParenthesis == 0) { Match match = matchEndOfStatement.Match(codeToFormat, start); StringBuilder codeFormatted = new StringBuilder(); codeFormatted.Append(";\r\n"); int levelToIndentNext = level; bool isBracketFound = (match.Groups.Count == 2 && match.Groups[1].Value == "}"); if (isBracketFound) { string matchStr = match.Groups[1].Value; levelToIndentNext--; } for (int i = 0; i < levelToIndentNext; i++) { for (int j = 0; j < tabSize; j++) { codeFormatted.Append(' '); } } if (isBracketFound) { codeFormatted.Append("}\r\n"); } TextSpan editTextSpan = new TextSpan(); pBuffer.GetLineIndexOfPosition(start, out editTextSpan.iStartLine, out editTextSpan.iStartIndex); pBuffer.GetLineIndexOfPosition(startCopy + match.Index + match.Length, out editTextSpan.iEndLine, out editTextSpan.iEndIndex); changeList.Add(new EditSpan(editTextSpan, codeFormatted.ToString())); } break; } token = (ShaderToken) lexer.GetNext(ref state, out start, out end); } return changeList; }
private void SearchForCodeBlocks(IVsTextLines buffer) { // We don't want any change in the buffer while we are parsing, // so we have to lock it. ErrorHandler.ThrowOnFailure(buffer.LockBufferEx((uint)BufferLockFlags.BLF_READ)); try { // Find the total number of lines in the buffer. int totalLines; ErrorHandler.ThrowOnFailure(buffer.GetLineCount(out totalLines)); // Set the initial values for the variables used during the parsing. SimpleParserState state = SimpleParserState.WaitForExternalSource; TextSpanAndCookie blockSpan = new TextSpanAndCookie(); // Parse all the lines in the buffer for (int line = 0; line < totalLines; ++line) { // Get the text of the current line. int lineLen; ErrorHandler.ThrowOnFailure(buffer.GetLengthOfLine(line, out lineLen)); if (0 == lineLen) { // The line is empty, no point in parsing it. continue; } string lineText; ErrorHandler.ThrowOnFailure(buffer.GetLineText(line, 0, line, lineLen, out lineText)); // Create the tokenizer. CompilerContext context = new CompilerContext("", new QuietCompilerSink()); using (SystemState systemState = new SystemState()) { tokenizer = new Tokenizer(lineText.ToCharArray(), true, systemState, context); Token token = null; string commentText; // Read all the token looking for the code blocks inside a Snippet Statements // nested in an External Source statement. Note that the standard FoxPro // parser does not return such statements and this is the reason for this // parser. while (!tokenizer.IsEndOfFile) { token = tokenizer.Next(); // This parser is strange in that it is only interested in comments: // an external code statement is in the form // #ExternalSource("PathOfTheOriginalFile", originalLineNumber) // ... (some code) ... // #End ExternalSource // and a snippet statement is // # Snippet Statement // ... (some code) ... // #End Snippet Statement // So if we want to find the text region inside a snippet nested // inside an external source, we are only interested in the comment tokens. if (TokenKind.Comment != token.Kind) { continue; } // The comments are line comments, so the comment's text is everything that // is after the beginning of the comment. commentText = CleanCommentStart(lineText.Substring(tokenizer.StartLocation.Column)); if (string.IsNullOrEmpty(commentText)) { continue; } switch (state) { case SimpleParserState.WaitForExternalSource: // This function returns a non zero value only if the comment text // is a valid external source statment. blockSpan.ulHTMLCookie = ParseExternalSource(commentText); if (0 != blockSpan.ulHTMLCookie) { // The CodeDOM provider is adding 1 to the line number, but in this // case the number is actualy the HTML editor's cookie, so we have to // restore the original value. blockSpan.ulHTMLCookie -= 1; state = SimpleParserState.WaitForSnippet; } break; case SimpleParserState.WaitForSnippet: // Check if this comment is the beginning of a snippet block. if (IsBeginSnippet(commentText)) { // This is the beginning of a snippet block, so // the actual code will start at the beginning of the // next line. blockSpan.CodeSpan.iStartLine = line + 1; // Set the default for the start index. blockSpan.CodeSpan.iStartIndex = 0; // Now we have to find the end of the snippet section // to complete the span of the code. state = SimpleParserState.WaitForEndSnippet; } else if (IsEndExternalSource(commentText)) { // This was and external block not related to the HTML editor. // Reset the text span and wait for the next external source. blockSpan = new TextSpanAndCookie(); state = SimpleParserState.WaitForExternalSource; } break; case SimpleParserState.WaitForEndSnippet: if (IsEndSnippet(commentText)) { // The code block ends at the end of the line before // this token. // Update the data about the code span and add the // block to the list of the blocks found. blockSpan.CodeSpan.iEndLine = line - 1; ErrorHandler.ThrowOnFailure( buffer.GetLengthOfLine(line - 1, out blockSpan.CodeSpan.iEndIndex)); blocks.Add(blockSpan); blockSpan = new TextSpanAndCookie(); state = SimpleParserState.WaitForEndExternal; } break; case SimpleParserState.WaitForEndExternal: // We expect only one snippet block inside the external source // section, so here we skip everything between the end of the first // snippet block and the end of the external code section. if (IsEndExternalSource(commentText)) { state = SimpleParserState.WaitForExternalSource; } break; } } } } } finally { // Make sure that the buffer is always unlocked when we exit this function. buffer.UnlockBufferEx((uint)BufferLockFlags.BLF_READ); } }
/// <summary> /// Gets the text. /// </summary> /// <param name="textLines">The text lines.</param> /// <returns></returns> private static string GetText(IVsTextLines textLines) { int line, index; string buffer; if (textLines.GetLastLineIndex(out line, out index) != VSConstants.S_OK) return String.Empty; if (textLines.GetLineText(0, 0, line, index, out buffer) != VSConstants.S_OK) return String.Empty; return buffer; }
/// <include file='doc\Colorizer.uex' path='docs/doc[@for="Colorizer.GetLineInfo"]/*' /> public virtual TokenInfo[] GetLineInfo(IVsTextLines buffer, int line, IVsTextColorState colorState) { int length; NativeMethods.ThrowOnFailure(buffer.GetLengthOfLine(line, out length)); if (length == 0) return null; string text; NativeMethods.ThrowOnFailure(buffer.GetLineText(line, 0, line, length, out text)); int state; NativeMethods.ThrowOnFailure(colorState.GetColorStateAtStartOfLine(line, out state)); if (this.cachedLine == line && this.cachedLineText == text && this.cachedLineState == state && this.cachedLineInfo != null) { return this.cachedLineInfo; } // recolorize the line, and cache the results this.cachedLineInfo = null; this.cachedLine = line; this.cachedLineText = text; this.cachedLineState = state; NativeMethods.ThrowOnFailure(GetColorInfo(text, length, state)); //now it should be in the cache return this.cachedLineInfo; }
private void SearchForCodeBlocks(IVsTextLines buffer) { // We don't want any change in the buffer while we are parsing, // so we have to lock it. ErrorHandler.ThrowOnFailure(buffer.LockBufferEx((uint)BufferLockFlags.BLF_READ)); try { // Find the total number of lines in the buffer. int totalLines; ErrorHandler.ThrowOnFailure(buffer.GetLineCount(out totalLines)); // Set the initial values for the variables used during the parsing. SimpleParserState state = SimpleParserState.WaitForExternalSource; TextSpanAndCookie blockSpan = new TextSpanAndCookie(); // Parse all the lines in the buffer for (int line = 0; line < totalLines; ++line) { // Get the text of the current line. int lineLen; ErrorHandler.ThrowOnFailure(buffer.GetLengthOfLine(line, out lineLen)); if (0 == lineLen) { // The line is empty, no point in parsing it. continue; } string lineText; ErrorHandler.ThrowOnFailure(buffer.GetLineText(line, 0, line, lineLen, out lineText)); // Create the tokenizer. CompilerContext context = new CompilerContext("", new QuietCompilerSink()); using (SystemState systemState = new SystemState()) { tokenizer = new Tokenizer(lineText.ToCharArray(), true, systemState, context); Token token = null; string commentText; // Read all the token looking for the code blocks inside a Snippet Statements // nested in an External Source statement. Note that the standard IronPython // parser does not return such statements and this is the reason for this // parser. while (!tokenizer.IsEndOfFile) { token = tokenizer.Next(); // This parser is strange in that it is only interested in comments: // an external code statement is in the form // #ExternalSource("PathOfTheOriginalFile", originalLineNumber) // ... (some code) ... // #End ExternalSource // and a snippet statement is // # Snippet Statement // ... (some code) ... // #End Snippet Statement // So if we want to find the text region inside a snippet nested // inside an external source, we are only interested in the comment tokens. if (TokenKind.Comment != token.Kind) { continue; } // The comments are line comments, so the comment's text is everything that // is after the beginning of the comment. commentText = CleanCommentStart(lineText.Substring(tokenizer.StartLocation.Column)); if (string.IsNullOrEmpty(commentText)) { continue; } switch (state) { case SimpleParserState.WaitForExternalSource: // This function returns a non zero value only if the comment text // is a valid external source statment. blockSpan.ulHTMLCookie = ParseExternalSource(commentText); if (0 != blockSpan.ulHTMLCookie) { // The CodeDOM provider is adding 1 to the line number, but in this // case the number is actualy the HTML editor's cookie, so we have to // restore the original value. blockSpan.ulHTMLCookie -= 1; state = SimpleParserState.WaitForSnippet; } break; case SimpleParserState.WaitForSnippet: // Check if this comment is the beginning of a snippet block. if (IsBeginSnippet(commentText)) { // This is the beginning of a snippet block, so // the actual code will start at the beginning of the // next line. blockSpan.CodeSpan.iStartLine = line + 1; // Set the default for the start index. blockSpan.CodeSpan.iStartIndex = 0; // Now we have to find the end of the snippet section // to complete the span of the code. state = SimpleParserState.WaitForEndSnippet; } else if (IsEndExternalSource(commentText)) { // This was and external block not related to the HTML editor. // Reset the text span and wait for the next external source. blockSpan = new TextSpanAndCookie(); state = SimpleParserState.WaitForExternalSource; } break; case SimpleParserState.WaitForEndSnippet: if (IsEndSnippet(commentText)) { // The code block ends at the end of the line before // this token. // Update the data about the code span and add the // block to the list of the blocks found. blockSpan.CodeSpan.iEndLine = line - 1; ErrorHandler.ThrowOnFailure( buffer.GetLengthOfLine(line - 1, out blockSpan.CodeSpan.iEndIndex)); blocks.Add(blockSpan); blockSpan = new TextSpanAndCookie(); state = SimpleParserState.WaitForEndExternal; } break; case SimpleParserState.WaitForEndExternal: // We expect only one snippet block inside the external source // section, so here we skip everything between the end of the first // snippet block and the end of the external code section. if (IsEndExternalSource(commentText)) { state = SimpleParserState.WaitForExternalSource; } break; } } } } } finally { // Make sure that the buffer is always unlocked when we exit this function. buffer.UnlockBufferEx((uint)BufferLockFlags.BLF_READ); } }
public int PositionCaretForEditing(IVsTextLines pBuffer, [ComAliasName("Microsoft.VisualStudio.TextManager.Interop.TextSpan")]VsTextSpan[] ts) { // If the formatted location of the $end$ position (the inserted comment) was on an // empty line and indented, then we have already removed the white space on that line // and the navigation location will be at column 0 on a blank line. We must now // position the caret in virtual space. if (indentCaretOnCommit) { int lineLength; pBuffer.GetLengthOfLine(ts[0].iStartLine, out lineLength); string lineText; pBuffer.GetLineText(ts[0].iStartLine, 0, ts[0].iStartLine, lineLength, out lineText); if (lineText == string.Empty) { int endLinePosition; pBuffer.GetPositionOfLine(ts[0].iStartLine, out endLinePosition); TextView.TryMoveCaretToAndEnsureVisible(new VirtualSnapshotPoint(TextView.TextSnapshot.GetPoint(endLinePosition), indentDepth)); } } return VSConstants.S_OK; }
public static List<EditSpan> ReformatCode(IVsTextLines pBuffer, TextSpan span, int tabSize) { string filePath = FilePathUtilities.GetFilePath(pBuffer); // Return dynamic scanner based on file extension List<EditSpan> changeList = new List<EditSpan>(); string codeToFormat; int endOfFirstLineIndex; // Get 1st line and parse custom define pBuffer.GetLengthOfLine(0, out endOfFirstLineIndex); pBuffer.GetLineText(0, 0, 0, endOfFirstLineIndex, out codeToFormat); Dictionary<string,string> defines = ParseDefineLine(codeToFormat); AsmHighlighterScanner scanner = AsmHighlighterScannerFactory.GetScanner(filePath); Scanner lexer = scanner.Lexer; // Iterate on each line of the selection to format for (int line = span.iStartLine; line <= span.iEndLine; line++) { int lineLength; pBuffer.GetLengthOfLine(line, out lineLength); pBuffer.GetLineText(line, 0, line, lineLength, out codeToFormat); string codeToAssemble = ConvertToFasm(lexer, codeToFormat, defines); lexer.SetSource(codeToFormat, 0); int state = 0; int start, end; bool instructionFound = false, commentFound = false; int commentStart = 0; AsmHighlighterToken token = (AsmHighlighterToken)lexer.GetNext(ref state, out start, out end); while (token != AsmHighlighterToken.EOF ) { switch (token) { case AsmHighlighterToken.INSTRUCTION: case AsmHighlighterToken.FPUPROCESSOR: case AsmHighlighterToken.SIMDPROCESSOR: instructionFound = true; break; case AsmHighlighterToken.COMMENT_LINE: if (!commentFound) { commentFound = true; commentStart = start; } break; } if ( instructionFound && commentFound ) { byte[] buffer = null; try { buffer = ManagedFasm.Assemble(codeToAssemble); } catch (Exception ex) { // Unable to parse instruction... skip } if (buffer != null) { } TextSpan editTextSpan = new TextSpan(); editTextSpan.iStartLine = line; editTextSpan.iEndLine = line; editTextSpan.iStartIndex = commentStart; editTextSpan.iEndIndex = commentStart+1; if ((codeToFormat.Length - commentStart) > 2 && codeToFormat.Substring(commentStart, 2) == ";#") { editTextSpan.iEndIndex = editTextSpan.iEndIndex + 2; } string text = ";#" + ((buffer == null) ? "?" : string.Format("{0:X}",buffer.Length)); changeList.Add(new EditSpan(editTextSpan, text)); break; } token = (AsmHighlighterToken)lexer.GetNext(ref state, out start, out end); } } return changeList; }
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 CollapseToDefinitions(IVsTextLines textLines, IVsOutliningSession session){ if (textLines == null || session == null) return (int)HResult.E_INVALIDARG; int lastLine; int lastIdx; string text; textLines.GetLineCount(out lastLine ); textLines.GetLengthOfLine(--lastLine, out lastIdx); textLines.GetLineText(0, 0, lastLine, lastIdx, out text); NewOutlineRegion[] outlineRegions = this.GetCollapsibleRegions(text, VsShell.GetFilePath(textLines)); if (outlineRegions != null && outlineRegions.Length > 0) session.AddOutlineRegions((uint)ADD_OUTLINE_REGION_FLAGS.AOR_PRESERVE_EXISTING, outlineRegions.Length, outlineRegions); return 0; }
public int PositionCaretForEditing(IVsTextLines pBuffer, [ComAliasName("Microsoft.VisualStudio.TextManager.Interop.TextSpan")]VsTextSpan[] ts) { // If the formatted location of the $end$ position (the inserted comment) was on an // empty line and indented, then we have already removed the white space on that line // and the navigation location will be at column 0 on a blank line. We must now // position the caret in virtual space. int lineLength; pBuffer.GetLengthOfLine(ts[0].iStartLine, out lineLength); string endLineText; pBuffer.GetLineText(ts[0].iStartLine, 0, ts[0].iStartLine, lineLength, out endLineText); int endLinePosition; pBuffer.GetPositionOfLine(ts[0].iStartLine, out endLinePosition); PositionCaretForEditingInternal(endLineText, endLinePosition); return VSConstants.S_OK; }
internal static string GetTextFromVsTextLines(IVsTextLines vsTextLines) { int lines; int lastLineLength; VSErrorHandler.ThrowOnFailure(vsTextLines.GetLineCount(out lines)); VSErrorHandler.ThrowOnFailure(vsTextLines.GetLengthOfLine(lines - 1, out lastLineLength)); string text; VSErrorHandler.ThrowOnFailure(vsTextLines.GetLineText(0, 0, lines - 1, lastLineLength, out text)); return text; }
private static string GetAllText(IVsTextLines buffer) { int endLine, endIndex; string text; if (buffer.GetLastLineIndex(out endLine, out endIndex) != VSConstants.S_OK || buffer.GetLineText(0, 0, endLine, endIndex, out text) != VSConstants.S_OK) { text = null; } return text; }
public bool GotoNextToken(DelphiToken aToken, out int aStartLine, out int aStartIndex, out int aEndLine, out int aEndIndex) { int lCurrLine, lCurrIndex, lLineLen, lState = 0; int lLastState = 0; string lLineText = ""; TokenInfo lTokenInfo = new TokenInfo(); lCurrLine = StartLine; lCurrIndex = StartIndex; int lAddChrs = StartIndex; aStartIndex = 0; aStartLine = 0; aEndIndex = 0; aEndLine = 0; lLineLen = 0; if (aToken == DelphiToken.None) { return(false); } System.Diagnostics.Debug.Assert(aToken != EndToken, "End Token and aToken parameter match in GotoNextToken"); bool result = false; while (lCurrLine <= EndLine) { if (lCurrLine == EndLine - 2) { result = false; } if (lLineText == "") { // TODO: Read and check out whats the diff between NativeMethods.ThrowOnFailure and ErrorHandler.ThrowOnFailure? ErrorHandler.ThrowOnFailure(FTextLines.GetLengthOfLine(lCurrLine, out lLineLen)); ErrorHandler.ThrowOnFailure(FTextLines.GetLineText(lCurrLine, 0, lCurrLine, lLineLen, out lLineText)); FScanner.SetSource(lLineText, lCurrIndex); } lTokenInfo.Type = TokenType.Unknown; lTokenInfo.EndIndex = lLineLen - 1; try { FScanner.ScanTokenAndProvideInfoAboutIt(lTokenInfo, ref lState); } catch { /* Do we care? */ } // lTokenInfo.StartIndex will = 0 for the first token even if // in line "FScanner.SetSource(lLineText, lCurrIndex)" lCurrIndex > 0 // so we will need to add some values to make the values correct. if (lAddChrs > 0) { lTokenInfo.EndIndex += lAddChrs; lTokenInfo.StartIndex += lAddChrs; } // if we have reached your end token then exit if (lTokenInfo.Token == (int)EndToken && lState == DelphiScanner.YYINITIAL) { break; } aEndIndex = lTokenInfo.EndIndex; // set end point aEndLine = lCurrLine; // set end line lCurrIndex = lTokenInfo.StartIndex; // Set new point if ((lState == DelphiScanner.YYINITIAL) && (lTokenInfo.Token == (int)aToken) && (lState != lLastState)) { // no worries we found have the StartIndex and StartLine already result = true; } else if ((lState == DelphiScanner.YYINITIAL) || (lState != lLastState)) { aStartLine = lCurrLine; aStartIndex = lCurrIndex; lLastState = lState; result = (lTokenInfo.Token == (int)aToken); } if (result) { break; } lCurrIndex = lTokenInfo.EndIndex + 1; if (lCurrIndex >= lLineLen) { lLineText = ""; lCurrIndex = 0; lAddChrs = 0; lCurrLine++; } } if (result) { StartIndex = lTokenInfo.EndIndex + 1; StartLine = aEndLine; // aEndIndex is correct but the GetLineText method does not read the text out correctly. ErrorHandler.ThrowOnFailure(FTextLines.GetLineText(aStartLine, aStartIndex, aEndLine, aEndIndex + 1, out FTokenValue)); } return(result); }
/// <include file='doc\Colorizer.uex' path='docs/doc[@for="Colorizer.GetLineInfo"]/*' /> public virtual TokenInfo[] GetLineInfo(IVsTextLines buffer, int line, IVsTextColorState colorState) { int length; NativeMethods.ThrowOnFailure(buffer.GetLengthOfLine(line, out length)); if (length == 0) return null; string text; NativeMethods.ThrowOnFailure(buffer.GetLineText(line, 0, line, length, out text)); int state; NativeMethods.ThrowOnFailure(colorState.GetColorStateAtStartOfLine(line, out state)); if (this.cachedLine == line && this.cachedLineText == text && this.cachedLineState == state && this.cachedLineInfo != null) { return this.cachedLineInfo; } // recolorize the line, and cache the results this.cachedLineInfo = null; this.cachedLine = line; this.cachedLineText = text; this.cachedLineState = state; // GetColorInfo will update the cache. Note that here we don't use NativeMethods.ThrowOnFailure // because the return code is the current parsing state, not an HRESULT. GetColorInfo(text, length, state); //now it should be in the cache return this.cachedLineInfo; }