Beispiel #1
0
        TextSegment GetWordRangeAtPosition(int column, IDocumentLine line)
        {
            string text = Editor.GetLineText(line);

            string pattern = @"(-?\d*\.\d\w*)|([^\[\{\]\}\:\""\,\s]+)";

            MatchCollection matches = Regex.Matches(text, pattern, RegexOptions.Singleline);

            foreach (Match match in matches)
            {
                string word      = match.Value;
                int    endWord   = match.Index + match.Length;
                int    startWord = match.Index;

                int startColumn = startWord + 1;
                int endColumn   = endWord + 1;

                if (startColumn <= column && column <= endColumn)
                {
                    Console.WriteLine("GetWordRangeAtPosition: '{0}' start={1},length={2}", word, startColumn, word.Length);
                    return(new TextSegment(startColumn, word.Length));
                }
            }

            return(new TextSegment());
        }
        void GetLineFromActiveTextEditor()
        {
            int           lineNumber   = activeTextEditor.Caret.Line;
            IDocumentLine documentLine = activeTextEditor.Document.GetLineByNumber(lineNumber);

            lineFromActiveTextEditor = activeTextEditor.Document.GetText(documentLine);
        }
Beispiel #3
0
        /// <summary>
        /// Checks if deferral code has been changed or removed from the line.
        /// If so, ensures the removal of any associated deferral schedules.
        /// </summary>
        public static void DeleteAssociatedScheduleIfDeferralCodeChanged(
            PXGraph graph,
            IDocumentLine documentLine)
        {
            IDocumentLine oldLine;

            // Obtain the document line last saved into the database
            // to check if the new line's deferral code differs from it.
            // -
            switch (documentLine.Module)
            {
            case GL.BatchModule.AR:
                oldLine = GetOriginal <ARTran>(graph.Caches[typeof(ARTran)], documentLine as ARTran);
                break;

            case GL.BatchModule.AP:
                oldLine = GetOriginal <APTran>(graph.Caches[typeof(APTran)], documentLine as APTran);
                break;

            default:
                throw new PXException(Messages.UnexpectedDocumentLineModule);
            }

            DeleteAssociatedScheduleIfDeferralCodeChanged(graph, documentLine, oldLine);
        }
            void EditorKeyPress(object sender, KeyEventArgs e)
            {
                if (e.Key == Key.Tab || e.Key == Key.Enter || e.Key == Key.Return)
                {
                    using (editor.Document.OpenUndoGroup())
                    {
                        // is there a better way to calculate the optimal insertion point?
                        DomRegion region = resolveResult.CallingMember.BodyRegion;
                        editor.Caret.Line   = region.EndLine;
                        editor.Caret.Column = region.EndColumn;

                        editor.Document.Insert(editor.Caret.Offset, this.newHandlerCode);

                        editor.Language.FormattingStrategy.IndentLines(editor, region.EndLine, editor.Caret.Line);

                        IDocumentLine line = editor.Document.GetLine(editor.Caret.Line - 1);
                        int           indentationLength = DocumentUtilitites.GetWhitespaceAfter(editor.Document, line.Offset).Length;

                        editor.Select(line.Offset + indentationLength, line.Length - indentationLength);
                    }
                    e.Handled = true;
                }
                // detatch our keydown filter to return to the normal processing state
                RemoveEventHandlers();
            }
        /// <summary>
        /// Default implementation for multiline comments.
        /// </summary>
        protected void SurroundSelectionWithBlockComment(ITextEditor editor, string blockStart, string blockEnd)
        {
            using (editor.Document.OpenUndoGroup()) {
                int startOffset = editor.SelectionStart;
                int endOffset   = editor.SelectionStart + editor.SelectionLength;

                if (editor.SelectionLength == 0)
                {
                    IDocumentLine line = editor.Document.GetLineByOffset(editor.SelectionStart);
                    startOffset = line.Offset;
                    endOffset   = line.Offset + line.Length;
                }

                BlockCommentRegion region = FindSelectedCommentRegion(editor, blockStart, blockEnd);

                if (region != null)
                {
                    editor.Document.Remove(region.EndOffset, region.CommentEnd.Length);
                    editor.Document.Remove(region.StartOffset, region.CommentStart.Length);
                }
                else
                {
                    editor.Document.Insert(endOffset, blockEnd);
                    editor.Document.Insert(startOffset, blockStart);
                }
            }
        }
        public override void IndentLine(ITextEditor editor, IDocumentLine line)
        {
            var document = editor.Document;
            var engine   = CreateIndentEngine(document, editor.ToEditorOptions());

            IndentSingleLine(engine, document, line);
        }
		public override void IndentLine(ITextEditor editor, IDocumentLine line)
		{
			if (line.LineNumber == 1) {
				base.IndentLine(editor, line);
				return;
			}
			
			IDocument document = editor.Document;
			IDocumentLine previousLine = document.GetLine(line.LineNumber - 1);
			string previousLineText = previousLine.Text.Trim();
			
			if (previousLineText.EndsWith(":")) {
				IncreaseLineIndent(editor, line);
			} else if (previousLineText == "pass") {
				DecreaseLineIndent(editor, line);
			} else if ((previousLineText == "return") || (previousLineText.StartsWith("return "))) {
				DecreaseLineIndent(editor, line);
			} else if ((previousLineText == "raise") || (previousLineText.StartsWith("raise "))) {
				DecreaseLineIndent(editor, line);
			} else if (previousLineText == "break") {
				DecreaseLineIndent(editor, line);
			} else {
				base.IndentLine(editor, line);
			}
		}
        async Task <HighlightState> GetStateAsync(IDocumentLine line, CancellationToken cancellationToken = default)
        {
            var pl = line?.PreviousLine;

            if (pl == null)
            {
                return(HighlightState.CreateNewState(this));
            }
            if (stateCache.Count == 0)
            {
                stateCache.Add(HighlightState.CreateNewState(this));
            }
            var ln = line.LineNumber;

            if (ln <= stateCache.Count)
            {
                return(stateCache [ln - 1].Clone());
            }
            var lastState = stateCache [stateCache.Count - 1];
            var cur       = Document.GetLine(stateCache.Count);

            if (cur != null && cur.Offset < line.Offset)
            {
                do
                {
                    var high = new Highlighter(this, lastState.Clone());
                    await high.GetColoredSegments(Document, cur.Offset, cur.LengthIncludingDelimiter, cancellationToken);

                    stateCache.Add(lastState = high.State);
                    cur = cur.NextLine;
                } while (cur != null && cur.Offset < line.Offset);
            }

            return(lastState.Clone());
        }
		void ModifyLineIndent(ITextEditor editor, IDocumentLine line, bool increaseIndent)
		{
			string indentation = GetLineIndentation(editor, line.LineNumber - 1);
			indentation = GetNewLineIndentation(indentation, editor.Options.IndentationString, increaseIndent);
			string newIndentedText = indentation + line.Text;
			editor.Document.Replace(line.Offset, line.Length, newIndentedText);
		}
Beispiel #10
0
        /// <summary>
        /// Gets the line containing the character at a specific offset in the document
        /// (first char at index 0 at the beginning of document)
        /// </summary>
        public ITextLine GetLineByOffset(int offset, out int indexOfCharInLine)
        {
            IDocumentLine documentLine = _avalonEditTextDocument.GetLineByOffset(offset);

            indexOfCharInLine = offset - documentLine.Offset;
            return(BuildTextLineFromDocumentLine(documentLine));
        }
Beispiel #11
0
 /// <summary>
 /// Checks whether the sequence point can be added to the document.
 /// </summary>
 /// <remarks>
 /// Checks for invalid start lines, start columns, end columns and end
 /// lines that cannot fit in the document.</remarks>
 bool IsValidSequencePoint(IDocument document, CodeCoverageSequencePoint sequencePoint)
 {
     if (sequencePoint.Line <= 0 || sequencePoint.EndLine <= 0 || sequencePoint.Column <= 0 || sequencePoint.EndColumn <= 0)
     {
         return(false);
     }
     else if (sequencePoint.Line > document.TotalNumberOfLines)
     {
         return(false);
     }
     else if (sequencePoint.EndLine > document.TotalNumberOfLines)
     {
         return(false);
     }
     else if (sequencePoint.Line == sequencePoint.EndLine && sequencePoint.Column > sequencePoint.EndColumn)
     {
         return(false);
     }
     else
     {
         // Check the columns exist on the line.
         IDocumentLine lineSegment = document.GetLine(sequencePoint.Line);
         if (sequencePoint.Column > lineSegment.Length)
         {
             return(false);
         }
         IDocumentLine endLineSegment = document.GetLine(sequencePoint.EndLine);
         if (sequencePoint.EndColumn > endLineSegment.Length + 1)
         {
             return(false);
         }
     }
     return(true);
 }
        static void MarkResult(List <ITextEditor> textAreas, SearchResultMatch result)
        {
            ITextEditor textArea = OpenTextArea(result.FileName);

            if (textArea != null)
            {
                if (!textAreas.Contains(textArea))
                {
                    textAreas.Add(textArea);
                }
                textArea.Caret.Offset = result.Offset;
                IDocumentLine segment = textArea.Document.GetLineForOffset(result.Offset);

                int lineNr = segment.LineNumber;

                foreach (var bookmark in BookmarkManager.GetBookmarks(result.FileName))
                {
                    if (bookmark.CanToggle && bookmark.LineNumber == lineNr)
                    {
                        // bookmark or breakpoint already exists at that line
                        return;
                    }
                }
                BookmarkManager.AddMark(new Bookmark(result.FileName, textArea.Document.OffsetToPosition(result.Offset)));
            }
        }
        private void Reformat(CustomDialog dialog)
        {
            ITextEditor editor       = UttCodeEditor.GetActiveTextEditor();
            string      selectedText = editor.SelectedText;

            string[]      xmlLines     = FormatXml(GetSelectedString()).Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
            IDocumentLine documentLine = editor.Document.GetLineForOffset(editor.SelectionStart);
            string        lineText     = documentLine.Text;
            string        indentation  = lineText.Substring(0, lineText.Length - lineText.TrimStart().Length);

            StringBuilder formattedText = new StringBuilder();

            foreach (string line in xmlLines)
            {
                formattedText.AppendLine(indentation + "\"" + line.Replace("\"", "\\\"") + "\"");
            }

            formattedText.Remove(formattedText.Length - Environment.NewLine.Length, Environment.NewLine.Length);

            if (!selectedText.TrimStart().StartsWith("\""))
            {
                formattedText.Insert(0, "\"" + Environment.NewLine);
            }

            if (!selectedText.TrimEnd().EndsWith("\""))
            {
                formattedText.Append(Environment.NewLine + indentation + "\"");
            }


            DocumentUtilitites.FindNextWordStart(editor.Document, documentLine.Offset);

            editor.Document.Replace(editor.SelectionStart, editor.SelectionLength, formattedText.ToString());
            dialog.Close();
        }
        public void SortLines(IDocument document, int startLine, int endLine, StringComparer comparer, bool removeDuplicates)
        {
            List <string> lines = new List <string>();

            for (int i = startLine; i <= endLine; ++i)
            {
                IDocumentLine line = document.GetLineByNumber(i);
                lines.Add(document.GetText(line.Offset, line.Length));
            }

            lines.Sort(comparer);

            if (removeDuplicates)
            {
                lines = lines.Distinct(comparer).ToList();
            }

            using (document.OpenUndoGroup()) {
                for (int i = 0; i < lines.Count; ++i)
                {
                    IDocumentLine line = document.GetLineByNumber(startLine + i);
                    document.Replace(line.Offset, line.Length, lines[i]);
                }

                // remove removed duplicate lines
                for (int i = startLine + lines.Count; i <= endLine; ++i)
                {
                    IDocumentLine line = document.GetLineByNumber(startLine + lines.Count);
                    document.Remove(line.Offset, line.TotalLength);
                }
            }
        }
		/// <summary>
		/// Replaces the text in a line.
		/// If only whitespace at the beginning and end of the line was changed, this method
		/// only adjusts the whitespace and doesn't replace the other text.
		/// </summary>
		public static void SmartReplaceLine(this IDocument document, IDocumentLine line, string newLineText)
		{
			if (document == null)
				throw new ArgumentNullException("document");
			if (line == null)
				throw new ArgumentNullException("line");
			if (newLineText == null)
				throw new ArgumentNullException("newLineText");
			string newLineTextTrim = newLineText.Trim(whitespaceChars);
			string oldLineText = line.Text;
			if (oldLineText == newLineText)
				return;
			int pos = oldLineText.IndexOf(newLineTextTrim, StringComparison.Ordinal);
			if (newLineTextTrim.Length > 0 && pos >= 0) {
				using (document.OpenUndoGroup()) {
					// find whitespace at beginning
					int startWhitespaceLength = 0;
					while (startWhitespaceLength < newLineText.Length) {
						char c = newLineText[startWhitespaceLength];
						if (c != ' ' && c != '\t')
							break;
						startWhitespaceLength++;
					}
					// find whitespace at end
					int endWhitespaceLength = newLineText.Length - newLineTextTrim.Length - startWhitespaceLength;
					
					// replace whitespace sections
					int lineOffset = line.Offset;
					document.Replace(lineOffset + pos + newLineTextTrim.Length, line.Length - pos - newLineTextTrim.Length, newLineText.Substring(newLineText.Length - endWhitespaceLength));
					document.Replace(lineOffset, pos, newLineText.Substring(0, startWhitespaceLength));
				}
			} else {
				document.Replace(line.Offset, line.Length, newLineText);
			}
		}
Beispiel #16
0
        void GetPreviousLine()
        {
            int lineNumber = line.LineNumber - 1;

            previousLine     = document.GetLine(lineNumber);
            previousLineText = previousLine.Text.Trim();
        }
Beispiel #17
0
        public virtual ICompletionItemList GenerateCompletionList(ITextEditor editor, IProjectContent projectContent)
        {
            int           caretLineNumber = editor.Caret.Line;
            int           caretColumn     = editor.Caret.Column;
            IDocumentLine caretLine       = editor.Document.GetLine(caretLineNumber);
            string        lineText        = caretLine.Text;

            if (!lineText.Trim().StartsWith("///", StringComparison.Ordinal) &&
                !lineText.Trim().StartsWith("'''", StringComparison.Ordinal))
            {
                return(null);
            }

            DefaultCompletionItemList list = new DefaultCompletionItemList();

            foreach (string[] tag in commentTags)
            {
                list.Items.Add(new DefaultCompletionItem(tag[0])
                {
                    Description = new SimpleDescription(tag[1])
                });
            }
            list.SortItems();
            return(list);
        }
Beispiel #18
0
        public HighlightedLine HighlightLine(int lineNumber)
        {
            IDocumentLine line            = Document.GetLineByNumber(lineNumber);
            var           highlightedLine = new HighlightedLine(Document, line);

            lineNumber--;
            if (lineNumber >= SyntaxInfo.Count)
            {
                return(highlightedLine);
            }
            int lineOffset          = line.Offset;
            int pos                 = 0;
            List <SyntaxSpan> spans = SyntaxInfo[lineNumber];

            foreach (SyntaxSpan span in spans)
            {
                if (pos >= line.Length)
                {
                    break;
                }
                highlightedLine.Sections.Add(new HighlightedSection
                {
                    Offset = pos + lineOffset,
                    Length = Math.Min(span.Length, line.Length - pos),
                    Color  = SyntaxInfo.Colors[span.FormatType]
                });
                pos += span.Length;
            }

            return(highlightedLine);
        }
        void InsertEventHandlerBeforeLine(IDocument doc, string eventHandler, IDocumentLine classEndLine)
        {
            string newContent = "\r\n" + eventHandler + "\r\n";
            int    offset     = classEndLine.Offset;

            doc.Insert(offset, newContent);
        }
		/// <summary>
		/// Replaces the text in a line.
		/// If only whitespace at the beginning and end of the line was changed, this method
		/// only adjusts the whitespace and doesn't replace the other text.
		/// </summary>
		public static void SmartReplaceLine(this IDocument document, IDocumentLine line, string newLineText)
		{
			if (document == null)
				throw new ArgumentNullException("document");
			if (line == null)
				throw new ArgumentNullException("line");
			if (newLineText == null)
				throw new ArgumentNullException("newLineText");
			string newLineTextTrim = newLineText.Trim(whitespaceChars);
			string oldLineText = document.GetText(line);
			if (oldLineText == newLineText)
				return;
			int pos = oldLineText.IndexOf(newLineTextTrim, StringComparison.Ordinal);
			if (newLineTextTrim.Length > 0 && pos >= 0) {
				using (document.OpenUndoGroup()) {
					// find whitespace at beginning
					int startWhitespaceLength = 0;
					while (startWhitespaceLength < newLineText.Length) {
						char c = newLineText[startWhitespaceLength];
						if (c != ' ' && c != '\t')
							break;
						startWhitespaceLength++;
					}
					// find whitespace at end
					int endWhitespaceLength = newLineText.Length - newLineTextTrim.Length - startWhitespaceLength;
					
					// replace whitespace sections
					int lineOffset = line.Offset;
					document.Replace(lineOffset + pos + newLineTextTrim.Length, line.Length - pos - newLineTextTrim.Length, newLineText.Substring(newLineText.Length - endWhitespaceLength));
					document.Replace(lineOffset, pos, newLineText.Substring(0, startWhitespaceLength));
				}
			} else {
				document.Replace(line.Offset, line.Length, newLineText);
			}
		}
Beispiel #21
0
        static void Apply_TrimTrailingWhitespace(
            TextEditor editor,
            IDocumentLine line,
            List <TextChange> changes)
        {
            int offset = line.EndOffset;

            for (; offset > line.Offset; --offset)
            {
                char c = editor.GetCharAt(offset - 1);

                if (!char.IsWhiteSpace(c))
                {
                    break;
                }
            }

            TextChange change = ChangeFromBounds(offset, line.EndOffset, string.Empty);

            if (change.Span.Length == 0)
            {
                return;
            }

            changes.Add(change);
        }
        static WixDocumentLineSegment ConvertRegionToSingleLineSegment(IDocument document, DomRegion region)
        {
            IDocumentLine documentLine = document.GetLineByNumber(region.BeginLine);

            return(new WixDocumentLineSegment(documentLine.Offset + region.BeginColumn - 1,
                                              region.EndColumn - region.BeginColumn + 1));
        }
 void HighlightLineAndUpdateTreeList(IDocumentLine line, int lineNumber)
 {
     //Debug.WriteLine("Highlight line " + lineNumber + (highlightedLine != null ? "" : " (span stack only)"));
     spanStack = storedSpanStacks[lineNumber - 1];
     HighlightLineInternal(line);
     if (!EqualSpanStacks(spanStack, storedSpanStacks[lineNumber]))
     {
         isValid[lineNumber] = true;
         //Debug.WriteLine("Span stack in line " + lineNumber + " changed from " + storedSpanStacks[lineNumber] + " to " + spanStack);
         storedSpanStacks[lineNumber] = spanStack;
         if (lineNumber + 1 < isValid.Count)
         {
             isValid[lineNumber + 1] = false;
             firstInvalidLine        = lineNumber + 1;
         }
         else
         {
             firstInvalidLine = int.MaxValue;
         }
         if (lineNumber + 1 < document.LineCount)
         {
             OnHighlightStateChanged(lineNumber + 1, lineNumber + 1);
         }
     }
     else if (firstInvalidLine == lineNumber)
     {
         isValid[lineNumber] = true;
         firstInvalidLine    = isValid.IndexOf(false);
         if (firstInvalidLine < 0)
         {
             firstInvalidLine = int.MaxValue;
         }
     }
 }
        static int FindEndStatementAroundOffset(IDocument document, int offset, out VBStatement statement)
        {
            IDocumentLine line = document.GetLineForOffset(offset);

            string interestingText = line.Text.TrimLine().Trim(' ', '\t');

            //LoggingService.Debug("text: '" + interestingText + "'");

            foreach (VBStatement s in VBNetFormattingStrategy.Statements)
            {
                Match match = Regex.Matches(interestingText, s.EndRegex, RegexOptions.Singleline | RegexOptions.IgnoreCase).OfType <Match>().FirstOrDefault();
                if (match != null)
                {
                    //LoggingService.DebugFormatted("Found end statement at offset {1}: {0}", s, offset);
                    statement = s;
                    int result = match.Index + (line.Length - line.Text.TrimStart(' ', '\t').Length) + line.Offset;
                    if (offset >= result && offset <= (result + match.Length))
                    {
                        return(result);
                    }
                }
            }

            statement = null;
            return(-1);
        }
Beispiel #25
0
        static bool TryDeclarationTypeInference(ITextEditor editor, IDocumentLine curLine)
        {
            string lineText = editor.Document.GetText(curLine.Offset, curLine.Length);
            ILexer lexer    = ParserFactory.CreateLexer(SupportedLanguage.VBNet, new System.IO.StringReader(lineText));

            if (lexer.NextToken().Kind != Tokens.Dim)
            {
                return(false);
            }
            if (lexer.NextToken().Kind != Tokens.Identifier)
            {
                return(false);
            }
            if (lexer.NextToken().Kind != Tokens.As)
            {
                return(false);
            }
            Token t1 = lexer.NextToken();

            if (t1.Kind != Tokens.QuestionMark)
            {
                return(false);
            }
            Token t2 = lexer.NextToken();

            if (t2.Kind != Tokens.Assign)
            {
                return(false);
            }
            string expr = lineText.Substring(t2.Location.Column);

            LoggingService.Debug("DeclarationTypeInference: >" + expr + "<");
            ResolveResult rr = ParserService.Resolve(new ExpressionResult(expr),
                                                     editor.Caret.Line,
                                                     t2.Location.Column, editor.FileName,
                                                     editor.Document.Text);

            if (rr != null && rr.ResolvedType != null)
            {
                ClassFinder   context  = new ClassFinder(ParserService.GetParseInformation(editor.FileName), editor.Caret.Line, t1.Location.Column);
                VBNetAmbience ambience = new VBNetAmbience();
                if (CodeGenerator.CanUseShortTypeName(rr.ResolvedType, context))
                {
                    ambience.ConversionFlags = ConversionFlags.None;
                }
                else
                {
                    ambience.ConversionFlags = ConversionFlags.UseFullyQualifiedTypeNames;
                }
                string typeName = ambience.Convert(rr.ResolvedType);
                using (editor.Document.OpenUndoGroup()) {
                    int offset = curLine.Offset + t1.Location.Column - 1;
                    editor.Document.Remove(offset, 1);
                    editor.Document.Insert(offset, typeName);
                }
                editor.Caret.Column += typeName.Length - 1;
                return(true);
            }
            return(false);
        }
        static bool IsSingleLine(int line, ITextEditor editor)
        {
            if (line < 1)
            {
                return(false);
            }

            IDocumentLine lineSeg = editor.Document.GetLine(line);

            if (lineSeg == null)
            {
                return(false);
            }

            string text = lineSeg.Text;

            if (text.TrimComments().Trim(' ', '\t', '\r', '\n').EndsWith("_", StringComparison.OrdinalIgnoreCase))
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
Beispiel #27
0
        /// <summary>
        /// This method gets the line indentation.
        /// </summary>
        /// <param name = "line"></param>
        /// <param name="doc">
        /// The <see cref="IReadonlyTextDocument"/> the line belongs to.
        /// </param>
        /// <returns>
        /// The indentation of the line (all whitespace chars up to the first non ws char).
        /// </returns>
        public static string GetIndentation(this IDocumentLine line, IReadonlyTextDocument doc)
        {
            if (line == null)
            {
                throw new ArgumentNullException(nameof(line));
            }
            if (doc == null)
            {
                throw new ArgumentNullException(nameof(doc));
            }
            var result = new StringBuilder();
            int offset = line.Offset;
            int max    = Math.Min(offset + line.LengthIncludingDelimiter, doc.Length);

            for (int i = offset; i < max; i++)
            {
                char ch = doc.GetCharAt(i);
                if (ch != ' ' && ch != '\t')
                {
                    break;
                }
                result.Append(ch);
            }
            return(result.ToString());
        }
Beispiel #28
0
        HighlightState GetState(IDocumentLine line)
        {
            var pl = line.PreviousLine;

            if (pl == null)
            {
                return(HighlightState.CreateNewState(this));
            }
            if (stateCache.Count == 0)
            {
                stateCache.Add(HighlightState.CreateNewState(this));
            }
            var ln = line.LineNumber;

            if (ln <= stateCache.Count)
            {
                return(stateCache [ln - 1].Clone());
            }
            var lastState = stateCache [stateCache.Count - 1];
            var cur       = Document.GetLine(stateCache.Count);

            if (cur != null && cur.Offset < line.Offset)
            {
                do
                {
                    var high = new Highlighter(this, lastState.Clone());
                    high.GetColoredSegments(Document, cur.Offset, cur.LengthIncludingDelimiter).Wait();
                    stateCache.Add(lastState = high.State);
                    cur = cur.NextLine;
                } while (cur != null && cur.Offset < line.Offset);
            }

            return(lastState.Clone());
        }
        /// <summary>
        /// Creates a new <see cref="FixedHighlighter"/> for a copy of a portion
        /// of the input document (including the original highlighting).
        /// </summary>
        public static FixedHighlighter CreateView(IHighlighter highlighter, int offset, int endOffset)
        {
            var oldDocument = highlighter.Document;
            // ReadOnlyDocument would be better; but displaying the view in AvalonEdit
            // requires a TextDocument
            var newDocument = new TextDocument(oldDocument.CreateSnapshot(offset, endOffset - offset));

            var oldStartLine       = oldDocument.GetLineByOffset(offset);
            var oldEndLine         = oldDocument.GetLineByOffset(endOffset);
            int oldStartLineNumber = oldStartLine.LineNumber;

            HighlightedLine[] newLines = new HighlightedLine[oldEndLine.LineNumber - oldStartLineNumber + 1];
            highlighter.BeginHighlighting();
            try {
                for (int i = 0; i < newLines.Length; i++)
                {
                    HighlightedLine oldHighlightedLine = highlighter.HighlightLine(oldStartLineNumber + i);
                    IDocumentLine   newLine            = newDocument.GetLineByNumber(1 + i);
                    HighlightedLine newHighlightedLine = new HighlightedLine(newDocument, newLine);
                    MoveSections(oldHighlightedLine.Sections, -offset, newLine.Offset, newLine.EndOffset, newHighlightedLine.Sections);
                    newHighlightedLine.ValidateInvariants();
                    newLines[i] = newHighlightedLine;
                }
            } finally {
                highlighter.EndHighlighting();
            }
            return(new FixedHighlighter(newDocument, newLines));
        }
		public override void IndentLine(ITextEditor editor, IDocumentLine line)
		{
			LineIndenter indenter = CreateLineIndenter(editor, line);
			if (!indenter.Indent()) {
				base.IndentLine(editor, line);
			}
		}
        void GetLineFromActiveTextEditor()
        {
            int           lineNumber   = activeTextEditor.Caret.Line;
            IDocumentLine documentLine = activeTextEditor.Document.GetLine(lineNumber);

            lineFromActiveTextEditor = documentLine.Text;
        }
        void GetPreviousLine()
        {
            int lineNumber = line.LineNumber - 1;

            previousLine     = document.GetLineByNumber(lineNumber);
            previousLineText = document.GetText(previousLine).Trim();
        }
        public static void SetPosition(FileName fileName, IDocument document, int makerStartLine, int makerStartColumn, int makerEndLine, int makerEndColumn)
        {
            Remove();

            startLine   = makerStartLine;
            startColumn = makerStartColumn;
            endLine     = makerEndLine;
            endColumn   = makerEndColumn;

            if (startLine < 1 || startLine > document.TotalNumberOfLines)
            {
                return;
            }
            if (endLine < 1 || endLine > document.TotalNumberOfLines)
            {
                endLine   = startLine;
                endColumn = int.MaxValue;
            }
            if (startColumn < 1)
            {
                startColumn = 1;
            }

            IDocumentLine line = document.GetLine(startLine);

            if (endColumn < 1 || endColumn > line.Length)
            {
                endColumn = line.Length;
            }
            instance = new CurrentLineBookmark(fileName, new Location(startColumn, startLine));
            BookmarkManager.AddMark(instance);
        }
 /// <summary>
 /// Creates a new HighlightedLine instance.
 /// </summary>
 public HighlightedLine(IDocument document, IDocumentLine documentLine)
 {
     //if (!document.Lines.Contains(documentLine))
     //	throw new ArgumentException("Line is null or not part of document");
     Document     = document ?? throw new ArgumentNullException(nameof(document));
     DocumentLine = documentLine;
     Sections     = new NullSafeCollection <HighlightedSection>();
 }
Beispiel #35
0
		public EntityBookmark(IUnresolvedEntity entity, IDocument document)
		{
			this.entity = entity;
			int lineNr = entity.Region.BeginLine;
			if (document != null && lineNr > 0 && lineNr < document.LineCount) {
				this.line = document.GetLineByNumber(lineNr);
			}
		}
		public VBIndentationStrategy(ITextEditor editor, int start, int end)
			: this()
		{
			this.editor = editor;
			
			startLine = editor.Document.GetLine(start);
			endLine = editor.Document.GetLine(end);
		}
 bool IsBracketOnly(IDocument document, IDocumentLine documentLine)
 {
     string lineText = document.GetText(documentLine).Trim();
     return lineText == "{" || string.IsNullOrEmpty(lineText)
         || lineText.StartsWith("//", StringComparison.Ordinal)
         || lineText.StartsWith("/*", StringComparison.Ordinal)
         || lineText.StartsWith("*", StringComparison.Ordinal)
         || lineText.StartsWith("'", StringComparison.Ordinal);
 }
Beispiel #38
0
		public RubyLineIndenter(ITextEditor editor, IDocumentLine line)
			: base(editor, line)
		{
			CreateDecreaseLineIndentStatements();
			CreateDecreaseLineIndentStartsWithStatements();
			CreateIncreaseLineIndentStatements();
			CreateIncreaseLineIndentStartsWithStatements();
			CreateIncreaseLineIndentEndsWithStatements();
			CreateIncreaseLineIndentContainsStatements();
		}
		public override void IndentLine(ITextEditor editor, IDocumentLine line)
		{
			editor.Document.StartUndoableAction();
			try {
				TryIndent(editor, line.LineNumber, line.LineNumber);
			} catch (XmlException ex) {
				LoggingService.Debug(ex.ToString());
			} finally {
				editor.Document.EndUndoableAction();
			}
		}
		/// <summary>
		/// Updates <see cref="CurrentSpanStack"/> for the specified line in the specified document.
		/// 
		/// Before calling this method, <see cref="CurrentSpanStack"/> must be set to the proper
		/// state for the beginning of this line. After highlighting has completed,
		/// <see cref="CurrentSpanStack"/> will be updated to represent the state after the line.
		/// </summary>
		public void ScanLine(IDocument document, IDocumentLine line)
		{
			//this.lineStartOffset = line.Offset; not necessary for scanning
			this.lineText = document.GetText(line);
			try {
				Debug.Assert(highlightedLine == null);
				HighlightLineInternal();
			} finally {
				this.lineText = null;
			}
		}
		static void IndentSingleLine(CacheIndentEngine engine, IDocument document, IDocumentLine line)
		{
			engine.Update(line.EndOffset);
			if (engine.NeedsReindent) {
				var indentation = TextUtilities.GetWhitespaceAfter(document, line.Offset);
				// replacing the indentation in two steps is necessary to make the caret move accordingly.
				document.Replace(indentation.Offset, indentation.Length, "");
				document.Replace(indentation.Offset, 0, engine.ThisLineIndent);
				engine.ResetEngineToPosition(line.Offset);
			}
		}
Beispiel #42
0
		/// <inheritdoc/>
		public bool MoveNext()
		{
			if (lineDirty) {
				DocumentUtilitites.SmartReplaceLine(doc, line, text);
				lineDirty = false;
			}
			++num;
			if (num > maxLine) return false;
			line = doc.GetLine(num);
			text = line.Text;
			return true;
		}
Beispiel #43
0
		public static bool IsInsideDocumentationComment(ITextEditor editor, IDocumentLine curLine, int cursorOffset)
		{
			for (int i = curLine.Offset; i < cursorOffset; ++i) {
				char ch = editor.Document.GetCharAt(i);
				if (ch == '"')
					return false;
				if (ch == '\'' && i + 2 < cursorOffset && editor.Document.GetCharAt(i + 1) == '\'' &&
				    editor.Document.GetCharAt(i + 2) == '\'')
					return true;
			}
			return false;
		}
		public virtual void IndentLine(ITextEditor editor, IDocumentLine line)
		{
			IDocument document = editor.Document;
			int lineNumber = line.LineNumber;
			if (lineNumber > 1) {
				IDocumentLine previousLine = document.GetLineByNumber(lineNumber - 1);
				string indentation = DocumentUtilities.GetWhitespaceAfter(document, previousLine.Offset);
				// copy indentation to line
				string newIndentation = DocumentUtilities.GetWhitespaceAfter(document, line.Offset);
				document.Replace(line.Offset, newIndentation.Length, indentation);
			}
		}
		/// <summary>
		/// Highlights the specified line in the specified document.
		/// 
		/// Before calling this method, <see cref="CurrentSpanStack"/> must be set to the proper
		/// state for the beginning of this line. After highlighting has completed,
		/// <see cref="CurrentSpanStack"/> will be updated to represent the state after the line.
		/// </summary>
		public HighlightedLine HighlightLine(IDocument document, IDocumentLine line)
		{
			this.lineStartOffset = line.Offset;
			this.lineText = document.GetText(line);
			try {
				this.highlightedLine = new HighlightedLine(document, line);
				HighlightLineInternal();
				return this.highlightedLine;
			} finally {
				this.highlightedLine = null;
				this.lineText = null;
				this.lineStartOffset = 0;
			}
		}
		public override void IndentLine(ITextEditor editor, IDocumentLine line)
		{
			int lineNr = line.LineNumber;
			DocumentAccessor acc = new DocumentAccessor(editor.Document, lineNr, lineNr);
			
			CSharpIndentationStrategy indentStrategy = new CSharpIndentationStrategy();
			indentStrategy.IndentationString = editor.Options.IndentationString;
			indentStrategy.Indent(acc, false);
			
			string t = acc.Text;
			if (t.Length == 0) {
				// use AutoIndentation for new lines in comments / verbatim strings.
				base.IndentLine(editor, line);
			}
		}
        public override void IndentLine(ITextEditor editor, IDocumentLine line)
        {
            if (line.LineNumber > 1)
            {
                IDocumentLine above = editor.Document.GetLine(line.LineNumber - 1);
                string up = above.Text.Trim();
                if (up.StartsWith("--") == false)
                {
                    // above line is an indent statement
                    if (up.EndsWith("do")
                        || up.EndsWith("then")
                        || (up.StartsWith("function") && up.EndsWith(")"))
                        || (up.Contains("function") && up.EndsWith(")"))) // e.g. aTable.x = function([...])
                    {
                        string indentation = DocumentUtilitites.GetWhitespaceAfter(editor.Document, above.Offset);
                        string newLine = line.Text.TrimStart();
                        newLine = indentation + editor.Options.IndentationString + newLine;
                        editor.Document.SmartReplaceLine(line, newLine);
                    }
                    else // above line is not an indent statement
                    {
                        string indentation = DocumentUtilitites.GetWhitespaceAfter(editor.Document, above.Offset);
                        string newLine = line.Text.TrimStart();
                        newLine = indentation + newLine;
                        editor.Document.SmartReplaceLine(line, newLine);
                    }
                }

                if (line.Text.StartsWith("end"))
                {
                    string indentation = DocumentUtilitites.GetWhitespaceAfter(editor.Document, above.Offset);
                    string newLine = line.Text.TrimStart();
                    string newIndent = "";

                    if (indentation.Length >= editor.Options.IndentationSize)
                        newIndent = indentation.Substring(0, indentation.Length - editor.Options.IndentationSize);

                    newLine = newIndent + newLine;
                    editor.Document.SmartReplaceLine(line, newLine);
                }
            }
            else
            {

            }
            //base.IndentLine(editor, line);
        }
		public override void IndentLine(ITextEditor editor, IDocumentLine line)
		{
			IDocument document = editor.Document;
			int lineNumber = line.LineNumber;
			if (lineNumber > 1) {
				IDocumentLine previousLine = document.GetLine(line.LineNumber - 1);
				
				if (previousLine.Text.EndsWith(":", StringComparison.Ordinal)) {
					string indentation = DocumentUtilitites.GetWhitespaceAfter(document, previousLine.Offset);
					indentation += editor.Options.IndentationString;
					string newIndentation = DocumentUtilitites.GetWhitespaceAfter(document, line.Offset);
					document.Replace(line.Offset, newIndentation.Length, indentation);
					return;
				}
			}
			base.IndentLine(editor, line);
		}
		public void Init()
		{
			formattingStrategy = new XmlFormattingStrategy();
			
			options = new MockTextEditorOptions();
			textEditor = new MockTextEditor();
			textEditor.Options = options;
			
			textDocument = new TextDocument();
			document = textDocument;
			textEditor.SetDocument(document);
			
			document.Text = 
				"<root>\r\n" +
				"\t<child>\r\n" +
				"</child>\r\n" +
				"</root>\r\n";
			
			docLine = MockRepository.GenerateStub<IDocumentLine>();
			docLine.Stub(l => l.LineNumber).Return(3);
			formattingStrategy.IndentLine(textEditor, docLine);
		}
		public static bool GuessSemicolonInsertionOffset (TextEditorData data, IDocumentLine curLine, int caretOffset, out int outOffset)
		{
			int lastNonWsOffset = caretOffset;
			char lastNonWsChar = '\0';
			outOffset = caretOffset;
			int max = curLine.EndOffset;
	//		if (caretOffset - 2 >= curLine.Offset && data.Document.GetCharAt (caretOffset - 2) == ')' && !IsSemicolonalreadyPlaced (data, caretOffset))
	//			return false;

			int end = caretOffset;
			while (end > 1 && char.IsWhiteSpace (data.GetCharAt (end)))
				end--;
			int end2 = end;
			while (end2 > 1 && char.IsLetter(data.GetCharAt (end2 - 1)))
				end2--;
			if (end != end2) {
				string token = data.GetTextBetween (end2, end + 1);
				// guess property context
				if (token == "get" || token == "set")
					return false;
			}

			bool isInString = false , isInChar= false , isVerbatimString= false;
			bool isInLineComment = false , isInBlockComment= false;
			bool firstChar = true;
			for (int pos = caretOffset; pos < max; pos++) {
				if (pos == caretOffset) {
					if (isInString || isInChar || isVerbatimString || isInLineComment || isInBlockComment) {
						outOffset = pos;
						return true;
					}
				}
				char ch = data.Document.GetCharAt (pos);
				switch (ch) {
				case '}':
					if (firstChar && !IsSemicolonalreadyPlaced (data, caretOffset))
						return false;
					break;
				case '/':
					if (isInBlockComment) {
						if (pos > 0 && data.Document.GetCharAt (pos - 1) == '*') 
							isInBlockComment = false;
					} else if (!isInString && !isInChar && pos + 1 < max) {
						char nextChar = data.Document.GetCharAt (pos + 1);
						if (nextChar == '/') {
							outOffset = lastNonWsOffset;
							return true;
						}
						if (!isInLineComment && nextChar == '*') {
							outOffset = lastNonWsOffset;
							return true;
						}
					}
					break;
				case '\\':
					if (isInChar || (isInString && !isVerbatimString))
						pos++;
					break;
				case '@':
					if (!(isInString || isInChar || isInLineComment || isInBlockComment) && pos + 1 < max && data.Document.GetCharAt (pos + 1) == '"') {
						isInString = true;
						isVerbatimString = true;
						pos++;
					}
					break;
				case '"':
					if (!(isInChar || isInLineComment || isInBlockComment)) {
						if (isInString && isVerbatimString && pos + 1 < max && data.Document.GetCharAt (pos + 1) == '"') {
							pos++;
						} else {
							isInString = !isInString;
							isVerbatimString = false;
						}
					}
					break;
				case '\'':
					if (!(isInString || isInLineComment || isInBlockComment)) 
						isInChar = !isInChar;
					break;
				}
				if (!char.IsWhiteSpace (ch)) {
					firstChar = false;
					lastNonWsOffset = pos;
					lastNonWsChar = ch;
				}
			}
			// if the line ends with ';' the line end is not the correct place for a new semicolon.
			if (lastNonWsChar == ';')
				return false;
			outOffset = lastNonWsOffset;
			return true;
		}
 public override void IndentLine(ITextEditor editor, IDocumentLine line)
 {
     editor.Document.StartUndoableAction();
     TryIndent(editor, line.LineNumber, line.LineNumber);
     editor.Document.EndUndoableAction();
 }
		IUrlTextLineMarker ITextMarkerFactory.CreateUrlTextMarker (MonoDevelop.Ide.Editor.TextEditor editor, IDocumentLine line, string value, MonoDevelop.Ide.Editor.UrlType url, string syntax, int startCol, int endCol)
		{
			return new UrlTextLineMarker (TextEditor.Document, line, value, (Mono.TextEditor.UrlType)url, syntax, startCol, endCol);
		}
		static void DoCasingOnLine(IDocumentLine lineAbove, string textToReplace, ITextEditor editor)
		{
			foreach (string keyword in keywords) {
				string regex = "\\b" + keyword + "\\b"; // \b = word border
				MatchCollection matches = Regex.Matches(textToReplace, regex, RegexOptions.IgnoreCase | RegexOptions.Singleline);
				foreach (Match match in matches) {
					if (keyword == "EndIf") // special case
						editor.Document.Replace(lineAbove.Offset + match.Index, match.Length, "End If");
					else
						editor.Document.Replace(lineAbove.Offset + match.Index, match.Length, keyword);
				}
			}
		}
		bool IsInsideDocumentationComment(ITextEditor textArea, IDocumentLine curLine, int cursorOffset)
		{
			for (int i = curLine.Offset; i < cursorOffset; ++i) {
				char ch = textArea.Document.GetCharAt(i);
				if (ch == '"') {
					// parsing strings correctly is too complicated (see above),
					// but I don't now any case where a doc comment is after a string...
					return false;
				}
				if (ch == '/' && i + 2 < cursorOffset && textArea.Document.GetCharAt(i + 1) == '/' && textArea.Document.GetCharAt(i + 2) == '/') {
					return true;
				}
			}
			return false;
		}
		bool IsInsideStringOrComment(ITextEditor textArea, IDocumentLine curLine, int cursorOffset)
		{
			// scan cur line if it is inside a string or single line comment (//)
			bool insideString  = false;
			char stringstart = ' ';
			bool verbatim = false; // true if the current string is verbatim (@-string)
			char c = ' ';
			char lastchar;
			
			for (int i = curLine.Offset; i < cursorOffset; ++i) {
				lastchar = c;
				c = textArea.Document.GetCharAt(i);
				if (insideString) {
					if (c == stringstart) {
						if (verbatim && i + 1 < cursorOffset && textArea.Document.GetCharAt(i + 1) == '"') {
							++i; // skip escaped character
						} else {
							insideString = false;
						}
					} else if (c == '\\' && !verbatim) {
						++i; // skip escaped character
					}
				} else if (c == '/' && i + 1 < cursorOffset && textArea.Document.GetCharAt(i + 1) == '/') {
					return true;
				} else if (c == '"' || c == '\'') {
					stringstart = c;
					insideString = true;
					verbatim = (c == '"') && (lastchar == '@');
				}
			}
			
			return insideString;
		}
		public override void IndentLine(ITextEditor editor, IDocumentLine line)
		{
			var document = editor.Document;
			var engine = CreateIndentEngine(document, editor.ToEditorOptions());
			IndentSingleLine(engine, document, line);
		}
		void DoInsertionOnLine(string terminator, IDocumentLine currentLine, IDocumentLine lineAbove, string textToReplace, ITextEditor editor, int lineNr)
		{
			string curLineText = currentLine.Text;
			
			if (Regex.IsMatch(textToReplace.Trim(), "^If .*[^_]$", RegexOptions.IgnoreCase)) {
				if (!Regex.IsMatch(textToReplace, "\\bthen\\b", RegexOptions.IgnoreCase)) {
					string specialThen = "Then"; // do special check in cases like If t = True' comment
					if (editor.Document.GetCharAt(lineAbove.Offset + textToReplace.Length) == '\'')
						specialThen += " ";
					if (editor.Document.GetCharAt(lineAbove.Offset + textToReplace.Length - 1) != ' ')
						specialThen = " " + specialThen;
					editor.Document.Insert(lineAbove.Offset + textToReplace.Length, specialThen);
					textToReplace += specialThen;
				}
			}
			
			// check #Region statements
			if (Regex.IsMatch(textToReplace.Trim(), "^#Region", RegexOptions.IgnoreCase) && LookForEndRegion(editor)) {
				string indentation = DocumentUtilitites.GetWhitespaceAfter(editor.Document, lineAbove.Offset);
				textToReplace += indentation + "\r\n" + indentation + "#End Region";
				editor.Document.Replace(currentLine.Offset, currentLine.Length, textToReplace);
			}
			
			foreach (VBStatement statement_ in statements) {
				VBStatement statement = statement_;	// allow passing statement byref
				if (Regex.IsMatch(textToReplace.Trim(), statement.StartRegex, RegexOptions.IgnoreCase)) {
					string indentation = DocumentUtilitites.GetWhitespaceAfter(editor.Document, lineAbove.Offset);
					if (IsEndStatementNeeded(editor, ref statement, lineNr)) {
						editor.Document.Replace(currentLine.Offset, currentLine.Length, terminator + indentation + statement.EndStatement);
					}
					if (!IsInsideInterface(editor, lineNr) || statement == interfaceStatement) {
						for (int i = 0; i < statement.IndentPlus; i++) {
							indentation += editor.Options.IndentationString;
						}
					}
					editor.Document.Replace(currentLine.Offset, currentLine.Length, indentation + curLineText.Trim());
					editor.Caret.Line = currentLine.LineNumber;
					editor.Caret.Column = indentation.Length;
					return;
				}
			}
		}
		void ITextEditorImpl.AddMarker (IDocumentLine line, ITextLineMarker lineMarker)
		{
			var debugPair = lineMarker as DebugMarkerPair;
			if (debugPair != null) {
				debugPair.AddTo (TextEditor.Document, ((DocumentLineWrapper)line).Line);
				return;
			}
			var textLineMarker = lineMarker as TextLineMarker;
			if (textLineMarker == null)
				throw new InvalidOperationException ("Tried to add an incompatible text marker. Use the MarkerHost to create compatible ones.");

			if (lineMarker is IUnitTestMarker) {
				var actionMargin = TextEditor.ActionMargin;
				if (actionMargin != null) {
					actionMargin.IsVisible = true;
				}
			}

			TextEditor.Document.AddMarker (((DocumentLineWrapper)line).Line, textLineMarker);
		}
		public override void IndentLine(ITextEditor editor, IDocumentLine line)
		{
			IndentLines(editor, line.LineNumber, line.LineNumber);
		}
		IEnumerable<ITextLineMarker> ITextEditorImpl.GetLineMarkers (IDocumentLine line)
		{
			return ((DocumentLineWrapper)line).Line.Markers.OfType<ITextLineMarker> ();
		}