GetText() public method

Retrieves the text for a portion of the document.
public GetText ( ISegment segment ) : string
segment ISegment
return string
Esempio n. 1
0
 public void IndentLine(TextDocument document, DocumentLine line)
 {
     if (document == null || line == null)
     {
         return;
     }
     DocumentLine previousLine = line.PreviousLine;
     if (previousLine != null)
     {
         ISegment indentationSegment = TextUtilities.GetWhitespaceAfter(document, previousLine.Offset);
         string indentation = document.GetText(indentationSegment);
         if (Program.OptionsObject.Editor_AgressiveIndentation)
         {
             string currentLineTextTrimmed = (document.GetText(line)).Trim();
             string lastLineTextTrimmed = (document.GetText(previousLine)).Trim();
             char currentLineFirstNonWhitespaceChar = ' ';
             if (currentLineTextTrimmed.Length > 0)
             {
                 currentLineFirstNonWhitespaceChar = currentLineTextTrimmed[0];
             }
             char lastLineLastNonWhitespaceChar = ' ';
             if (lastLineTextTrimmed.Length > 0)
             {
                 lastLineLastNonWhitespaceChar = lastLineTextTrimmed[lastLineTextTrimmed.Length - 1];
             }
             if (lastLineLastNonWhitespaceChar == '{' && currentLineFirstNonWhitespaceChar != '}')
             {
                 indentation += "\t";
             }
             else if (currentLineFirstNonWhitespaceChar == '}')
             {
                 if (indentation.Length > 0)
                 {
                     indentation = indentation.Substring(0, indentation.Length - 1);
                 }
                 else
                 {
                     indentation = string.Empty;
                 }
             }
             /*if (lastLineTextTrimmed == "{" && currentLineTextTrimmed != "}")
             {
                 indentation += "\t";
             }
             else if (currentLineTextTrimmed == "}")
             {
                 if (indentation.Length > 0)
                 {
                     indentation = indentation.Substring(0, indentation.Length - 1);
                 }
                 else
                 {
                     indentation = string.Empty;
                 }
             }*/
         }
         indentationSegment = TextUtilities.GetWhitespaceAfter(document, line.Offset);
         document.Replace(indentationSegment, indentation);
     }
 }
        /// <inheritdoc cref="IIndentationStrategy.IndentLine"/>
        public override void IndentLine(TextDocument document, DocumentLine line)
        {
            if (line?.PreviousLine == null)
                return;

            var prevLine = document.GetText(line.PreviousLine.Offset, line.PreviousLine.Length);
            var curLine = document.GetText(line.Offset, line.Length);
            int prev = CalcSpace(prevLine);

            var previousIsComment = prevLine.TrimStart().StartsWith("--", StringComparison.CurrentCulture);

            if (Regex.IsMatch(curLine, patternFull) && !previousIsComment)
            {
                var ind = new string(' ', prev);
                document.Insert(line.Offset, ind);
            }
            else if (Regex.IsMatch(prevLine, patternStart) && !previousIsComment)
            {
                var ind = new string(' ', prev + indent_space_count);
                document.Insert(line.Offset, ind);

                var found = false;
                for (int i = line.LineNumber; i < document.LineCount; ++i)
                {
                    var text = document.GetText(document.Lines[i].Offset, document.Lines[i].Length);

                    if (string.IsNullOrWhiteSpace(text) || text.TrimStart().StartsWith("--", StringComparison.CurrentCulture))
                        continue;

                    var sps = CalcSpace(text);

                    if (sps == prev && Regex.IsMatch(text, patternEnd))
                        found = true;
                }

                if (!found)
                {
                    var ntext = Environment.NewLine + new string(' ', prev) + "end";
                    var point = textEditor.SelectionStart;
                    document.Insert(line.Offset + ind.Length, ntext);
                    textEditor.SelectionStart = point;
                }
            }
            else
            {
                var ind = new string(' ', prev);
                if (line != null)
                    document.Insert(line.Offset, ind);
            }
        }
		/// <summary>
		/// Sets the indentation for the specified line.
		/// Usually this is constructed from the indentation of the previous line.
		/// </summary>
		/// <param name="document"></param>
		/// <param name="line"></param>
		public void IndentLine(TextDocument document, DocumentLine line)
		{
			var pLine = line.PreviousLine;
			if (pLine != null)
			{
				var segment = TextUtilities.GetWhitespaceAfter(document, pLine.Offset);
				var indentation = document.GetText(segment);

				var amount = HtmlParser.CountUnclosedTags(document.GetText(pLine));
				if (amount > 0)
					indentation += new string('\t', amount);

				document.Replace(TextUtilities.GetWhitespaceAfter(document, line.Offset), indentation);
			}
		}
Esempio n. 4
0
		public static Block ConvertTextDocumentToBlock(TextDocument document, IHighlighter highlighter)
		{
			if (document == null)
				throw new ArgumentNullException("document");
//			Table table = new Table();
//			table.Columns.Add(new TableColumn { Width = GridLength.Auto });
//			table.Columns.Add(new TableColumn { Width = new GridLength(1, GridUnitType.Star) });
//			TableRowGroup trg = new TableRowGroup();
//			table.RowGroups.Add(trg);
			Paragraph p = new Paragraph();
			foreach (DocumentLine line in document.Lines) {
				int lineNumber = line.LineNumber;
//				TableRow row = new TableRow();
//				trg.Rows.Add(row);
//				row.Cells.Add(new TableCell(new Paragraph(new Run(lineNumber.ToString()))) { TextAlignment = TextAlignment.Right });
				HighlightedInlineBuilder inlineBuilder = new HighlightedInlineBuilder(document.GetText(line));
				if (highlighter != null) {
					HighlightedLine highlightedLine = highlighter.HighlightLine(lineNumber);
					int lineStartOffset = line.Offset;
					foreach (HighlightedSection section in highlightedLine.Sections)
						inlineBuilder.SetHighlighting(section.Offset - lineStartOffset, section.Length, section.Color);
				}
//				Paragraph p = new Paragraph();
//				row.Cells.Add(new TableCell(p));
				p.Inlines.AddRange(inlineBuilder.CreateRuns());
				p.Inlines.Add(new LineBreak());
			}
			return p;
		}
Esempio n. 5
0
        static DToken SearchBackward(TextDocument doc, int caretOffset, CodeLocation caret,out DToken lastToken)
        {
            var ttp = doc.GetText(0, caretOffset);
            var sr = new StringReader(ttp);
            var lexer = new Lexer(sr);
            lexer.NextToken();

            var stk=new Stack<DToken>();

            while (lexer.LookAhead.Kind!=DTokens.EOF)
            {
                if (lexer.LookAhead.Kind == DTokens.OpenParenthesis || lexer.LookAhead.Kind==DTokens.OpenSquareBracket || lexer.LookAhead.Kind==DTokens.OpenCurlyBrace)
                    stk.Push(lexer.LookAhead);

                else if (lexer.LookAhead.Kind == DTokens.CloseParenthesis || lexer.LookAhead.Kind == DTokens.CloseSquareBracket || lexer.LookAhead.Kind == DTokens.CloseCurlyBrace)
                {
                    if (stk.Peek().Kind == getOppositeBracketToken( lexer.LookAhead.Kind))
                        stk.Pop();
                }

                lexer.NextToken();
            }

            lastToken = lexer.CurrentToken;

            sr.Close();
            lexer.Dispose();

            if (stk.Count < 1)
                return null;

            return stk.Pop();
        }
 protected override IEnumerable<NewFolding> CreateNewFoldings(TextDocument document)
 {
     string name = null;
     int? startOffset = null;
     int? endOffset = null;
     foreach (var line in document.Lines)
     {
         var text = document.GetText(line);
         var isFunction = _functionRegex.IsMatch(text);
         if (isFunction)
         {
             if (startOffset != null && endOffset != null)
             {
                 yield return new NewFolding { StartOffset = startOffset.Value, EndOffset = endOffset.Value, Name = name, IsDefinition = true };
             }
             name = text;
             startOffset = line.Offset;
             endOffset = null;
             continue;
         }
         if (startOffset == null || string.IsNullOrWhiteSpace(text)) continue;
         var firstChar = text.First(c => !char.IsWhiteSpace(c));
         if (!firstChar.Equals(Gherkin.Comment) && !firstChar.Equals(Gherkin.Tag)) endOffset = line.EndOffset;
     }
     if (startOffset != null && endOffset != null)
     {
         yield return new NewFolding { StartOffset = startOffset.Value, EndOffset = endOffset.Value, Name = name, IsDefinition = true };
     }
 }
Esempio n. 7
0
        public void IndentLine(ICSharpCode.AvalonEdit.Document.TextDocument document, DocumentLine line, bool TakeCaret)
        {
            if (line.PreviousLine == null)
            {
                return;
            }

            if (!DSettings.Instance.EnableSmartIndentation)
            {
                var t = document.GetText(line);
                int c = 0;
                for (; c < t.Length && (t[c] == ' ' || t[c] == '\t'); c++)
                {
                    ;
                }

                RawlyIndentLine(t.Length == 0 ? string.Empty : t.Substring(0, c + 1), document, line);

                return;
            }

            var tr        = document.CreateReader();
            var newIndent = D_Parser.Formatting.Indent.IndentEngineWrapper.CalculateIndent(tr, line.LineNumber, dEditor.Editor.Options.ConvertTabsToSpaces, dEditor.Editor.Options.IndentationSize);

            tr.Close();

            RawlyIndentLine(newIndent, document, line);
        }
Esempio n. 8
0
 bool IsBracketOnly(TextDocument document, DocumentLine documentLine)
 {
     var 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);
 }
		/// <inheritdoc/>
		public override string GetText(TextDocument document)
		{
			StringBuilder b = new StringBuilder();
			foreach (ISegment s in this.Segments) {
				if (b.Length > 0)
					b.AppendLine();
				b.Append(document.GetText(s));
			}
			return b.ToString();
		}
Esempio n. 10
0
        private Match FindMatch(int startOffset)
        {
            // fetch the end offset of the VisualLine being generated
            int endOffset = CurrentContext.VisualLine.LastDocumentLine.EndOffset;

            ICSharpCode.AvalonEdit.Document.TextDocument document = CurrentContext.Document;
            string relevantText = document.GetText(startOffset, endOffset - startOffset);

            return(imageRegex.Match(relevantText));
        }
Esempio n. 11
0
        /// <summary>
        /// Create <see cref="NewFolding"/>s for the specified document.
        /// </summary>
        public IEnumerable<NewFolding> CreateNewFoldings(TextDocument document, out int firstErrorOffset)
        {
            firstErrorOffset = -1;

            var foldings = new List<NewFolding>();
            var stack = new Stack<int>();

            foreach (var line in document.Lines)
            {
                var text = document.GetText(line.Offset, line.Length);

                // комментарии пропускаем
                if (commentPattern.IsMatch(text))
                    continue;

                foreach (Match match in startPattern.Matches(text))
                {
                    var element = match.Groups["start"];
                    if (element.Success)
                    {
                        stack.Push(line.EndOffset);
                    }
                }

                foreach (Match match in endPattern.Matches(text))
                {
                    var element = match.Groups["end"];
                    if (element.Success)
                    {
                        if (stack.Count > 0)
                        {
                            var first = stack.Pop();
                            var folding = new NewFolding(first, line.EndOffset);
                            foldings.Add(folding);
                        }
                        else
                        {
                            firstErrorOffset = line.Offset;
                        }
                    }
                }
            }

            if (stack.Count > 0)
            {
                firstErrorOffset = stack.Pop();
            }

            foldings.Sort((a, b) => a.StartOffset.CompareTo(b.StartOffset));
            return foldings;
        }
		/// <inheritdoc/>
		public virtual void IndentLine(TextDocument document, DocumentLine line)
		{
			if (document == null)
				throw new ArgumentNullException("document");
			if (line == null)
				throw new ArgumentNullException("line");
			DocumentLine previousLine = line.PreviousLine;
			if (previousLine != null) {
				ISegment indentationSegment = TextUtilities.GetWhitespaceAfter(document, previousLine.Offset);
				string indentation = document.GetText(indentationSegment);
				// copy indentation to line
				indentationSegment = TextUtilities.GetWhitespaceAfter(document, line.Offset);
				document.Replace(indentationSegment, indentation);
			}
		}
        /// <inheritdoc/>
        public virtual void IndentLine(TextDocument document, DocumentLine line)
        {
            if (document == null)
                throw new ArgumentNullException(nameof(document));
            if (line == null)
                throw new ArgumentNullException(nameof(line));

            if (line.PreviousLine != null)
            {
                var indentationSegment = TextUtilities.GetWhitespaceAfter(document, line.PreviousLine.Offset);
                var indentation = document.GetText(indentationSegment);
                // copy indentation to line
                indentationSegment = TextUtilities.GetWhitespaceAfter(document, line.Offset);

                document.Replace(indentationSegment, indentation);
            }
        }
		/// <inheritdoc/>
		public virtual void IndentLine(TextDocument document, DocumentLine line)
		{
			if (document == null)
				throw new ArgumentNullException("document");
			if (line == null)
				throw new ArgumentNullException("line");
			DocumentLine previousLine = line.PreviousLine;
			if (previousLine != null) {
				ISegment indentationSegment = TextUtilities.GetWhitespaceAfter(document, previousLine.Offset);
				string indentation = document.GetText(indentationSegment);
				// copy indentation to line
				indentationSegment = TextUtilities.GetWhitespaceAfter(document, line.Offset);
				document.Replace(indentationSegment.Offset, indentationSegment.Length, indentation,
				                 OffsetChangeMappingType.RemoveAndInsert);
				// OffsetChangeMappingType.RemoveAndInsert guarantees the caret moves behind the new indentation.
			}
		}
Esempio n. 15
0
        private void codeEditor_TextEntered(object sender, TextCompositionEventArgs e)
        {
            if (e.Text == ".")
            {
                ICSharpCode.AvalonEdit.Editing.TextArea      area = (sender as ICSharpCode.AvalonEdit.Editing.TextArea);
                ICSharpCode.AvalonEdit.Document.TextDocument doc  = area.Document;
                int startoff = area.Caret.Offset - 1;
                int off      = area.Caret.Offset - 2;
                while (true)
                {
                    char o = doc.GetCharAt(off);
                    if (!char.IsLetter(o))
                    {
                        break;
                    }
                    if (off == 0)
                    {
                        break;
                    }
                    off--;
                }
                string prevToken = doc.GetText(off, startoff - off);

                // Open code completion after the user has pressed dot:
                completionWindow        = new CompletionWindow(CodeEditor.TextArea);
                completionWindow.Margin = new Thickness(0);
                IList <ICompletionData> data = completionWindow.CompletionList.CompletionData;
                try
                {
                    List <string> items = CompletionDatabase.completionDatabase[prevToken];
                    foreach (string item in items)
                    {
                        data.Add(new CompletionData(item));
                    }
                    completionWindow.Show();
                    completionWindow.Closed += delegate
                    {
                        completionWindow = null;
                    };
                }catch (Exception)
                {
                }
            }
        }
Esempio n. 16
0
        public void IndentLine(TextDocument document, DocumentLine line, bool TakeCaret)
        {
            if (line.PreviousLine == null)
                return;

            if (!DSettings.Instance.EnableSmartIndentation)
            {
                var prevIndent = ReadRawLineIndentation(document.GetText(line));

                RawlyIndentLine(prevIndent, document, line);

                return;
            }

            var tr=document.CreateReader();
            var block = CalculateIndentation(tr, line.LineNumber);
            tr.Close();

            RawlyIndentLine(block != null ? block.GetLineIndentation(line.LineNumber) : 0, document, line);
        }
Esempio n. 17
0
        public void GetCompletions(TextDocument doc, int Offset, IList<ICompletionData> data)
        {    
  
            // match only last N chars
            int N = Math.Min(Offset, 200);
            string s = doc.GetText(Offset - N, N);

            foreach (CodeEnvironment ee in envs)
            {
                if ( ee.MatchEnv(s) )
                {
                    foreach (MyCompletionData snipp in ee.snippets)
                    {
                        data.Add(snipp);
                    }
                }
            }
    

            //data.Add(new MyCompletionData("draw"));
            //data.Add(new MyCompletionData("fill"));
            //data.Add(new MyCompletionData("minimum size"));
        }
Esempio n. 18
0
 internal override string FoldTitle(FoldingSection section, TextDocument doc)
 {
     var array = Regex.Split(section.Title, "æ");
     var offset = section.StartOffset + array[0].Length;
     var length = section.Length - (array[0].Length + array[1].Length);
     return doc.GetText(offset, length);
 }
Esempio n. 19
0
        /// <summary>
        /// Marks the region that starts at the given offset.
        /// </summary>
        /// <param name="document">The document.</param>
        /// <param name="offset">The offset.</param>
        /// <param name="folds">The fold markers.</param>
        /// <returns>The index of the next character after the region.</returns>
        private static int MarkRegion(TextDocument document, int offset, List<NewFolding> folds)
        {
            if (offset >= document.TextLength)
                return offset;

            if (document.GetCharAt(offset) == '#')
            {
                int startOffset = offset;
                offset++;
                string word = TextUtilities.GetIdentifierAt(document, offset);
                if (word == "region")
                {
                    offset += "region".Length;

                    // Find label
                    var line = document.GetLineByOffset(offset);
                    int lineEnd = line.Offset + line.Length;
                    int labelLength = lineEnd - offset;
                    string label = document.GetText(offset, labelLength);
                    label = label.Trim();
                    if (label.Length == 0)
                        label = "#region";

                    // Find and mark subregions
                    offset = FindAndMarkRegions(document, lineEnd, folds);

                    if (offset <= document.TextLength)
                    {
                        AddFold(document, folds, startOffset, offset, label);
                        offset++;
                    }
                }
            }
            else
            {
                offset++;
            }
            return offset;
        }
Esempio n. 20
0
        /// <summary>
        /// Gets the line of the document as <see cref="string"/>.
        /// </summary>
        /// <param name="document">The document.</param>
        /// <param name="lineNumber">The line number.</param>
        /// <returns>The line as <see cref="string"/>.</returns>
        internal static string GetLineAsString(this TextDocument document, int lineNumber)
        {
            var line = document.GetLineByNumber(lineNumber);

            return(document.GetText(line));
        }
Esempio n. 21
0
        public void GetCompletions(TextDocument doc, int Offset, IList<ICompletionData> data)
        {    
  
            // match only last N chars
            int N = Math.Min(Offset, 200);
            string s = doc.GetText(Offset - N, N);

            foreach (CodeEnvironment ee in envs)
            {
                if ( ee.MatchEnv(s) )
                {
                    foreach (MyCompletionData snipp in ee.snippets)
                    {
                        data.Add(snipp);
                    }

                    if (ee.ID == DynamicSnippetsEnv && DynamicSnippets != null)
                    {
                        foreach (string snipp in DynamicSnippets)
                        {
                            data.Add(new MyCompletionData(snipp, null));
                        }
                    }
                }
            }

        }
Esempio n. 22
0
        /// <summary>
        /// Gets the expression before a given offset.
        /// </summary>
        /// <param name="document">The document.</param>
        /// <param name="initialOffset">The initial offset.</param>
        /// <returns>The expression.</returns>
        /// <remarks>
        /// This method returns the expression before a specified offset.
        /// That method is used in code completion to determine the expression before
        /// the caret. The expression can be passed to a parser to resolve the type
        /// or similar.
        /// </remarks>
        internal static string GetExpressionBeforeOffset(TextDocument document, int initialOffset)
        {
            int offset = initialOffset;

            while (offset - 1 > 0)
            {
                switch (document.GetCharAt(offset - 1))
                {
                case '\n':
                case '\r':
                case '}':
                    goto done;

                //offset = FindOpeningBracket(document, offset - 2, '{','}');
                //break;
                case ']':
                    offset = FindOpeningBracket(document, offset - 2, '[', ']');
                    break;

                case ')':
                    offset = FindOpeningBracket(document, offset - 2, '(', ')');
                    break;

                case '.':
                    --offset;
                    break;

                case '"':
                    if (offset < initialOffset - 1)
                    {
                        return(null);
                    }
                    return("\"\"");

                case '\'':
                    if (offset < initialOffset - 1)
                    {
                        return(null);
                    }
                    return("'a'");

                case '>':
                    if (document.GetCharAt(offset - 2) == '-')
                    {
                        offset -= 2;
                        break;
                    }
                    goto done;

                default:
                    if (char.IsWhiteSpace(document.GetCharAt(offset - 1)))
                    {
                        --offset;
                        break;
                    }
                    int start = offset - 1;
                    if (!IsIdentifierPart(document.GetCharAt(start)))
                    {
                        goto done;
                    }

                    while (start > 0 && IsIdentifierPart(document.GetCharAt(start - 1)))
                    {
                        --start;
                    }
                    string word = document.GetText(start, offset - start).Trim();
                    switch (word)
                    {
                    case "ref":
                    case "out":
                    case "in":
                    case "return":
                    case "throw":
                    case "case":
                        goto done;
                    }

                    if (word.Length > 0 && !IsIdentifierPart(word[0]))
                    {
                        goto done;
                    }
                    offset = start;
                    break;
                }
            }
done:
            // simple exit fails when : is inside comment line or any other character
            // we have to check if we got several ids in resulting line, which usually happens when
            // id. is typed on next line after comment one
            // Would be better if lexer would parse properly such expressions. However this will cause
            // modifications in this area too - to get full comment line and remove it afterwards
            if (offset < 0)
            {
                return(string.Empty);
            }

            string resText = document.GetText(offset, initialOffset - offset).Trim();
            int    pos     = resText.LastIndexOf('\n');

            if (pos >= 0)
            {
                offset += pos + 1;
                // whitespaces and tabs, which might be inside, will be skipped by trim below
            }

            string expression = document.GetText(offset, initialOffset - offset).Trim();

            return(expression);
        }
Esempio n. 23
0
 private bool CommentAtBeginOfLine(TextDocument document, DocumentLine documentLine)
 {
     var text = document.GetText(documentLine).TrimStart(Whitespaces.ToArray());
     if (string.IsNullOrEmpty(text))
     {
         return false;
     }
     if (!AllowMultipleComments && text.StartsWith(CommentMarker))
     {
         return false;
     }
     document.Insert(documentLine.Offset, CommentMarker);
     return true;
 }
Esempio n. 24
0
		/// <summary>
		/// Gets the selected text.
		/// </summary>
		public virtual string GetText(TextDocument document)
		{
			if (document == null)
				throw new ArgumentNullException("document");
			StringBuilder b = null;
			string text = null;
			foreach (ISegment s in Segments) {
				if (text != null) {
					if (b == null)
						b = new StringBuilder(text);
					else
						b.Append(text);
				}
				text = document.GetText(s);
			}
			if (b != null) {
				if (text != null) b.Append(text);
				return b.ToString();
			} else {
				return text ?? string.Empty;
			}
		}
Esempio n. 25
0
        /// <summary>
        /// Converts a TextDocument to Block.
        /// </summary>
        static Block ConvertTextDocumentToBlock(TextDocument document, IHighlighter highlighter)
        {
            // ref.:  http://community.sharpdevelop.net/forums/t/12012.aspx
              if (document == null)
            throw new ArgumentNullException("document");

              Paragraph p = new Paragraph();

              foreach (DocumentLine line in document.Lines)
              {
            int lineNumber = line.LineNumber;

            HighlightedInlineBuilder inlineBuilder = new HighlightedInlineBuilder(document.GetText(line));

            if (highlighter != null)
            {
              HighlightedLine highlightedLine = highlighter.HighlightLine(lineNumber);

              int lineStartOffset = line.Offset;

              foreach (HighlightedSection section in highlightedLine.Sections)
            inlineBuilder.SetHighlighting(section.Offset - lineStartOffset, section.Length, section.Color);
            }

            p.Inlines.AddRange(inlineBuilder.CreateRuns());
            p.Inlines.Add(new LineBreak());
              }

              return p;
        }
Esempio n. 26
0
 /// <summary>
 /// Part of the text between start offset and end offset (included),
 /// (first char at index 0 at the beginning of document)
 /// </summary>
 public string TextSegment(int startOffset, int endOffset)
 {
     return(_avalonEditTextDocument.GetText(startOffset, endOffset - startOffset + 1));
 }
Esempio n. 27
0
        public static TextReplaceBlockRegion FindSelectedStartCommentRegion(string commentStart,
                                                                        TextDocument document,
                                                                        string selectedText,
                                                                        int selectionStart,
                                                                        int selectionLength)
        {
            if (document == null)
            return null;

              ////if (document.TextLength == 0)
              ////  return null;

              // Find start of comment in selected text.
              int commentStartOffset = selectedText.IndexOf(commentStart);
              if (commentStartOffset >= 0)
            commentStartOffset += selectionStart;

              // Find start of comment before or partially inside the selected text.
              if (commentStartOffset == -1)
              {
            int offset = selectionStart + selectionLength + commentStart.Length - 1;
            if (offset > document.TextLength)
              offset = document.TextLength;

            string text = document.GetText(0, offset);
            commentStartOffset = text.LastIndexOf(commentStart);
              }

              if (commentStartOffset != -1)
            return new TextReplaceBlockRegion(commentStart, string.Empty, commentStartOffset, -1);

              return null;
        }
Esempio n. 28
0
        /// <summary>
        /// Search in the current selection and before/after the current selection to determine
        /// whether a start/end comment match can be found there. Return the matched positions
        /// for uncommentin if so.
        /// 
        /// This can include  a position before the current selection and a position at the end
        /// of the current selection if the user has partially selected a commented area.
        /// </summary>
        /// <param name="commentStart"></param>
        /// <param name="commentEnd"></param>
        /// <param name="document"></param>
        /// <param name="selectedText"></param>
        /// <param name="selectionLength"></param>
        /// <param name="selectionStart"></param>
        /// <returns></returns>
        public static TextReplaceBlockRegion FindSelectedCommentRegion(string commentStart,
                                                                   string commentEnd,
                                                                   TextDocument document,
                                                                   string selectedText,
                                                                   int selectionStart,
                                                                   int selectionLength
                                                                   )
        {
            if (document == null)
            return null;

              ////if (document.TextLength == 0)
              ////  return null;

              // Find start of comment in selected text.
              int commentEndOffset = -1;

              int commentStartOffset = selectedText.IndexOf(commentStart);
              if (commentStartOffset >= 0)
            commentStartOffset += selectionStart;

              // Find end of comment in selected text.
              if (commentStartOffset >= 0)
            commentEndOffset = selectedText.IndexOf(commentEnd, commentStartOffset + commentStart.Length - selectionStart);
              else
            commentEndOffset = selectedText.IndexOf(commentEnd);

              if (commentEndOffset >= 0)
            commentEndOffset += selectionStart;

              // Find start of comment before or partially inside the selected text.
              int commentEndBeforeStartOffset = -1;
              if (commentStartOffset == -1)
              {
            int offset = selectionStart + selectionLength + commentStart.Length - 1;
            if (offset > document.TextLength)
              offset = document.TextLength;

            string text = document.GetText(0, offset);
            commentStartOffset = text.LastIndexOf(commentStart);
            if (commentStartOffset >= 0)
            {
              // Find end of comment before comment start.
              commentEndBeforeStartOffset = text.IndexOf(commentEnd, commentStartOffset, selectionStart - commentStartOffset);

              if (commentEndBeforeStartOffset > commentStartOffset)
            commentStartOffset = -1;
            }
              }

              // Find end of comment after or partially after the selected text.
              if (commentEndOffset == -1)
              {
            int offset = selectionStart + 1 - commentEnd.Length;
            if (offset < 0)
              offset = selectionStart;

            string text = document.GetText(offset, document.TextLength - offset);

            commentEndOffset = text.IndexOf(commentEnd);

            if (commentEndOffset >= 0)
              commentEndOffset += offset;
              }

              if (commentStartOffset != -1 && commentEndOffset != -1)
            return new TextReplaceBlockRegion(commentStart, commentEnd, commentStartOffset, commentEndOffset);

              return null;
        }
Esempio n. 29
0
        public static TextReplaceBlockRegion FindSelectedEndCommentRegion(string commentEnd,
                                                                      TextDocument document,
                                                                      string selectedText,
                                                                      int selectionStart)
        {
            if (document == null)
            return null;

              ////if (document.TextLength == 0)
              ////  return null;

              // Find start of comment in selected text.
              int commentEndOffset = -1;

              commentEndOffset = selectedText.IndexOf(commentEnd);

              if (commentEndOffset >= 0)
            commentEndOffset += selectionStart;

              // Find end of comment after or partially after the selected text.
              if (commentEndOffset == -1)
              {
            int offset = selectionStart + 1 - commentEnd.Length;
            if (offset < 0)
              offset = selectionStart;

            string text = document.GetText(offset, document.TextLength - offset);

            commentEndOffset = text.IndexOf(commentEnd);

            if (commentEndOffset >= 0)
              commentEndOffset += offset;
              }

              if (commentEndOffset != -1)
            return new TextReplaceBlockRegion(string.Empty, commentEnd, -1, commentEndOffset);

              return null;
        }
        public override IEnumerable<NewFolding> CreateNewFoldings(TextDocument document, out int firstErrorOffset)
        {
            firstErrorOffset = -1;
            
           var folds =  new List<NewFolding>();

            
            linenr = 1;
            prev = false;
            startfold = 0; endfold = 0;
            n = 0;
            var l = document.GetLineByNumber(linenr);
           
            int sep = 0;
           
            do
            {
                int N = l.TotalLength;
                var line = document.GetText(n, N);
                var M = r.Match(line);
                if (M.Success)
                {
                    if (!prev)
                    {
                        prev = true;
                        startfold = n;
                        
                    }
                    endfold = n + l.Length;   

                }
                else
                {

                    if (prev)
                        folds.Add(lastfold=new NewFolding{ StartOffset=startfold, EndOffset= endfold, Name="FileSync Complete", DefaultClosed=true});
                    prev = false;
                    
                   
                }



                linenr++;
                n += N;
            }
            while ((l = l.NextLine) != null);


            return folds;
        }
Esempio n. 31
0
		public static HighlightedInlineBuilder CreateInlineBuilder(Location startPosition, Location endPosition, TextDocument document, IHighlighter highlighter)
		{
			if (startPosition.Line >= 1 && startPosition.Line <= document.LineCount) {
				var matchedLine = document.GetLineByNumber(startPosition.Line);
				HighlightedInlineBuilder inlineBuilder = new HighlightedInlineBuilder(document.GetText(matchedLine));
				if (highlighter != null) {
					HighlightedLine highlightedLine = highlighter.HighlightLine(startPosition.Line);
					int startOffset = highlightedLine.DocumentLine.Offset;
					// copy only the foreground color
					foreach (HighlightedSection section in highlightedLine.Sections) {
						if (section.Color.Foreground != null) {
							inlineBuilder.SetForeground(section.Offset - startOffset, section.Length, section.Color.Foreground.GetBrush(null));
						}
					}
				}
				
				// now highlight the match in bold
				if (startPosition.Column >= 1) {
					if (endPosition.Line == startPosition.Line && endPosition.Column > startPosition.Column) {
						// subtract one from the column to get the offset inside the line's text
						int startOffset = startPosition.Column - 1;
						int endOffset = Math.Min(inlineBuilder.Text.Length, endPosition.Column - 1);
						inlineBuilder.SetFontWeight(startOffset, endOffset - startOffset, FontWeights.Bold);
					}
				}
				return inlineBuilder;
			}
			return null;
		}
 public void GetNameMatch(TextDocument aDoc, int line, string text, ref List<string> suggestions)
 {
     int depth = scanner_.GetBraceDepth(line);
     do {
         string[] lineCodes = aDoc.GetText(aDoc.Lines[line]).Split(BREAKCHARS, StringSplitOptions.RemoveEmptyEntries);
         foreach (string lineCode in lineCodes) {
             if (lineCode.Length > 3 && lineCode.StartsWith(text)) { //contains our current text
                 int startidx = lineCode.IndexOf(text);
                 if (!suggestions.Contains(lineCode))
                     suggestions.Add(lineCode);
             }
         }
         --line;
     } while (depth > 0 && line > 0); //function depth may be on the first 0 scanning up, same with class def
 }
Esempio n. 33
0
        public static string GetWordUnderMouse(ICSharpCode.AvalonEdit.Document.TextDocument document, TextViewPosition position)
        {
            string wordHovered = string.Empty;

            var line   = position.Line;
            var column = position.Column - 1;

            var offset = document.GetOffset(line, column);

            if (offset >= document.TextLength)
            {
                offset--;
            }

            var textAtOffset = document.GetText(offset, 1);

            // Get text backward of the mouse position, until the first space
            while (!string.IsNullOrWhiteSpace(textAtOffset))
            {
                wordHovered = textAtOffset + wordHovered;

                offset--;

                if (offset < 0)
                {
                    break;
                }

                textAtOffset = document.GetText(offset, 1);

                if (textAtOffset == "(" || textAtOffset == ")" || textAtOffset == "<" || textAtOffset == ">" || textAtOffset == "," || textAtOffset == ";")
                {
                    break;
                }
            }

            // Get text forward the mouse position, until the first space
            offset = document.GetOffset(line, column);
            if (offset < document.TextLength - 1)
            {
                offset++;

                textAtOffset = document.GetText(offset, 1);

                while (!string.IsNullOrWhiteSpace(textAtOffset))
                {
                    wordHovered = wordHovered + textAtOffset;

                    offset++;

                    if (offset >= document.TextLength)
                    {
                        break;
                    }

                    textAtOffset = document.GetText(offset, 1);

                    if (textAtOffset == "(" || textAtOffset == ")" || textAtOffset == "<" || textAtOffset == ">" || textAtOffset == "," || textAtOffset == ";")
                    {
                        break;
                    }
                }
            }

            return(wordHovered);
        }
        public BaseTypeInfo GetClassType(TextDocument aDoc, int line, string text)
        {
            if (globals_ == null)
                return null;
            --line; //subtract one for how AvalonEdit stores text versus reports its position
            int startLine = line;
            if (text.Equals("this")) { //easy case
                int depth = scanner_.GetBraceDepth(line);
                do {
                    string lineCode = aDoc.GetText(aDoc.Lines[line]);
                    if (lineCode.Contains("class ")) {
                        string[] parts = lineCode.Trim().Split(SPACECHAR, StringSplitOptions.RemoveEmptyEntries);
                        if (parts[0].Equals("shared") && globals_.ContainsTypeInfo(parts[2]))
                            return globals_.GetTypeInfo(parts[2]);
                        else if (globals_.ContainsTypeInfo(parts[1]))
                            return globals_.GetTypeInfo(parts[1]);
                        else
                            break;
                    }
                    depth = scanner_.GetBraceDepth(line);
                    --line;
                } while (depth > 0 && line > 0); //class def may be on last line

                //unkonwn class
                int curDepth = depth;
                string[] nameparts = aDoc.GetText(aDoc.Lines[line]).Trim().Split(SPACECHAR, StringSplitOptions.RemoveEmptyEntries);
                string className = "";
                if (nameparts[0].Equals("shared"))
                    className = nameparts[2];
                else if (nameparts[0].Equals("abstract"))
                    className = nameparts[2];
                else
                    className = nameparts[1];
                //TODO get baseclasses
                if (globals_.ContainsTypeInfo(className))
                    return globals_.GetTypeInfo(className);
                TypeInfo tempType = new TypeInfo() { Name = className };
                ++line;
                do {
                    depth = scanner_.GetBraceDepth(line);
                    if (depth == curDepth+1) {
                        string lineCode = aDoc.GetText(aDoc.Lines[line]);
                        string[] words = aDoc.GetText(aDoc.Lines[line]).Trim().Split(SPACECHAR, StringSplitOptions.RemoveEmptyEntries);
                        if (words != null && words.Length > 1) {
                            if (words[1].Contains("(")) { //function
                                if (globals_.ContainsTypeInfo(words[0])) {

                                }
                            } else {
                                string rettype = FilterTypeName(words[0]);
                                string propname = FilterTypeName(words[1]);
                                if (globals_.ContainsTypeInfo(rettype)) {
                                    tempType.Properties[propname] = globals_.GetTypeInfo(rettype);
                                }
                            }
                        }
                    }
                    ++line;
                } while (line < startLine);
                return tempType;
            }

            //SCOPE block for depth
            {
                int depth = scanner_.GetBraceDepth(line);
                bool indexType = false;
                if (text.Contains('[')) {
                    indexType = true;
                    text = text.Substring(0, text.IndexOf('['));
                }
                do {
                    string lineCode = aDoc.GetText(aDoc.Lines[line]).Trim();
                    if (lineCode.Contains(text)) {

                        // Prevent partial matches as false positives, ie. "sceneFile" passing as "scene"
                        string[] lineTokens = lineCode.Split(BREAKCHARS, StringSplitOptions.RemoveEmptyEntries);
                        if (!lineTokens.Contains(text))
                        {
                            --line;
                            depth = scanner_.GetBraceDepth(line);
                            continue;
                        }

                        int endidx = lineCode.IndexOf(text);
                        int idx = endidx;
                        bool okay = true;
                        bool hitSpace = false;
                        while (idx > 0) { //scan backwards to find the typename
                            if (!char.IsLetterOrDigit(lineCode[idx]) && !BACKSCAN_ALLOW.Contains(lineCode[idx])) {
                                okay = false;
                                ++idx;
                                break;
                            }
                            if (!hitSpace && lineCode[idx] == ' ')
                                hitSpace = true;
                            else if (lineCode[idx] == ' ')
                            {
                                break;
                            }
                            --idx;
                        }
                        if (idx < 0) idx = 0;
                        string substr = endidx - idx > 0 ? FilterTypeName(lineCode.Substring(idx, endidx - idx).Trim()) : "";
                        if (substr.Length > 0) { //not empty
                            if (substr.Contains(">")) {//TEMPLATE DEFINITION
                                try
                                {
                                    if (!indexType)
                                        substr = lineCode.Substring(0, lineCode.IndexOf('<'));
                                    else
                                    {
                                        int start = lineCode.IndexOf('<');
                                        int end = lineCode.IndexOf('>');
                                        substr = lineCode.Substring(start + 1, end - start - 1);
                                        substr = substr.Replace("@", "");
                                    }
                                }
                                catch (Exception) { /* silently eat */}
                            }
                            if (globals_.ContainsTypeInfo(substr)) {
                                //Found a class
                                if (indexType)
                                {
                                    TypeInfo ti = globals_.GetTypeInfo(substr);
                                    //HACK for Map types
                                    if (ti.Properties.ContainsKey("values"))
                                    {
                                        TypeInfo valueType = ti.Properties["values"];
                                        if (valueType is TemplateInst)
                                            return ((TemplateInst)valueType).WrappedType;
                                    }
                                }
                                return globals_.GetTypeInfo(substr);
                            } else if (substr.Contains(':'))
                            {
                                string[] words = substr.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
                                if (words.Length > 1 && globals_.ContainsNamespace(words[0]))
                                {
                                    Globals g = globals_;
                                    for (int i = 0; i < words.Length - 1; ++i)
                                    {
                                        g = globals_.GetNamespace(words[i]);
                                    }
                                    if (g.ContainsTypeInfo(words[words.Length - 1]))
                                        return g.GetTypeInfo(words[words.Length - 1]);
                                }
                            }
                        }
                    }
                    --line;
                    depth = scanner_.GetBraceDepth(line);
                } while (depth >= 0 && line > 0);
                return null;
            }
        }
Esempio n. 35
0
 private bool CommentAtBeginOfText(TextDocument document, DocumentLine documentLine)
 {
     var text = document.GetText(documentLine);
     if (string.IsNullOrEmpty(text))
     {
         return false;
     }
     if (!AllowMultipleComments && text.TrimStart(Whitespaces.ToArray()).StartsWith(commentMarker))
     {
         return false;
     }
     var num = documentLine.Offset;
     var text2 = text;
     var i = 0;
     while (i < text2.Length)
     {
         var letter = text2[i];
         if (IsWhitespace(letter))
         {
             num++;
             i++;
         }
         else
         {
             if (num >= documentLine.EndOffset)
             {
                 return false;
             }
             break;
         }
     }
     document.Insert(num, CommentMarker);
     return true;
 }
Esempio n. 36
0
		/// <summary>
		/// Gets the newline sequence used in the document at the specified line.
		/// </summary>
		public static string GetNewLineFromDocument(TextDocument document, int lineNumber)
		{
			DocumentLine line = document.GetLineByNumber(lineNumber);
			if (line.DelimiterLength == 0) {
				// at the end of the document, there's no line delimiter, so use the delimiter
				// from the previous line
				line = line.PreviousLine;
				if (line == null)
					return Environment.NewLine;
			}
			return document.GetText(line.Offset + line.Length, line.DelimiterLength);
		}
Esempio n. 37
0
 protected override IEnumerable<NewFolding> CreateNewFoldings(TextDocument document, out int firstErrorOffset)
 {
     var list = new List<NewFolding>();
     firstErrorOffset = -1;
     var stack = new Stack<DocumentLine>();
     var stack2 = new Stack<DocumentLine>();
     var flag = false;
     foreach (var current in document.Lines)
     {
         var input = document.GetText(current).ToLower().TrimEnd(new[]
         {
             ' ',
             '\t'
         }).TrimStart(new[]
         {
             ' ',
             '\t'
         });
         if (FoldFunctions && KrlRegularExpressions.DefLineRegex.IsMatch(input))
         {
             stack.Push(current);
             flag = true;
         }
         if (FoldFunctions && KrlRegularExpressions.EndDefLineRegex.IsMatch(input) && stack.Count > 0)
         {
             var endOffset = current.EndOffset;
             var documentLine = stack.Pop();
             var name = document.GetText(documentLine).TrimStart(new[]
             {
                 ' ',
                 '\t'
             }).TrimEnd(new[]
             {
                 ' ',
                 '\t'
             });
             list.Add(new NewFolding(documentLine.Offset, endOffset)
             {
                 Name = name
             });
             flag = false;
         }
         if (KrlRegularExpressions.FoldStartLineRegex.IsMatch(input) && (flag | !FoldFunctions))
         {
             stack2.Push(current);
         }
         if (KrlRegularExpressions.FoldEndLineRegex.IsMatch(input) && stack2.Count > 0 && (flag | !FoldFunctions))
         {
             var endOffset = current.EndOffset;
             var documentLine2 = stack2.Pop();
             var text = document.GetText(documentLine2).TrimStart(new[]
             {
                 ' ',
                 '\t'
             }).TrimEnd(new[]
             {
                 ' ',
                 '\t'
             }).ToUpper();
             text = text.Replace(";FOLD", string.Empty).TrimStart(new[]
             {
                 ' ',
                 '\t'
             });
             var num = text.IndexOf(';');
             if (num > 0)
             {
                 text = text.Remove(num);
             }
             list.Add(new NewFolding(documentLine2.Offset, endOffset)
             {
                 Name = text,
                 DefaultClosed = FoldsClosedByDefault
             });
         }
     }
     list.Sort((a, b) => a.StartOffset.CompareTo(b.StartOffset));
     return list;
 }