Example #1
0
        /// <summary>
        ///     Get entire TextLines buffer as a TextSpan
        /// </summary>
        /// <param name="pBuffer"></param>
        /// <returns></returns>
        private static TextSpan GetBufferSpan(IVsTextLines textBuffer)
        {
            ArgumentValidation.CheckForNullReference(textBuffer, "textBuffer");

            var lineCount = 0;
            var charCount = 0;

            // Get line count for the whole buffer.
            var result = textBuffer.GetLineCount(out lineCount);

            if (result == VSConstants.S_OK &&
                lineCount > 0)
            {
                // Get char count for last line.
                result = textBuffer.GetLengthOfLine(lineCount - 1, out charCount);
                if (result != VSConstants.S_OK)
                {
                    charCount = 0;
                }
            }
            else
            {
                lineCount = 0;
            }

            // Create a TextSpan from begin to end of the text buffer.
            var span = new TextSpan();

            span.iStartLine  = 0;
            span.iStartIndex = 0;
            span.iEndLine    = lineCount - 1 > 0 ? lineCount - 1 : 0;
            span.iEndIndex   = charCount > 0 ? charCount : 0;
            return(span);
        }
Example #2
0
        private void DoFormatting(EditArray mgr, TextSpan span)
        {
            // Make sure there is one space after every comma unless followed
            // by a tab or comma is at end of line.
            IVsTextLines pBuffer = this.GetTextLines();

            if (pBuffer != null)
            {
                int numlines;
                int endCol;
                pBuffer.GetLineCount(out numlines);
                settings_pkg.set_reformat_types(false);
                pBuffer.GetLengthOfLine(span.iEndLine, out endCol);
                string s = this.GetText(span.iStartLine, 0, span.iEndLine, endCol);
                string t = reformat_pkg_pkg.reformat__2(s, span.iStartLine, span.iEndLine);

                TextSpan editTextSpan = new TextSpan();

                editTextSpan.iStartLine  = span.iStartLine;
                editTextSpan.iEndLine    = span.iEndLine;
                editTextSpan.iStartIndex = 0;
                editTextSpan.iEndIndex   = endCol;

                // Add edit operation
                mgr.Add(new EditSpan(editTextSpan, t));
                // Apply all edits
                mgr.ApplyEdits();
            }
        }
Example #3
0
        /// <devdoc>Pins the text span to valid line bounds returned from IVsTextLines.</devdoc>
        internal static void Normalize(ref TextSpan span, IVsTextLines textLines)
        {
            MakePositive(ref span);
            if (textLines == null)
            {
                return;
            }
            //adjust max. lines
            int lineCount;

            if (NativeMethods.Failed(textLines.GetLineCount(out lineCount)))
            {
                return;
            }
            span.iEndLine = Math.Min(span.iEndLine, lineCount - 1);
            //make sure the start is still before the end
            if (!IsPositive(span))
            {
                span.iStartLine  = span.iEndLine;
                span.iStartIndex = span.iEndIndex;
            }
            //adjust for line length
            int lineLength;

            if (NativeMethods.Failed(textLines.GetLengthOfLine(span.iStartLine, out lineLength)))
            {
                return;
            }
            span.iStartIndex = Math.Min(span.iStartIndex, lineLength);
            if (NativeMethods.Failed(textLines.GetLengthOfLine(span.iEndLine, out lineLength)))
            {
                return;
            }
            span.iEndIndex = Math.Min(span.iEndIndex, lineLength);
        }
        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 TUnitScanner(IVsTextLines aTextLines)
 {
     System.Diagnostics.Debug.Assert(aTextLines != null, "aTextLines param is null in TUnitScanner");
     FTextLines = aTextLines;
     FStartLine = 0;
     ErrorHandler.ThrowOnFailure(FTextLines.GetLineCount(out FEndLine));
     FEndLine--;
     ErrorHandler.ThrowOnFailure(FTextLines.GetLengthOfLine(FEndLine, out FEndIndex));
 }
Example #6
0
		// »щет в исходном файле все блоки, обрамленные прагмой #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);
			}
		}
Example #7
0
        // »щет в исходном файле все блоки, обрамленные прагмой #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);
            }
        }
 internal IVsTextLinesReader(IVsTextLines textLines)
 {
     TextLines = textLines;
     Errored   = false;
     if (TextLines.GetLineCount(out LineCount) != VSConstants.S_OK)
     {
         Errored = true;
     }
     CurrentLineIndex = -1;
     CurrentOffset    = 0;
     LineSize         = -1;
 }
Example #9
0
        private List <String> GetEntireBufferContent(IVsTextLines lines)
        {
            var list      = new List <String>();
            int lineCount = 0;

            lines.GetLineCount(out lineCount);
            for (int i = 0; i < lineCount; i++)
            {
                list.Add(GetLineContent(lines, i));
            }
            return(list);
        }
Example #10
0
        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);
        }
Example #11
0
        /// <summary>
        /// Return true if the user is currently on the input line.
        /// Here we assume that the input line is always the last one.
        /// </summary>
        private bool IsCurrentLineInputLine()
        {
            // Get the total number of lines in the buffer.
            int totalLines;

            Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(
                textLines.GetLineCount(out totalLines));
            // Get the current position of the cursor.
            int currentLine;
            int currentColumn;

            Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(
                textView.GetCaretPos(out currentLine, out currentColumn));
            // Verify whether the current line (that is 0-based) is the last one.
            return(currentLine == totalLines - 1);
        }
Example #12
0
        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("");
        }
Example #13
0
        public static void TextSpanNormalize(ref TextSpan span, IVsTextLines textLines)
        {
            TextSpanMakePositive(ref span);
            if (textLines == null)
            {
                return;
            }

            //adjust max. lines
            int lineCount;

            try {
                textLines.GetLineCount(out lineCount);
            } catch (Exception) {
                return;
            }
            span.iEndLine = Math.Min(span.iEndLine, lineCount - 1);

            //make sure the start is still before the end
            if (!TextSpanPositive(span))
            {
                span.iStartLine  = span.iEndLine;
                span.iStartIndex = span.iEndIndex;
            }

            //adjust for line length
            int lineLength;

            try {
                textLines.GetLengthOfLine(span.iStartLine, out lineLength);
            } catch (Exception) {
                return;
            }
            span.iStartIndex = Math.Min(span.iStartIndex, lineLength);

            try {
                textLines.GetLengthOfLine(span.iEndLine, out lineLength);
            } catch (Exception) {
                return;
            }
            span.iEndIndex = Math.Min(span.iEndIndex, lineLength);
        }
Example #14
0
        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 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);
            }
        }
Example #16
0
 private List<String> GetEntireBufferContent(IVsTextLines lines)
 {
     var list = new List<String>();
     int lineCount = 0;
     lines.GetLineCount(out lineCount);
     for (int i = 0; i < lineCount; i++)
     {
         list.Add(GetLineContent(lines, i));
     }
     return list;
 }
        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;
        }
Example #18
0
        /// <summary>
        ///     Get entire TextLines buffer as a TextSpan
        /// </summary>
        /// <param name="pBuffer"></param>
        /// <returns></returns>
        private static TextSpan GetBufferSpan(IVsTextLines textBuffer)
        {
            ArgumentValidation.CheckForNullReference(textBuffer, "textBuffer");

            var lineCount = 0;
            var charCount = 0;

            // Get line count for the whole buffer.
            var result = textBuffer.GetLineCount(out lineCount);
            if (result == VSConstants.S_OK
                && lineCount > 0)
            {
                // Get char count for last line.
                result = textBuffer.GetLengthOfLine(lineCount - 1, out charCount);
                if (result != VSConstants.S_OK)
                {
                    charCount = 0;
                }
            }
            else
            {
                lineCount = 0;
            }

            // Create a TextSpan from begin to end of the text buffer.
            var span = new TextSpan();
            span.iStartLine = 0;
            span.iStartIndex = 0;
            span.iEndLine = lineCount - 1 > 0 ? lineCount - 1 : 0;
            span.iEndIndex = charCount > 0 ? charCount : 0;
            return span;
        }
Example #19
0
    public static void TextSpanNormalize(ref  TextSpan span, IVsTextLines textLines ) {
      TextSpanMakePositive(ref span );
      if (textLines == null) return;

      //adjust max. lines
      int lineCount;
      try {
        textLines.GetLineCount(out lineCount );
      } catch (Exception) {
        return;  
      }
      span.iEndLine = Math.Min( span.iEndLine, lineCount-1 );
  
      //make sure the start is still before the end
      if (!TextSpanPositive( span)) {
        span.iStartLine  = span.iEndLine;
        span.iStartIndex = span.iEndIndex;
      }
  
      //adjust for line length
      int lineLength;
      try {
        textLines.GetLengthOfLine( span.iStartLine, out lineLength );
      } catch (Exception) {
        return;
      }
      span.iStartIndex = Math.Min( span.iStartIndex, lineLength );

      try {
        textLines.GetLengthOfLine( span.iEndLine, out lineLength );
      } catch (Exception) {
        return;
      }
      span.iEndIndex = Math.Min( span.iEndIndex, lineLength );      
    }
Example #20
0
        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);
            }
        }
Example #21
0
 public int GetLineCount(out int piLineCount)
 {
     return(_textBuffer.GetLineCount(out piLineCount));
 }
Example #22
0
 /// <devdoc>Pins the text span to valid line bounds returned from IVsTextLines.</devdoc>
 internal static void Normalize(ref  TextSpan span, IVsTextLines textLines)
 {
     MakePositive(ref span);
     if (textLines == null) return;
     //adjust max. lines
     int lineCount;
     if (NativeMethods.Failed(textLines.GetLineCount(out lineCount)))
         return;
     span.iEndLine = Math.Min(span.iEndLine, lineCount - 1);
     //make sure the start is still before the end
     if (!IsPositive(span))
     {
         span.iStartLine = span.iEndLine;
         span.iStartIndex = span.iEndIndex;
     }
     //adjust for line length
     int lineLength;
     if (NativeMethods.Failed(textLines.GetLengthOfLine(span.iStartLine, out lineLength)))
         return;
     span.iStartIndex = Math.Min(span.iStartIndex, lineLength);
     if (NativeMethods.Failed(textLines.GetLengthOfLine(span.iEndLine, out lineLength)))
         return;
     span.iEndIndex = Math.Min(span.iEndIndex, lineLength);
 }
        private static void addMarkersToDocument(IVsTextLines textLines)
        {
            int lineCount;

            textLines.GetLineCount(out lineCount);

            CommentStrings commentMarkers = getCommentMarkerStrings(textLines);

            if (!GlobalSettings.shouldShowIssueLinks(lineCount))
            {
                return;
            }

            bool isInBlockComment = false;

            for (int lineNumber = 0; lineNumber < lineCount; ++lineNumber)
            {
                string text;
                int    lineLength;

                List <string> issueKeys = new List <string>();

                textLines.GetLengthOfLine(lineNumber, out lineLength);
                textLines.GetLineText(lineNumber, 0, lineNumber, lineLength, out text);

                if (text == null)
                {
                    continue;
                }

                if (commentMarkers.BlockOpen != null && commentMarkers.BlockClose != null)
                {
                    int             current = 0;
                    MatchCollection matches;
                    if (isInBlockComment)
                    {
                        matches = BlockCommentEnded.Matches(text);
                        if (matches.Count > 0)
                        {
                            scanCommentedLine(textLines, lineNumber, matches[0].Value, 0, ref issueKeys);
                            current          = matches[0].Length;
                            isInBlockComment = false;
                        }
                        else
                        {
                            scanCommentedLine(textLines, lineNumber, text, 0, ref issueKeys);
                            maybeAddMarginMarker(textLines, lineNumber, lineLength, issueKeys);
                            continue;
                        }
                    }
                    else
                    {
                        if (scanForLineComment(textLines, lineNumber, text, commentMarkers, ref issueKeys))
                        {
                            maybeAddMarginMarker(textLines, lineNumber, lineLength, issueKeys);
                            continue;
                        }
                    }

                    matches = BlockInOneLine.Matches(text, current);
                    for (int i = 0; i < matches.Count; ++i)
                    {
                        scanCommentedLine(textLines, lineNumber, matches[i].Value, matches[i].Index, ref issueKeys);
                        current = matches[i].Index + matches[i].Length;
                    }

                    if (scanForLineComment(textLines, lineNumber, text, commentMarkers, ref issueKeys))
                    {
                        maybeAddMarginMarker(textLines, lineNumber, lineLength, issueKeys);
                        continue;
                    }

                    matches = BlockCommentStarted.Matches(text, current);
                    if (matches.Count > 0)
                    {
                        isInBlockComment = true;
                        scanCommentedLine(textLines, lineNumber, matches[0].Value, matches[0].Index, ref issueKeys);
                    }
                }
                else
                {
                    if (commentMarkers.Line == null)
                    {
                        maybeAddMarginMarker(textLines, lineNumber, lineLength, issueKeys);
                        continue;
                    }

                    scanForLineComment(textLines, lineNumber, text, commentMarkers, ref issueKeys);
                }
                maybeAddMarginMarker(textLines, lineNumber, lineLength, issueKeys);
            }
        }
        // Считывает содержимое файла из буфера, связанного с документом.
        // Такой способ позволяет получить еще не сохраненный на диск контент.
        private string ReadSourceFromBuffer()
        {
            IVsRunningDocumentTable rdt = NemerlePackage.GetGlobalService(typeof(IVsRunningDocumentTable)) as IVsRunningDocumentTable;

            if (rdt != null)
            {
                IEnumRunningDocuments documents;

                rdt.GetRunningDocumentsEnum(out documents);

                IntPtr documentData = IntPtr.Zero;
                uint[] docCookie    = new uint[1];
                uint   fetched;

                while ((Microsoft.VisualStudio.VSConstants.S_OK == documents.Next(1, docCookie, out fetched)) && (1 == fetched))
                {
                    uint         flags;
                    uint         editLocks;
                    uint         readLocks;
                    string       moniker;
                    IVsHierarchy docHierarchy;
                    uint         docId;
                    IntPtr       docData = IntPtr.Zero;

                    try
                    {
                        ErrorHandler.ThrowOnFailure(rdt.GetDocumentInfo(docCookie[0], out flags, out readLocks, out editLocks, out moniker, out docHierarchy, out docId, out docData));

                        // Check if this document is the one we are looking for.
                        if (docId == _id && _hierarchy.Equals(docHierarchy))
                        {
                            documentData = docData;
                            docData      = IntPtr.Zero;
                            break;
                        }
                    }
                    finally
                    {
                        if (docData != IntPtr.Zero)
                        {
                            Marshal.Release(docData);
                        }
                    }
                }

                if (documentData != IntPtr.Zero)
                {
                    object       obj      = Marshal.GetObjectForIUnknown(documentData);
                    IVsTextLines txtLines = obj as IVsTextLines;

                    int totalLines;
                    ErrorHandler.ThrowOnFailure(txtLines.GetLineCount(out totalLines));
                    StringBuilder sb = new StringBuilder();

                    for (int line = 0; line < totalLines; ++line)
                    {
                        int lineLen;
                        ErrorHandler.ThrowOnFailure(txtLines.GetLengthOfLine(line, out lineLen));

                        string lineText;
                        ErrorHandler.ThrowOnFailure(txtLines.GetLineText(line, 0, line, lineLen, out lineText));

                        sb.AppendLine(lineText);
                    }

                    return(sb.ToString());
                }
            }

            return(null);
        }
Example #25
0
    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 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);
            }
        }
Example #27
0
        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);
        }
Example #28
0
 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;
 }
Example #29
0
        /// <summary>
        /// Generic test for the "(selection)" commands
        /// </summary>
        /// <param name="target">Command to process</param>
        /// <param name="file">File path</param>
        /// <param name="view"></param>
        /// <param name="lines"></param>
        /// <param name="getExpected">Function that returns list of expected results for specified file path</param>
        protected void GenericSelectionTest(AbstractBatchCommand_Accessor target, string file, IVsTextView view, IVsTextLines lines, Func <string, List <AbstractResultItem> > getExpected)
        {
            Agent.EnsureSolutionOpen();

            int lineCount;

            lines.GetLineCount(out lineCount);
            Random rnd = new Random();

            for (int i = 0; i < 20; i++)
            {
                // initialize selection range
                int beginLine = rnd.Next(lineCount);
                int endLine   = beginLine + rnd.Next(Math.Min(lineCount, beginLine + i) - beginLine);

                int beginLineLength, endLineLength;
                lines.GetLengthOfLine(beginLine, out beginLineLength);
                lines.GetLengthOfLine(endLine, out endLineLength);
                int beginColumn = rnd.Next(beginLineLength);
                int endColumn   = beginLine == endLine ? beginColumn + (rnd.Next(Math.Min(endLineLength, beginColumn + i) - beginColumn)) : rnd.Next(endLineLength);
                if (beginLine == endLine && beginColumn == endColumn)
                {
                    endColumn++;
                }

                // set the selection
                view.SetSelection(beginLine, beginColumn, endLine, endColumn);
                target.InitializeSelection();

                // obtain the list of expected results
                List <AbstractResultItem> expectedList = new List <AbstractResultItem>();
                foreach (AbstractResultItem expected in getExpected(file))
                {
                    if (!target.IsItemOutsideSelection(expected))
                    {
                        expectedList.Add(expected);
                    }
                }

                // run the command
                target.ProcessSelection(true);

                // compare the results
                if (target is BatchMoveCommand_Accessor)
                {
                    ValidateResults(expectedList, (target as BatchMoveCommand_Accessor).Results);
                }
                else if (target is BatchInlineCommand_Accessor)
                {
                    ValidateResults(expectedList, (target as BatchInlineCommand_Accessor).Results);
                }
                else
                {
                    Assert.Fail("Unkown parent command type");
                }

                Assert.IsTrue(expectedList.Count == 0 || VLDocumentViewsManager.IsFileLocked(file));

                VLDocumentViewsManager.ReleaseLocks();
                Assert.IsFalse(VLDocumentViewsManager.IsFileLocked(file));
            }

            // close the window
            Window win = VsShellUtilities.GetWindowObject(VLDocumentViewsManager.GetWindowFrameForFile(file, false));

            win.Detach();
            win.Close(vsSaveChanges.vsSaveChangesNo);
        }