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();
        }
            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();
            }
Esempio n. 3
0
        /// <summary>
        /// Determines if the property is a so-called auto-implemented property.
        /// </summary>
        public static bool IsAutoImplemented(this IProperty property)
        {
            if (property == null)
            {
                throw new ArgumentNullException("property");
            }

            if (property.IsAbstract || property.DeclaringType.ClassType == ICSharpCode.SharpDevelop.Dom.ClassType.Interface)
            {
                return(false);
            }

            string fileName = property.CompilationUnit.FileName;

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

            IDocument document    = DocumentUtilitites.LoadDocumentFromBuffer(ParserService.GetParseableFileContent(fileName));
            bool      isAutomatic = false;

            if (property.CanGet)
            {
                if (property.GetterRegion.IsEmpty)
                {
                    isAutomatic = true;
                }
                else
                {
                    int getterStartOffset = document.PositionToOffset(property.GetterRegion.BeginLine, property.GetterRegion.BeginColumn);
                    int getterEndOffset   = document.PositionToOffset(property.GetterRegion.EndLine, property.GetterRegion.EndColumn);

                    string text = document.GetText(getterStartOffset, getterEndOffset - getterStartOffset)
                                  .Replace(" ", "").Replace("\t", "").Replace("\n", "").Replace("\r", "");

                    isAutomatic = text == "get;";
                }
            }

            if (property.CanSet)
            {
                if (property.SetterRegion.IsEmpty)
                {
                    isAutomatic |= true;
                }
                else
                {
                    int setterStartOffset = document.PositionToOffset(property.SetterRegion.BeginLine, property.SetterRegion.BeginColumn);
                    int setterEndOffset   = document.PositionToOffset(property.SetterRegion.EndLine, property.SetterRegion.EndColumn);

                    string text = document.GetText(setterStartOffset, setterEndOffset - setterStartOffset)
                                  .Replace(" ", "").Replace("\t", "").Replace("\n", "").Replace("\r", "");

                    isAutomatic |= text == "set;";
                }
            }

            return(isAutomatic);
        }
Esempio n. 4
0
        /// <summary>
        /// Indents the switch body by the same indent the whole snippet has and adds one TAB.
        /// </summary>
        string GetBodyIndent(IDocument document, int offset)
        {
            int    lineStart = document.GetLineForOffset(offset).Offset;
            string indent    = DocumentUtilitites.GetWhitespaceAfter(document, lineStart);

            return(indent);
        }
        public void Initialize(IDocument document)
        {
            if (changeList != null && changeList.Any())
            {
                return;
            }

            this.document     = document;
            this.textDocument = (TextDocument)document.GetService(typeof(TextDocument));
            this.changeList   = new CompressingTreeList <LineChangeInfo>((x, y) => x.Equals(y));

            Stream baseFileStream = GetBaseVersion();

            // TODO : update baseDocument on VCS actions
            if (baseFileStream != null)
            {
                // ReadAll() is taking care of closing the stream
                baseDocument = DocumentUtilitites.LoadReadOnlyDocumentFromBuffer(new StringTextBuffer(ReadAll(baseFileStream)));
            }
            else
            {
                if (baseDocument == null)
                {
                    // if the file is not under subversion, the document is the opened document
                    var doc = new TextDocument(textDocument.Text);
                    baseDocument = new AvalonEditDocumentAdapter(doc, null);
                }
            }

            SetupInitialFileState(false);

            this.textDocument.LineTrackers.Add(this);
            this.textDocument.UndoStack.PropertyChanged += UndoStackPropertyChanged;
        }
Esempio n. 6
0
        public static void ShowAsSearchResults(string title, List <Reference> list)
        {
            if (list == null)
            {
                return;
            }
            List <SearchResultMatch> results  = new List <SearchResultMatch>(list.Count);
            TextDocument             document = null;
            ITextBuffer        buffer         = null;
            FileName           fileName       = null;
            ISyntaxHighlighter highlighter    = null;

            foreach (Reference r in list)
            {
                var f = new FileName(r.FileName);
                if (document == null || !f.Equals(fileName))
                {
                    buffer      = ParserService.GetParseableFileContent(r.FileName);
                    document    = new TextDocument(DocumentUtilitites.GetTextSource(buffer));
                    fileName    = new FileName(r.FileName);
                    highlighter = EditorControlService.Instance.CreateHighlighter(new AvalonEditDocumentAdapter(document, null), fileName);
                }
                var start             = document.GetLocation(r.Offset).ToLocation();
                var end               = document.GetLocation(r.Offset + r.Length).ToLocation();
                var builder           = SearchResultsPad.CreateInlineBuilder(start, end, document, highlighter);
                SearchResultMatch res = new SearchResultMatch(fileName, start, end, r.Offset, r.Length, builder, highlighter.DefaultTextColor);
                results.Add(res);
            }
            SearchResultsPad.Instance.ShowSearchResults(title, results);
            SearchResultsPad.Instance.BringToFront();
        }
Esempio n. 7
0
        public void SimpleDocument()
        {
            string    text     = "Hello\nWorld!\r\n";
            IDocument document = DocumentUtilitites.LoadReadOnlyDocumentFromBuffer(new StringTextBuffer(text));

            Assert.AreEqual(text, document.Text);
            Assert.AreEqual(3, document.TotalNumberOfLines);

            Assert.AreEqual(0, document.GetLine(1).Offset);
            Assert.AreEqual(5, document.GetLine(1).EndOffset);
            Assert.AreEqual(5, document.GetLine(1).Length);
            Assert.AreEqual(6, document.GetLine(1).TotalLength);
            Assert.AreEqual(1, document.GetLine(1).DelimiterLength);
            Assert.AreEqual(1, document.GetLine(1).LineNumber);

            Assert.AreEqual(6, document.GetLine(2).Offset);
            Assert.AreEqual(12, document.GetLine(2).EndOffset);
            Assert.AreEqual(6, document.GetLine(2).Length);
            Assert.AreEqual(8, document.GetLine(2).TotalLength);
            Assert.AreEqual(2, document.GetLine(2).DelimiterLength);
            Assert.AreEqual(2, document.GetLine(2).LineNumber);

            Assert.AreEqual(14, document.GetLine(3).Offset);
            Assert.AreEqual(14, document.GetLine(3).EndOffset);
            Assert.AreEqual(0, document.GetLine(3).Length);
            Assert.AreEqual(0, document.GetLine(3).TotalLength);
            Assert.AreEqual(0, document.GetLine(3).DelimiterLength);
            Assert.AreEqual(3, document.GetLine(3).LineNumber);
        }
        static void ApplyToRange(ITextEditor editor, Stack <string> indentation, List <int> eols, int blockStart, int blockEnd, int selectionStart, int selectionEnd)
        {
            LoggingService.InfoFormatted("indenting line {0} to {1} with {2}", blockStart, blockEnd, (indentation.PeekOrDefault() ?? "").Length);

            int  nextEol      = -1;
            bool wasMultiLine = false;

            for (int i = blockStart; i <= blockEnd; i++)
            {
                IDocumentLine curLine    = editor.Document.GetLine(i);
                string        lineText   = curLine.Text.TrimStart();
                string        noComments = lineText.TrimComments().TrimEnd();

                // adjust indentation if the current line is not selected
                // lines between the selection will be aligned to the selected level
                if (i < selectionStart || i > selectionEnd)
                {
                    indentation.PopOrDefault();
                    indentation.Push(DocumentUtilitites.GetWhitespaceAfter(editor.Document, curLine.Offset));
                }

                // look for next eol if line is not empty
                // (the lexer does not produce eols for empty lines)
                if (!string.IsNullOrEmpty(noComments) && i >= nextEol)
                {
                    int search = eols.BinarySearch(i);
                    if (search < 0)
                    {
                        search = ~search;
                    }
                    nextEol = search < eols.Count ? eols[search] : i;
                }

                // remove indentation in last line of multiline array(, collection, object) initializers
                if (i == nextEol && wasMultiLine && noComments == "}")
                {
                    wasMultiLine = false;
                    Unindent(indentation);
                }

                // apply the indentation
                editor.Document.SmartReplaceLine(curLine, (indentation.PeekOrDefault() ?? "") + lineText);

                // indent line if it is ended by (implicit) line continuation
                if (i < nextEol && !wasMultiLine)
                {
                    wasMultiLine = true;
                    Indent(editor, indentation);
                }

                // unindent if this is the last line of a multiline statement
                if (i == nextEol && wasMultiLine)
                {
                    wasMultiLine = false;
                    Unindent(indentation);
                }
            }
        }
 /// <summary>
 /// Inserts the PInvoke signature at the current cursor position.
 /// </summary>
 /// <param name="textArea">The text editor.</param>
 /// <param name="signature">A PInvoke signature string.</param>
 public void Generate(ITextEditor editor, string signature)
 {
     using (editor.Document.OpenUndoGroup()) {
         int startLine = editor.Document.GetLineForOffset(editor.SelectionStart).LineNumber;
         editor.SelectedText = DocumentUtilitites.NormalizeNewLines(signature, editor.Document, startLine);
         int endLine = editor.Document.GetLineForOffset(editor.SelectionStart + editor.SelectionLength).LineNumber;
         editor.Language.FormattingStrategy.IndentLines(editor, startLine, endLine);
     }
 }
Esempio n. 10
0
        void AddTask(Task task)
        {
            if (!isEnabled)
            {
                return;
            }
            if (!CheckTask(task))
            {
                return;
            }

            if (task.Line >= 1 && task.Line <= textEditor.Document.TotalNumberOfLines)
            {
                LoggingService.Debug(task.ToString());
                int offset    = textEditor.Document.PositionToOffset(task.Line, task.Column);
                int endOffset = TextUtilities.GetNextCaretPosition(DocumentUtilitites.GetTextSource(textEditor.Document), offset, System.Windows.Documents.LogicalDirection.Forward, CaretPositioningMode.WordBorderOrSymbol);
                if (endOffset < 0)
                {
                    endOffset = textEditor.Document.TextLength;
                }
                int length = endOffset - offset;

                if (length < 2)
                {
                    // marker should be at least 2 characters long, but take care that we don't make
                    // it longer than the document
                    length = Math.Min(2, textEditor.Document.TextLength - offset);
                }

                ITextMarker marker = this.markerService.Create(offset, length);

                Color markerColor = Colors.Transparent;

                switch (task.TaskType)
                {
                case TaskType.Error:
                    markerColor = Colors.Red;
                    break;

                case TaskType.Message:
                    markerColor = Colors.Blue;
                    break;

                case TaskType.Warning:
                    markerColor = Colors.Orange;
                    break;
                }

                marker.MarkerColor = markerColor;
                marker.MarkerType  = TextMarkerType.SquigglyUnderline;

                marker.ToolTip = task.Description;

                marker.Tag = task;
            }
        }
Esempio n. 11
0
            SearchedFile SearchFile(FileName fileName)
            {
                ITextBuffer buffer = fileFinder.Create(fileName);

                if (buffer == null)
                {
                    return(null);
                }

                ThrowIfCancellationRequested();

                var                 source      = DocumentUtilitites.GetTextSource(buffer);
                TextDocument        document    = null;
                DocumentHighlighter highlighter = null;
                int                 offset      = 0;
                int                 length      = source.TextLength;

                if (Target == SearchTarget.CurrentSelection && Selection != null)
                {
                    offset = Selection.Offset;
                    length = Selection.Length;
                }
                List <SearchResultMatch> results = new List <SearchResultMatch>();

                foreach (var result in strategy.FindAll(source, offset, length))
                {
                    ThrowIfCancellationRequested();
                    if (document == null)
                    {
                        document = new TextDocument(source);
                        var highlighting = HighlightingManager.Instance.GetDefinitionByExtension(Path.GetExtension(fileName));
                        if (highlighting != null)
                        {
                            highlighter = new DocumentHighlighter(document, highlighting.MainRuleSet);
                        }
                        else
                        {
                            highlighter = null;
                        }
                    }
                    var start   = document.GetLocation(result.Offset).ToLocation();
                    var end     = document.GetLocation(result.Offset + result.Length).ToLocation();
                    var builder = SearchResultsPad.CreateInlineBuilder(start, end, document, highlighter);
                    results.Add(new AvalonEditSearchResultMatch(fileName, start, end, result.Offset, result.Length, builder, result));
                }
                if (results.Count > 0)
                {
                    return(new SearchedFile(fileName, results));
                }
                else
                {
                    return(null);
                }
            }
        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;
                }
            }
        }
Esempio n. 13
0
            SearchResultMatch Find(FileName file, IDocument document, int searchOffset, int length)
            {
                var result = strategy.FindNext(DocumentUtilitites.GetTextSource(document), searchOffset, length);

                if (result != null)
                {
                    var start = document.OffsetToPosition(result.Offset);
                    var end   = document.OffsetToPosition(result.EndOffset);
                    return(new AvalonEditSearchResultMatch(file, start, end, result.Offset, result.Length, null, null, result));
                }
                return(null);
            }
        static void InsertDocumentationComments(ITextEditor editor, int lineNr, int cursorOffset)
        {
            string terminator = DocumentUtilitites.GetLineTerminator(editor.Document, lineNr);

            IDocumentLine currentLine  = editor.Document.GetLine(lineNr);
            IDocumentLine previousLine = (lineNr > 1) ? editor.Document.GetLine(lineNr - 1) : null;

            string curLineText   = currentLine.Text;
            string lineAboveText = previousLine == null ? null : previousLine.Text;

            if (curLineText != null && curLineText.EndsWith("'''", StringComparison.OrdinalIgnoreCase) && (lineAboveText == null || !lineAboveText.Trim().StartsWith("'''", StringComparison.OrdinalIgnoreCase)))
            {
                string indentation = DocumentUtilitites.GetWhitespaceAfter(editor.Document, currentLine.Offset);
                object member      = GetMemberAfter(editor, lineNr);
                if (member != null)
                {
                    StringBuilder sb = new StringBuilder();
                    sb.Append(" <summary>");
                    sb.Append(terminator);
                    sb.Append(indentation);
                    sb.Append("''' ");
                    sb.Append(terminator);
                    sb.Append(indentation);
                    sb.Append("''' </summary>");
                    if (member is IMethod)
                    {
                        IMethod method = (IMethod)member;
                        if (method.Parameters != null && method.Parameters.Count > 0)
                        {
                            for (int i = 0; i < method.Parameters.Count; ++i)
                            {
                                sb.Append(terminator);
                                sb.Append(indentation);
                                sb.Append("''' <param name=\"");
                                sb.Append(method.Parameters[i].Name);
                                sb.Append("\"></param>");
                            }
                        }
                        if (method.ReturnType != null && !method.IsConstructor && method.ReturnType.FullyQualifiedName != "System.Void")
                        {
                            sb.Append(terminator);
                            sb.Append(indentation);
                            sb.Append("''' <returns></returns>");
                        }
                    }
                    editor.Document.Insert(cursorOffset, sb.ToString());
                    editor.Caret.Position = editor.Document.OffsetToPosition(cursorOffset + indentation.Length + "/// ".Length + " <summary>".Length + terminator.Length);
                }
            }
        }
Esempio n. 15
0
        public virtual void IndentLine(ITextEditor editor, IDocumentLine line)
        {
            IDocument document   = editor.Document;
            int       lineNumber = line.LineNumber;

            if (lineNumber > 1)
            {
                IDocumentLine previousLine = document.GetLine(lineNumber - 1);
                string        indentation  = DocumentUtilitites.GetWhitespaceAfter(document, previousLine.Offset);
                // copy indentation to line
                string newIndentation = DocumentUtilitites.GetWhitespaceAfter(document, line.Offset);
                document.Replace(line.Offset, newIndentation.Length, indentation);
            }
        }
        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);
        }
Esempio n. 17
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);
 }
Esempio n. 18
0
        public void EmptyReadOnlyDocument()
        {
            IDocument document = DocumentUtilitites.LoadReadOnlyDocumentFromBuffer(new StringTextBuffer(string.Empty));

            Assert.AreEqual(string.Empty, document.Text);
            Assert.AreEqual(0, document.TextLength);
            Assert.AreEqual(1, document.TotalNumberOfLines);
            Assert.AreEqual(0, document.PositionToOffset(1, 1));
            Assert.AreEqual(new Location(1, 1), document.OffsetToPosition(0));

            Assert.AreEqual(0, document.GetLine(1).Offset);
            Assert.AreEqual(0, document.GetLine(1).EndOffset);
            Assert.AreEqual(0, document.GetLine(1).Length);
            Assert.AreEqual(0, document.GetLine(1).TotalLength);
            Assert.AreEqual(0, document.GetLine(1).DelimiterLength);
            Assert.AreEqual(1, document.GetLine(1).LineNumber);
        }
        void InitializeBaseDocument()
        {
            Stream baseFileStream = GetBaseVersion();

            if (baseFileStream != null)
            {
                // ReadAll() is taking care of closing the stream
                baseDocument = DocumentUtilitites.LoadReadOnlyDocumentFromBuffer(new StringTextBuffer(ReadAll(baseFileStream)));
            }
            else
            {
                // if the file is not under subversion, the document is the opened document
                if (baseDocument == null)
                {
                    baseDocument = DocumentUtilitites.LoadReadOnlyDocumentFromBuffer(document.CreateSnapshot());
                }
            }
        }
Esempio n. 20
0
        public static void ToggleBookmark(ITextEditor editor, int line,
                                          Predicate <SDBookmark> canToggle,
                                          Func <Location, SDBookmark> bookmarkFactory)
        {
            foreach (SDBookmark bookmark in GetBookmarks(new FileName(editor.FileName)))
            {
                if (canToggle(bookmark) && bookmark.LineNumber == line)
                {
                    BookmarkManager.RemoveMark(bookmark);
                    return;
                }
            }
            // no bookmark at that line: create a new bookmark
            int lineStartOffset = editor.Document.GetLine(line).Offset;
            int column          = 1 + DocumentUtilitites.GetWhitespaceAfter(editor.Document, lineStartOffset).Length;

            BookmarkManager.AddMark(bookmarkFactory(new Location(column, 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);
        }
Esempio n. 22
0
        /// <summary>
        /// C# only.
        /// </summary>
        public static void AddCodeToMethodStart(IMember m, ITextEditor textArea, string newCode)
        {
            int methodStart = FindMethodStartOffset(textArea.Document, m.BodyRegion);

            if (methodStart < 0)
            {
                return;
            }
            textArea.Select(methodStart, 0);
            using (textArea.Document.OpenUndoGroup()) {
                int startLine = textArea.Caret.Line;
                foreach (string newCodeLine in newCode.Split('\n'))
                {
                    textArea.Document.Insert(textArea.Caret.Offset,
                                             DocumentUtilitites.GetLineTerminator(textArea.Document, textArea.Caret.Line) + newCodeLine);
                }
                int endLine = textArea.Caret.Line;
                textArea.Language.FormattingStrategy.IndentLines(textArea, startLine, endLine);
            }
        }
Esempio n. 23
0
        protected override void Run(ITextEditor editor, string clipboardText)
        {
            string       indentation   = GetIndentation(editor.Document, editor.Caret.Line);
            IAmbience    ambience      = AmbienceService.GetCurrentAmbience();
            int          maxLineLength = editor.Options.VerticalRulerColumn - VisualIndentationLength(editor, indentation);
            StringWriter insertedText  = new StringWriter();

            insertedText.NewLine = DocumentUtilitites.GetLineTerminator(editor.Document, editor.Caret.Line);
            using (StringReader reader = new StringReader(clipboardText)) {
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    AppendTextLine(indentation, ambience, maxLineLength, insertedText, line);
                }
            }
            IDocument document     = editor.Document;
            int       insertionPos = document.GetLine(editor.Caret.Line).Offset + indentation.Length;

            document.Insert(insertionPos, insertedText.ToString());
        }
Esempio n. 24
0
        public static void InsertCode(this ITextEditor editor, AbstractNode target, AbstractNode insert, int insertOffset, bool updateCaretPos)
        {
            if (insertOffset < 0)
            {
                return;
            }

            var regionCorrectVisitor = new SetRegionInclusionVisitor();

            insert.AcceptVisitor(regionCorrectVisitor, null);

            var doc     = editor.Document;
            var codeGen = editor.Language.Properties.CodeGenerator;

            string indent = DocumentUtilitites.GetWhitespaceAfter(doc, doc.GetLineStartOffset(target.StartLocation));
            string code   = codeGen.GenerateCode(insert, indent);

            doc.Insert(insertOffset, code);
            if (updateCaretPos)
            {
                editor.Caret.Offset = insertOffset + code.Length - 1;
            }
        }
        public static void ShowAsSearchResults(string title, List <Reference> list)
        {
            if (list == null)
            {
                return;
            }
            List <SearchResultMatch> results  = new List <SearchResultMatch>(list.Count);
            TextDocument             document = null;
            FileName     fileName             = null;
            IHighlighter highlighter          = null;

            foreach (Reference r in list)
            {
                var f = new FileName(r.FileName);
                if (document == null || !f.Equals(fileName))
                {
                    document = new TextDocument(DocumentUtilitites.GetTextSource(ParserService.GetParseableFileContent(r.FileName)));
                    fileName = new FileName(r.FileName);
                    var def = HighlightingManager.Instance.GetDefinitionByExtension(Path.GetExtension(r.FileName));
                    if (def != null)
                    {
                        highlighter = new DocumentHighlighter(document, def.MainRuleSet);
                    }
                    else
                    {
                        highlighter = null;
                    }
                }
                var start             = document.GetLocation(r.Offset).ToLocation();
                var end               = document.GetLocation(r.Offset + r.Length).ToLocation();
                var builder           = SearchResultsPad.CreateInlineBuilder(start, end, document, highlighter);
                SearchResultMatch res = new SearchResultMatch(fileName, start, end, r.Offset, r.Length, builder);
                results.Add(res);
            }
            SearchResultsPad.Instance.ShowSearchResults(title, results);
            SearchResultsPad.Instance.BringToFront();
        }
Esempio n. 26
0
            public void Execute(object parameter)
            {
                if (editor.SelectionLength == 0)
                {
                    int wordStart = DocumentUtilitites.FindPrevWordStart(editor.Adapter.Document, editor.CaretOffset);
                    if (wordStart > 0)
                    {
                        string      word    = editor.Adapter.Document.GetText(wordStart, editor.CaretOffset - wordStart);
                        CodeSnippet snippet = SnippetManager.Instance.FindSnippet(Path.GetExtension(editor.Adapter.FileName),
                                                                                  word);
                        if (snippet != null)
                        {
                            snippet.TrackUsage("CustomTabCommand");

                            using (editor.Document.RunUpdate()) {
                                editor.Adapter.Document.Remove(wordStart, editor.CaretOffset - wordStart);
                                snippet.CreateAvalonEditSnippet(editor.Adapter).Insert(editor.TextArea);
                            }
                            return;
                        }
                    }
                }
                baseCommand.Execute(parameter);
            }
        public ICompilationUnit Parse(
            IProjectContent projectContent,
            string fileName,
            ITextBuffer fileContent,
            IEnumerable <TypeScriptFile> files)
        {
            try {
                using (TypeScriptContext context = contextFactory.CreateContext()) {
                    var file = new FileName(fileName);
                    context.AddFile(file, fileContent.Text);
                    context.RunInitialisationScript();

                    NavigationBarItem[] navigation = context.GetNavigationInfo(file);
                    var unit = new TypeScriptCompilationUnit(projectContent)
                    {
                        FileName = fileName
                    };
                    unit.AddNavigation(navigation, fileContent);

                    var typeScriptProjectContent = projectContent as TypeScriptProjectContent;
                    if (typeScriptProjectContent != null)
                    {
                        context.AddFiles(files);
                        IDocument    document    = DocumentUtilitites.LoadReadOnlyDocumentFromBuffer(fileContent);
                        Diagnostic[] diagnostics = context.GetDiagnostics(file, typeScriptProjectContent.Options);
                        TypeScriptService.TaskService.Update(diagnostics, file, document);
                    }

                    return(unit);
                }
            } catch (Exception ex) {
                Console.WriteLine(ex.ToString());
                LoggingService.Debug(ex.ToString());
            }
            return(new DefaultCompilationUnit(projectContent));
        }
        public string GetOldVersionFromLine(int lineNumber, out int newStartLine, out bool added)
        {
            LineChangeInfo info = changeList[lineNumber];

            added = info.Change == ChangeType.Added;

            if (info.Change != ChangeType.None && info.Change != ChangeType.Unsaved)
            {
                newStartLine = CalculateNewStartLineNumber(lineNumber);

                if (info.Change == ChangeType.Added)
                {
                    return("");
                }

                var startDocumentLine = baseDocument.GetLine(info.OldStartLineNumber + 1);
                var endLine           = baseDocument.GetLine(info.OldEndLineNumber);

                return(TextUtilities.NormalizeNewLines(baseDocument.GetText(startDocumentLine.Offset, endLine.EndOffset - startDocumentLine.Offset), DocumentUtilitites.GetLineTerminator(document, newStartLine == 0 ? 1 : newStartLine)));
            }

            newStartLine = 0;
            return(null);
        }
        static int SmartIndentInternal(ITextEditor editor, int begin, int end)
        {
            ILexer lexer = ParserFactory.CreateLexer(SupportedLanguage.VBNet, new StringReader(editor.Document.Text));

            Stack <string> indentation = new Stack <string>();

            indentation.Push(string.Empty);

            List <int> eols = new List <int>();

            bool inInterface    = false;
            bool isMustOverride = false;
            bool isDeclare      = false;
            bool isDelegate     = false;

            Token currentToken = null;
            Token prevToken    = null;

            int blockStart    = 1;
            int lambdaNesting = 0;

            while ((currentToken = lexer.NextToken()).Kind != Tokens.EOF)
            {
                if (prevToken == null)
                {
                    prevToken = currentToken;
                }

                if (currentToken.Kind == Tokens.MustOverride)
                {
                    isMustOverride = true;
                }

                if (currentToken.Kind == Tokens.Delegate)
                {
                    isDelegate = true;
                }

                if (currentToken.Kind == Tokens.Declare)
                {
                    isDeclare = true;
                }

                if (currentToken.Kind == Tokens.EOL)
                {
                    isDelegate = isDeclare = isMustOverride = false;
                    eols.Add(currentToken.Location.Line);
                }

                if (IsBlockEnd(currentToken, prevToken))
                {
                    // indent the lines inside the block
                    // this is an End-statement
                    // hence we indent from blockStart to the previous line
                    int blockEnd = currentToken.Location.Line - 1;

                    // if this is a lambda end include End-Statement in block
//					if (lambdaNesting > 0 && (currentToken.Kind == Tokens.Function || currentToken.Kind == Tokens.Sub)) {
//						blockEnd++;
//					}

                    ApplyToRange(editor, indentation, eols, blockStart, blockEnd, begin, end);

                    if (lambdaNesting > 0 && (currentToken.Kind == Tokens.Function || currentToken.Kind == Tokens.Sub))
                    {
                        Unindent(indentation);

                        ApplyToRange(editor, indentation, eols, currentToken.Location.Line, currentToken.Location.Line, begin, end);
                    }

                    if (currentToken.Kind == Tokens.Interface)
                    {
                        inInterface = false;
                    }

                    if (!inInterface && !isMustOverride && !isDeclare && !isDelegate)
                    {
                        Unindent(indentation);

                        if (currentToken.Kind == Tokens.Select)
                        {
                            Unindent(indentation);
                        }
                    }

                    // block start is this line (for the lines between two blocks)
                    blockStart = currentToken.Location.Line;

                    if (lambdaNesting > 0 && (currentToken.Kind == Tokens.Function || currentToken.Kind == Tokens.Sub))
                    {
                        blockStart++;
                        lambdaNesting--;
                    }
                }

                bool isMultiLineLambda;
                if (IsBlockStart(lexer, currentToken, prevToken, out isMultiLineLambda))
                {
                    // indent the lines between the last and this block
                    // this is a Begin-statement
                    // hence we indent from blockStart to the this line
                    int lastVisualLine = FindNextEol(lexer);
                    eols.Add(lastVisualLine);
                    ApplyToRange(editor, indentation, eols, blockStart, lastVisualLine, begin, end);

                    if (isMultiLineLambda && (currentToken.Kind == Tokens.Function || currentToken.Kind == Tokens.Sub))
                    {
                        lambdaNesting++;
                        int endColumn   = currentToken.Location.Column;
                        int startColumn = DocumentUtilitites.GetWhitespaceAfter(editor.Document, editor.Document.GetLine(lastVisualLine).Offset).Length;
                        if (startColumn < endColumn)
                        {
                            Indent(editor, indentation, new string(' ', endColumn - startColumn - 1));
                        }
                    }

                    if (!inInterface && !isMustOverride && !isDeclare && !isDelegate)
                    {
                        Indent(editor, indentation);

                        if (currentToken.Kind == Tokens.Select)
                        {
                            Indent(editor, indentation);
                        }
                    }

                    if (currentToken.Kind == Tokens.Interface)
                    {
                        inInterface = true;
                    }

                    // block start is the following line (for the lines inside a block)
                    blockStart = lastVisualLine + 1;
                }

                prevToken = currentToken;
            }

            ApplyToRange(editor, indentation, eols, blockStart, editor.Document.TotalNumberOfLines, begin, end);

            return((indentation.PeekOrDefault() ?? string.Empty).Length);
        }
        void FormatLineInternal(ITextEditor editor, int lineNr, int cursorOffset, char ch)
        {
            string terminator = DocumentUtilitites.GetLineTerminator(editor.Document, lineNr);

            doCasing    = PropertyService.Get("VBBinding.TextEditor.EnableCasing", true);
            doInsertion = PropertyService.Get("VBBinding.TextEditor.EnableEndConstructs", true);

            IDocumentLine currentLine = editor.Document.GetLine(lineNr);
            IDocumentLine lineAbove   = lineNr > 1 ? editor.Document.GetLine(lineNr - 1) : null;

            string curLineText   = currentLine == null ? "" : currentLine.Text;
            string lineAboveText = lineAbove == null ? "" : lineAbove.Text;

            if (ch == '\'')
            {
                InsertDocumentationComments(editor, lineNr, cursorOffset);
            }

            if (ch == '\n' && lineAboveText != null)
            {
                if (LanguageUtils.IsInsideDocumentationComment(editor, lineAbove, lineAbove.EndOffset))
                {
                    editor.Document.Insert(cursorOffset, "''' ");
                    return;
                }

                string textToReplace = lineAboveText.TrimLine();

                if (doCasing)
                {
                    DoCasingOnLine(lineAbove, textToReplace, editor);
                }

                if (doInsertion)
                {
                    DoInsertionOnLine(terminator, currentLine, lineAbove, textToReplace, editor, lineNr);
                }

                if (IsInString(lineAboveText))
                {
                    if (IsFinishedString(curLineText))
                    {
                        editor.Document.Insert(lineAbove.EndOffset, "\" & _");
                        editor.Document.Insert(currentLine.Offset, "\"");
                    }
                    else
                    {
                        editor.Document.Insert(lineAbove.EndOffset, "\"");
                    }
                }
                else
                {
                    string indent = DocumentUtilitites.GetWhitespaceAfter(editor.Document, lineAbove.Offset);
                    if (indent.Length > 0)
                    {
                        string newLineText = indent + currentLine.Text.Trim();
                        editor.Document.Replace(currentLine.Offset, currentLine.Length, newLineText);
                    }
                    editor.Caret.Column = indent.Length + 1;
                }

                IndentLines(editor, lineNr - 1, lineNr);
            }
            else if (ch == '>')
            {
                if (LanguageUtils.IsInsideDocumentationComment(editor, currentLine, cursorOffset))
                {
                    int column = editor.Caret.Offset - currentLine.Offset;
                    int index  = Math.Min(column - 1, curLineText.Length - 1);

                    while (index > 0 && curLineText[index] != '<')
                    {
                        --index;
                        if (curLineText[index] == '/')
                        {
                            return;                             // the tag was an end tag or already
                        }
                    }

                    if (index > 0)
                    {
                        StringBuilder commentBuilder = new StringBuilder("");
                        for (int i = index; i < curLineText.Length && i < column && !Char.IsWhiteSpace(curLineText[i]); ++i)
                        {
                            commentBuilder.Append(curLineText[i]);
                        }
                        string tag = commentBuilder.ToString().Trim();
                        if (!tag.EndsWith(">", StringComparison.OrdinalIgnoreCase))
                        {
                            tag += ">";
                        }
                        if (!tag.StartsWith("/", StringComparison.OrdinalIgnoreCase))
                        {
                            string endTag = "</" + tag.Substring(1);
                            editor.Document.Insert(editor.Caret.Offset, endTag);
                            editor.Caret.Offset -= endTag.Length;
                        }
                    }
                }
            }
        }