Пример #1
0
            public override void Execute(EditorRefactoringContext context)
            {
                SD.AnalyticsMonitor.TrackFeature(typeof(SuppressIssueContextAction), issueName);
                var lineNo   = context.CaretLocation.Line;
                var document = context.Editor.Document;

                var    line        = document.GetLineByNumber(lineNo);
                string indentation = DocumentUtilities.GetIndentation(document, lineNo);
                string newLine     = DocumentUtilities.GetLineTerminator(document, lineNo);

                document.Insert(line.Offset, indentation + "// disable once " + issueName + newLine);
            }
        void SaveInitializeComponents(CodeMemberMethod codeMethod)
        {
            var            bodyRegion = initializeComponents.BodyRegion;
            DocumentScript script     = GetScript(bodyRegion.FileName);

            string newline     = DocumentUtilities.GetLineTerminator(script.OriginalDocument, bodyRegion.BeginLine);
            string indentation = DocumentUtilities.GetIndentation(script.OriginalDocument, bodyRegion.BeginLine);
            string code        = "{" + newline + GenerateInitializeComponents(codeMethod, indentation, newline) + indentation + "}";

            int startOffset = script.GetCurrentOffset(bodyRegion.Begin);
            int endOffset   = script.GetCurrentOffset(bodyRegion.End);

            script.Replace(startOffset, endOffset - startOffset, code);
        }
        void CreateField(CodeMemberField newField)
        {
            // insert new field below InitializeComponents()

            var            bodyRegion  = initializeComponents.BodyRegion;
            DocumentScript script      = GetScript(bodyRegion.FileName);
            string         newline     = DocumentUtilities.GetLineTerminator(script.OriginalDocument, bodyRegion.BeginLine);
            string         indentation = DocumentUtilities.GetIndentation(script.OriginalDocument, bodyRegion.BeginLine);

            var    insertionLocation = new TextLocation(bodyRegion.EndLine + 1, 1);
            int    insertionOffset   = script.GetCurrentOffset(insertionLocation);
            string code = indentation + GenerateField(newField) + newline;

            script.InsertText(insertionOffset, code);
        }
Пример #4
0
        protected override void Run(ITextEditor editor, string clipboardText)
        {
            string       indentation   = DocumentUtilities.GetIndentation(editor.Document, editor.Caret.Line);
            IAmbience    ambience      = AmbienceService.GetCurrentAmbience();
            int          maxLineLength = editor.Options.VerticalRulerColumn - VisualIndentationLength(editor, indentation);
            StringWriter insertedText  = new StringWriter();

            insertedText.NewLine = DocumentUtilities.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.GetLineByNumber(editor.Caret.Line).Offset + indentation.Length;

            document.Insert(insertionPos, insertedText.ToString());
        }
Пример #5
0
        void InsertNewLine(IDocument document, NewLineInsertion insertion, ref int offset)
        {
            string eolMarker = DocumentUtilities.GetLineTerminator(document, 1);
            string str       = null;

            switch (insertion)
            {
            case NewLineInsertion.Eol:
                str = eolMarker;
                break;

            case NewLineInsertion.BlankLine:
                str = eolMarker + eolMarker;
                break;

            default:
                return;
            }

            document.Insert(offset, str);
            offset += str.Length;
        }
        void CreateField(CodeMemberField newField)
        {
            // insert new field below the last field or InitializeComponents()
            IField field = null;

            if (formClass != null)
            {
                field = formClass.Fields.LastOrDefault(f => string.Equals(f.Region.FileName,
                                                                          initializeComponents.Region.FileName,
                                                                          StringComparison.OrdinalIgnoreCase));
            }
            var            bodyRegion  = field != null ? field.BodyRegion : initializeComponents.BodyRegion;
            DocumentScript script      = GetScript(bodyRegion.FileName);
            string         newline     = DocumentUtilities.GetLineTerminator(script.OriginalDocument, bodyRegion.BeginLine);
            string         indentation = DocumentUtilities.GetIndentation(script.OriginalDocument, bodyRegion.BeginLine);

            var    insertionLocation = new TextLocation(bodyRegion.EndLine + 1, 1);
            int    insertionOffset   = script.GetCurrentOffset(insertionLocation);
            string code = indentation + GenerateField(newField) + newline;

            script.InsertText(insertionOffset, code);
        }
        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.GetLineByNumber(info.OldStartLineNumber + 1);
                var endLine           = baseDocument.GetLineByNumber(info.OldEndLineNumber);

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

            newStartLine = 0;
            return(null);
        }
        void FormatLineInternal(ITextEditor textArea, int lineNr, int cursorOffset, char ch)
        {
            IDocumentLine curLine    = textArea.Document.GetLineByNumber(lineNr);
            IDocumentLine lineAbove  = lineNr > 1 ? textArea.Document.GetLineByNumber(lineNr - 1) : null;
            string        terminator = DocumentUtilities.GetLineTerminator(textArea.Document, lineNr);

            string curLineText;

            // local string for curLine segment
            if (ch == '/')
            {
                curLineText = textArea.Document.GetText(curLine);
                string lineAboveText = lineAbove == null ? "" : textArea.Document.GetText(lineAbove);
                if (curLineText != null && curLineText.EndsWith("///", StringComparison.Ordinal) && (lineAboveText == null || !lineAboveText.Trim().StartsWith("///", StringComparison.Ordinal)))
                {
                    string            indentation = DocumentUtilities.GetWhitespaceAfter(textArea.Document, curLine.Offset);
                    IUnresolvedEntity member      = GetMemberAfter(textArea, 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>");

                        IUnresolvedMethod method = null;
                        if (member is IUnresolvedMethod)
                        {
                            method = (IUnresolvedMethod)member;
                        }
                        else if (member is IUnresolvedTypeDefinition)
                        {
                            IUnresolvedTypeDefinition type = (IUnresolvedTypeDefinition)member;
                            if (type.Kind == TypeKind.Delegate)
                            {
                                method = type.Methods.FirstOrDefault(m => m.Name == "Invoke");
                            }
                        }

                        if (method != null)
                        {
                            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.IsConstructor)
                            {
                                KnownTypeReference returnType = method.ReturnType as KnownTypeReference;
                                if (returnType == null || returnType.KnownTypeCode != KnownTypeCode.Void)
                                {
                                    sb.Append(terminator);
                                    sb.Append(indentation);
                                    sb.Append("/// <returns></returns>");
                                }
                            }
                        }

                        textArea.Document.Insert(cursorOffset, sb.ToString());
                        textArea.Caret.Offset = cursorOffset + indentation.Length + "/// ".Length + " <summary>".Length + terminator.Length;
                    }
                }
                return;
            }

            if (ch != '\n' && ch != '>')
            {
                if (IsInsideStringOrComment(textArea, curLine, cursorOffset))
                {
                    return;
                }
            }
            switch (ch)
            {
            case '>':
                if (IsInsideDocumentationComment(textArea, curLine, cursorOffset))
                {
                    curLineText = textArea.Document.GetText(curLine);
                    int column = cursorOffset - curLine.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.Ordinal))
                        {
                            tag += ">";
                        }
                        if (!tag.StartsWith("/", StringComparison.Ordinal))
                        {
                            textArea.Document.Insert(cursorOffset, "</" + tag.Substring(1), AnchorMovementType.BeforeInsertion);
                        }
                    }
                }
                break;

            case ':':
            case ')':
            case ']':
            case '{':
                //if (textArea.Document.TextEditorProperties.IndentStyle == IndentStyle.Smart) {
                IndentLine(textArea, curLine);
                //}
                break;

            case '}':
                // Try to get corresponding block beginning brace
                var bracketSearchResult = textArea.Language.BracketSearcher.SearchBracket(textArea.Document, cursorOffset);
                if (bracketSearchResult != null)
                {
                    // Format the block
                    if (!FormatStatement(textArea, cursorOffset, bracketSearchResult.OpeningBracketOffset))
                    {
                        // No auto-formatting seems to be active, at least indent the line
                        IndentLine(textArea, curLine);
                    }
                }
                break;

            case ';':
                // Format this line
                if (!FormatStatement(textArea, cursorOffset, cursorOffset))
                {
                    // No auto-formatting seems to be active, at least indent the line
                    IndentLine(textArea, curLine);
                }
                break;

            case '\n':
                string lineAboveText = lineAbove == null ? "" : textArea.Document.GetText(lineAbove);
                // curLine might have some text which should be added to indentation
                curLineText = textArea.Document.GetText(curLine);

                if (lineAboveText != null && lineAboveText.Trim().StartsWith("#region", StringComparison.Ordinal) &&
                    NeedEndregion(textArea.Document))
                {
                    textArea.Document.Insert(cursorOffset, "#endregion");
                    return;
                }

                IHighlighter highlighter          = textArea.GetService(typeof(IHighlighter)) as IHighlighter;
                bool         isInMultilineComment = false;
                bool         isInMultilineString  = false;
                if (highlighter != null && lineAbove != null)
                {
                    var spanStack = highlighter.GetColorStack(lineNr).Select(c => c.Name).ToArray();
                    isInMultilineComment = spanStack.Contains(HighlighterKnownSpanNames.Comment);
                    isInMultilineString  = spanStack.Contains(HighlighterKnownSpanNames.String);
                }
                bool isInNormalCode = !(isInMultilineComment || isInMultilineString);

                if (lineAbove != null && isInMultilineComment)
                {
                    string lineAboveTextTrimmed = lineAboveText.TrimStart();
                    if (lineAboveTextTrimmed.StartsWith("/*", StringComparison.Ordinal))
                    {
                        textArea.Document.Insert(cursorOffset, " * ");
                        return;
                    }

                    if (lineAboveTextTrimmed.StartsWith("*", StringComparison.Ordinal))
                    {
                        textArea.Document.Insert(cursorOffset, "* ");
                        return;
                    }
                }

                if (lineAbove != null && isInNormalCode)
                {
                    IDocumentLine nextLine     = lineNr + 1 <= textArea.Document.LineCount ? textArea.Document.GetLineByNumber(lineNr + 1) : null;
                    string        nextLineText = (nextLine != null) ? textArea.Document.GetText(nextLine) : "";

                    int indexAbove = lineAboveText.IndexOf("///", StringComparison.Ordinal);
                    int indexNext  = nextLineText.IndexOf("///", StringComparison.Ordinal);
                    if (indexAbove > 0 && (indexNext != -1 || indexAbove + 4 < lineAbove.Length))
                    {
                        textArea.Document.Insert(cursorOffset, "/// ");
                        return;
                    }

                    if (IsInNonVerbatimString(lineAboveText, curLineText))
                    {
                        textArea.Document.Insert(cursorOffset, "\"");
                        textArea.Document.Insert(lineAbove.Offset + lineAbove.Length,
                                                 "\" +");
                    }
                }
                if (textArea.Options.AutoInsertBlockEnd && lineAbove != null && isInNormalCode)
                {
                    string oldLineText = textArea.Document.GetText(lineAbove);
                    if (oldLineText.EndsWith("{", StringComparison.Ordinal))
                    {
                        if (NeedCurlyBracket(textArea.Document.Text))
                        {
                            int insertionPoint = curLine.Offset + curLine.Length;
                            textArea.Document.Insert(insertionPoint, terminator + "}");
                            IndentLine(textArea, textArea.Document.GetLineByNumber(lineNr + 1));
                            textArea.Caret.Offset = insertionPoint;
                        }
                    }
                }
                return;
            }
        }
        bool ShowCompletion(ITextEditor editor, char completionChar, bool ctrlSpace)
        {
            CSharpCompletionContext completionContext;

            if (fileContent == null)
            {
                completionContext = CSharpCompletionContext.Get(editor);
            }
            else
            {
                completionContext = CSharpCompletionContext.Get(editor, context, currentLocation, fileContent);
            }
            if (completionContext == null)
            {
                return(false);
            }

            int caretOffset;

            if (fileContent == null)
            {
                caretOffset     = editor.Caret.Offset;
                currentLocation = editor.Caret.Location;
            }
            else
            {
                caretOffset = completionContext.Document.GetOffset(currentLocation);
            }

            var completionFactory = new CSharpCompletionDataFactory(completionContext, new CSharpResolver(completionContext.TypeResolveContextAtCaret));

            CSharpCompletionEngine cce = new CSharpCompletionEngine(
                completionContext.Document,
                completionContext.CompletionContextProvider,
                completionFactory,
                completionContext.ProjectContent,
                completionContext.TypeResolveContextAtCaret
                );
            var formattingOptions = CSharpFormattingPolicies.Instance.GetProjectOptions(completionContext.Compilation.GetProject());

            cce.FormattingPolicy = formattingOptions.OptionsContainer.GetEffectiveOptions();
            cce.EolMarker        = DocumentUtilities.GetLineTerminator(completionContext.Document, currentLocation.Line);

            cce.IndentString = editor.Options.IndentationString;
            int startPos, triggerWordLength;
            IEnumerable <ICompletionData> completionData;

            if (ctrlSpace)
            {
                if (!cce.TryGetCompletionWord(caretOffset, out startPos, out triggerWordLength))
                {
                    startPos          = caretOffset;
                    triggerWordLength = 0;
                }
                completionData = cce.GetCompletionData(startPos, true);
                completionData = completionData.Concat(cce.GetImportCompletionData(startPos));
            }
            else
            {
                startPos = caretOffset;
                if (char.IsLetterOrDigit(completionChar) || completionChar == '_')
                {
                    if (startPos > 1 && char.IsLetterOrDigit(completionContext.Document.GetCharAt(startPos - 2)))
                    {
                        return(false);
                    }
                    completionData = cce.GetCompletionData(startPos, false);
                    startPos--;
                    triggerWordLength = 1;
                }
                else
                {
                    completionData    = cce.GetCompletionData(startPos, false);
                    triggerWordLength = 0;
                }
            }

            DefaultCompletionItemList list = new DefaultCompletionItemList();

            list.Items.AddRange(FilterAndAddTemplates(editor, completionData.Cast <ICompletionItem>().ToList()));
            if (list.Items.Count > 0 && (ctrlSpace || cce.AutoCompleteEmptyMatch))
            {
                list.SortItems();
                list.PreselectionLength  = caretOffset - startPos;
                list.PostselectionLength = Math.Max(0, startPos + triggerWordLength - caretOffset);
                list.SuggestedItem       = list.Items.FirstOrDefault(i => i.Text == cce.DefaultCompletionString);
                editor.ShowCompletionWindow(list);
                return(true);
            }

            if (!ctrlSpace)
            {
                // Method Insight
                var pce = new CSharpParameterCompletionEngine(
                    completionContext.Document,
                    completionContext.CompletionContextProvider,
                    completionFactory,
                    completionContext.ProjectContent,
                    completionContext.TypeResolveContextAtCaret
                    );
                var newInsight = pce.GetParameterDataProvider(caretOffset, completionChar) as CSharpMethodInsight;
                if (newInsight != null && newInsight.items.Count > 0)
                {
                    newInsight.UpdateHighlightedParameter(pce);
                    newInsight.Show();
                    return(true);
                }
            }
            return(false);
        }
        void DisplayTooltip(MouseEventArgs e)
        {
            int line = GetLineFromMousePosition(e);

            if (line == 0)
            {
                return;
            }

            int    startLine;
            bool   added;
            string oldText = changeWatcher.GetOldVersionFromLine(line, out startLine, out added);

            TextEditor editor = this.TextView.GetService <TextEditor>();

            markerService = this.TextView.GetService <ITextMarkerService>();

            LineChangeInfo zeroLineInfo = changeWatcher.GetChange(0);

            int  offset, length;
            bool hasNewVersion = changeWatcher.GetNewVersionFromLine(line, out offset, out length);

            if (line == 1 && zeroLineInfo.Change == ChangeType.Deleted)
            {
                int zeroStartLine; bool zeroAdded;
                startLine = 1;
                string deletedText = changeWatcher.GetOldVersionFromLine(0, out zeroStartLine, out zeroAdded);
                var    docLine     = editor.Document.GetLineByNumber(line);
                string newLine     = DocumentUtilities.GetLineTerminator(changeWatcher.CurrentDocument, 1);
                deletedText += newLine;
                deletedText += editor.Document.GetText(docLine.Offset, docLine.Length);
                if (oldText != null)
                {
                    oldText = deletedText + newLine + oldText;
                }
                else
                {
                    oldText = deletedText;
                }

                if (!hasNewVersion)
                {
                    offset        = 0;
                    length        = docLine.Length;
                    hasNewVersion = true;
                }
            }

            if (hasNewVersion)
            {
                if (marker != null)
                {
                    markerService.Remove(marker);
                }
                if (length <= 0)
                {
                    marker = null;
                    length = 0;
                }
                else
                {
                    marker = markerService.Create(offset, length);
                    marker.BackgroundColor = Colors.LightGreen;
                }
            }

            if (oldText != null)
            {
                LineChangeInfo currLineInfo = changeWatcher.GetChange(startLine);

                if (currLineInfo.Change == ChangeType.Deleted && !(line == 1 && zeroLineInfo.Change == ChangeType.Deleted))
                {
                    var docLine = editor.Document.GetLineByNumber(startLine);
                    if (docLine.DelimiterLength == 0)
                    {
                        oldText = DocumentUtilities.GetLineTerminator(changeWatcher.CurrentDocument, startLine) + oldText;
                    }
                    oldText = editor.Document.GetText(docLine.Offset, docLine.TotalLength) + oldText;
                }

                DiffControl differ = new DiffControl();
                differ.CopyEditorSettingsAndHighlighting(editor);
                differ.editor.Document.Text = oldText;

                if (oldText == string.Empty)
                {
                    differ.editor.Visibility     = Visibility.Collapsed;
                    differ.copyButton.Visibility = Visibility.Collapsed;
                }
                else
                {
                    if (differ.editor.SyntaxHighlighting != null)
                    {
                        var baseDocument     = new ReadOnlyDocument(changeWatcher.BaseDocument, TextView.Document.FileName);
                        var mainHighlighter  = new DocumentHighlighter(baseDocument, differ.editor.SyntaxHighlighting);
                        var popupHighlighter = differ.editor.TextArea.GetService(typeof(IHighlighter)) as DocumentHighlighter;

                        popupHighlighter.InitialSpanStack = mainHighlighter.GetSpanStack(currLineInfo.OldStartLineNumber);
                    }
                }

                differ.revertButton.Click += delegate {
                    if (hasNewVersion)
                    {
                        Document.Replace(offset, length, oldText);
                        tooltip.IsOpen = false;
                    }
                };

                const double borderThickness = 1;
                tooltip.Child = new Border {
                    Child           = differ,
                    BorderBrush     = editor.TextArea.Foreground,
                    BorderThickness = new Thickness(borderThickness)
                };

                if (tooltip.IsOpen)
                {
                    tooltip.IsOpen = false;
                }

                tooltip.Closed += delegate {
                    if (marker != null)
                    {
                        markerService.Remove(marker);
                    }
                };
                tooltip.HorizontalOffset = -borderThickness - TextView.ScrollOffset.X;
                tooltip.VerticalOffset   =
                    TextView.GetVisualTopByDocumentLine(startLine) - TextView.ScrollOffset.Y;
                tooltip.Placement       = PlacementMode.Top;
                tooltip.PlacementTarget = this.TextView;

                tooltip.IsOpen = true;
            }
        }