Beispiel #1
0
        internal void ComputeSourceEdits(FrugalList <TextChange> changes)
        {
            ITextEdit xedit = this.group.GetEdit((BaseBuffer)this.sourceBuffer);

            foreach (TextChange change in changes)
            {
                if (change.OldLength > 0)
                {
                    IList <SnapshotSpan> sourceDeletionSpans = this.currentElisionSnapshot.MapToSourceSnapshots(new Span(change.OldPosition, change.OldLength));
                    foreach (SnapshotSpan sourceDeletionSpan in sourceDeletionSpans)
                    {
                        xedit.Delete(sourceDeletionSpan);
                    }
                }
                if (change.NewLength > 0)
                {
                    // change includes an insertion
                    ReadOnlyCollection <SnapshotPoint> sourceInsertionPoints = this.currentElisionSnapshot.MapInsertionPointToSourceSnapshots(change.OldPosition, null);

                    if (sourceInsertionPoints.Count == 1)
                    {
                        // the insertion point is unambiguous
                        xedit.Insert(sourceInsertionPoints[0].Position, change.NewText);
                    }
                    else
                    {
                        // the insertion is at the boundary of source spans
                        int[] insertionSizes = new int[sourceInsertionPoints.Count];

                        if (this.resolver != null)
                        {
                            this.resolver.FillInInsertionSizes(new SnapshotPoint(this.currentElisionSnapshot, change.OldPosition),
                                                               sourceInsertionPoints, change.NewText, insertionSizes);
                        }

                        // if resolver was not provided, we just use zeros for the insertion sizes, which will push the entire insertion
                        // into the last slot.

                        int pos = 0;
                        for (int i = 0; i < insertionSizes.Length; ++i)
                        {
                            // contend with any old garbage that the client passed back.
                            int size = (i == insertionSizes.Length - 1)
                                            ? change.NewLength - pos
                                            : Math.Min(insertionSizes[i], change.NewLength - pos);
                            if (size > 0)
                            {
                                xedit.Insert(sourceInsertionPoints[i].Position, TextChange.ChangeNewSubstring(change, pos, size));
                                pos += size;
                                if (pos == change.NewLength)
                                {
                                    break;  // inserted text is used up, whether we've visited all of the insertionSizes or not
                                }
                            }
                        }
                    }
                }
            }
            this.editApplicationInProgress = true;
        }
        /// <summary>
        /// Comment out a span of text using the specified block comment format. If the <paramref name="span"/> is
        /// empty, the entire line containing the span's start point is commented.
        /// </summary>
        /// <param name="span">The span of text to comment.</param>
        /// <param name="edit">The <see cref="ITextEdit"/> to use for applying changes.</param>
        /// <param name="format">The block comment format.</param>
        /// <returns>A <see cref="VirtualSnapshotSpan"/> containing the commented code.</returns>
        /// <exception cref="ArgumentNullException">
        /// <para>If <paramref name="edit"/> is <see langword="null"/>.</para>
        /// <para>-or-</para>
        /// <para>If <paramref name="format"/> is <see langword="null"/>.</para>
        /// </exception>
        protected virtual VirtualSnapshotSpan CommentBlock(VirtualSnapshotSpan span, ITextEdit edit, BlockCommentFormat format)
        {
            if (edit == null)
            {
                throw new ArgumentNullException(nameof(edit));
            }
            if (format == null)
            {
                throw new ArgumentNullException(nameof(format));
            }

            //special case no selection
            if (span.IsEmpty)
            {
                VirtualSnapshotPoint start = new VirtualSnapshotPoint(span.Start.Position.GetContainingLine().Start + ScanToNonWhitespaceChar(span.Start.Position.GetContainingLine()));
                VirtualSnapshotPoint end   = span.IsInVirtualSpace ? span.End : new VirtualSnapshotPoint(span.End.Position.GetContainingLine().End);
                span = new VirtualSnapshotSpan(start, end);
            }

            // add start comment
            edit.Insert(span.Start.Position, format.StartText);
            // add end comment
            edit.Insert(span.End.Position, format.EndText);

            return(span);
        }
        /// <summary>
        /// Inserts a new comment at each virtual point, materializing the virtual space if necessary
        /// </summary>
        static void CommentEmptySpans(ITextEdit edit, IEnumerable <VirtualSnapshotPoint> virtualPoints, IEditorOperations editorOperations)
        {
            foreach (var virtualPoint in virtualPoints)
            {
                if (virtualPoint.IsInVirtualSpace)
                {
                    string leadingWhitespace;
                    if (editorOperations != null)
                    {
                        leadingWhitespace = editorOperations.GetWhitespaceForVirtualSpace(virtualPoint);
                    }
                    else
                    {
                        leadingWhitespace = new string (' ', virtualPoint.VirtualSpaces);
                    }

                    if (leadingWhitespace.Length > 0)
                    {
                        edit.Insert(virtualPoint.Position, leadingWhitespace);
                    }
                }

                edit.Insert(virtualPoint.Position, OpenComment);
                edit.Insert(virtualPoint.Position, CloseComment);
            }
        }
 /// <summary>
 /// Performs the actual insertions of comment markers around the <see cref="commentSpans"/>
 /// </summary>
 static void CommentSpans(ITextEdit edit, NormalizedSnapshotSpanCollection commentSpans)
 {
     foreach (var commentSpan in commentSpans)
     {
         edit.Insert(commentSpan.Start, OpenComment);
         edit.Insert(commentSpan.End, CloseComment);
     }
 }
Beispiel #5
0
        /// <summary>
        /// Rollback all modified text in the document except specified <see cref="IDiffChange"/>.
        /// </summary>
        /// <param name="diffChange">Information about a specific difference between two sequences.</param>
        private void RollbackAllButThisChange(IDiffChange diffChange)
        {
            ITextEdit edit = _textView.TextBuffer.CreateEdit();
            Span      viewSpan;

            try
            {
                string modifiedRegionText = _marginCore.GetModifiedText(diffChange, false);
                string originalText       = _marginCore.GetOriginalText();

                edit.Delete(0, edit.Snapshot.Length);
                edit.Insert(0, originalText);
                ApplyEdit(edit, "Undo Modified Text");

                edit = _textView.TextBuffer.CreateEdit();

                ITextSnapshotLine startLine = edit.Snapshot.GetLineFromLineNumber(diffChange.OriginalStart);
                ITextSnapshotLine endLine   = edit.Snapshot.GetLineFromLineNumber(diffChange.OriginalEnd);
                int start  = startLine.Start.Position;
                int length = endLine.EndIncludingLineBreak.Position - start;

                switch (diffChange.ChangeType)
                {
                case DiffChangeType.Insert:
                    edit.Insert(start, modifiedRegionText);
                    viewSpan = new Span(start, modifiedRegionText.Length);
                    break;

                case DiffChangeType.Delete:
                    edit.Delete(start, length);
                    viewSpan = new Span(start, 0);
                    break;

                case DiffChangeType.Change:
                    edit.Replace(start, length, modifiedRegionText);
                    viewSpan = new Span(start, modifiedRegionText.Length);
                    break;

                default:
                    throw new InvalidEnumArgumentException();
                }

                ApplyEdit(edit, "Restore Modified Region");
            }
            catch (Exception)
            {
                edit.Cancel();
                throw;
            }

            var viewSnapshotSpan = new SnapshotSpan(_textView.TextSnapshot, viewSpan);

            _textView.ViewScroller.EnsureSpanVisible(viewSnapshotSpan, EnsureSpanVisibleOptions.AlwaysCenter);
        }
        void CommentSpan(IEditorOptions options, SnapshotSpan span, ITextEdit textEdit, List <ITrackingSpan> spansToSelect)
        {
            var firstAndLastLine = DetermineFirstAndLastLine(span);

            // Keine Selection, und in die ganze Zeile ist leer
            if (span.IsEmpty && firstAndLastLine.Item1.IsEmptyOrWhitespace())
            {
                return;
            }

            // Blockselektion von leeren Zeilem
            if (!span.IsEmpty && string.IsNullOrWhiteSpace(span.GetText()))
            {
                return;
            }

            if (span.IsEmpty || string.IsNullOrWhiteSpace(span.GetText()))
            {
                var firstNonWhitespaceOnLine = firstAndLastLine.Item1.GetFirstNonWhitespacePosition();
                var insertPosition           = firstNonWhitespaceOnLine ?? firstAndLastLine.Item1.Start;

                // es gibt keine Selektion => ganze Zeile auskommentieren
                textEdit.Insert(insertPosition, SyntaxFacts.SingleLineComment);

                spansToSelect.Add(span.Snapshot.CreateTrackingSpan(Span.FromBounds(firstAndLastLine.Item1.Start, firstAndLastLine.Item1.End), SpanTrackingMode.EdgeInclusive));
            }
            else
            {
                // Partielle Selektion innerhalb einer Zeile
                if (!SpanIncludesAllTextOnIncludedLines(span) &&
                    firstAndLastLine.Item1.LineNumber == firstAndLastLine.Item2.LineNumber)
                {
                    textEdit.Insert(span.Start, SyntaxFacts.BlockCommentStart);
                    textEdit.Insert(span.End, SyntaxFacts.BlockCommentEnd);

                    spansToSelect.Add(span.Snapshot.CreateTrackingSpan(span, SpanTrackingMode.EdgeInclusive));
                }
                else
                {
                    // Das Kommentare an der kleinsten Spalte beginnen, die nicht aus einem Leerzeichen besteht
                    // Bsp.:
                    // ...A
                    // ....B
                    // ->->C
                    // Kommentar beginnt bei Spalte 3
                    var indentToColumn = DetermineSmallestSignificantColumn(options, span, firstAndLastLine);
                    ApplyCommentToNonBlankLines(options, textEdit, firstAndLastLine, indentToColumn);

                    // Den ganzen "Block" an Zeilen selektieren
                    spansToSelect.Add(span.Snapshot.CreateTrackingSpan(Span.FromBounds(firstAndLastLine.Item1.Start.Position, firstAndLastLine.Item2.End.Position), SpanTrackingMode.EdgeInclusive));
                }
            }
        }
        public override void Invoke(CancellationToken cancellationToken)
        {
            AttributeNode src         = Element.GetAttribute("src") ?? Element.GetAttribute("href") ?? Element.GetAttribute("abp-src") ?? Element.GetAttribute("abp-href");
            AttributeNode integrity   = Element.GetAttribute("integrity");
            AttributeNode crossorigin = Element.GetAttribute("crossorigin");

            string url = src.Value;

            if (url.StartsWith("//"))
            {
                url = "http:" + url;
            }

            string hash = CalculateHash(url);

            if (string.IsNullOrEmpty(hash))
            {
                MessageBox.Show("Could not resolve the URL to generate the hash", "Web Essentials", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            try
            {
                ProjectHelpers.DTE.UndoContext.Open(DisplayText);
                using (ITextEdit edit = TextBuffer.CreateEdit())
                {
                    if (integrity != null)
                    {
                        var span = new Span(integrity.ValueRangeUnquoted.Start, integrity.ValueRangeUnquoted.Length);
                        edit.Replace(span, hash);
                    }
                    else
                    {
                        edit.Insert(src.ValueRange.End, " integrity=\"" + hash + "\"");
                    }

                    if (crossorigin == null)
                    {
                        edit.Insert(src.ValueRange.End, " crossorigin=\"anonymous\"");
                    }

                    edit.Apply();
                }
            }
            finally
            {
                ProjectHelpers.DTE.UndoContext.Close();
            }
        }
Beispiel #8
0
        private void CopyLines(IWpfTextView wpfTextView, bool bDirectionDown)
        {
            ITextSnapshot snapshot = wpfTextView.TextSnapshot;

            int lineNumberFirstSelected = 0;
            int lineNumberLastSelected  = 0;

            if (wpfTextView.Selection.IsEmpty)
            {
                lineNumberLastSelected = lineNumberFirstSelected = snapshot.GetLineNumberFromPosition(wpfTextView.Caret.Position.BufferPosition);
            }
            else
            {
                ITextSelection textSelection = wpfTextView.Selection;
                lineNumberFirstSelected = snapshot.GetLineNumberFromPosition(textSelection.Start.Position);
                lineNumberLastSelected  = snapshot.GetLineNumberFromPosition(textSelection.End.Position - 1);
            }
            string            selectedText = "";
            ITextSnapshotLine textSnapshotLine;

            for (int i = lineNumberFirstSelected; i <= lineNumberLastSelected; ++i)
            {
                textSnapshotLine = snapshot.GetLineFromLineNumber(i);
                selectedText    += textSnapshotLine.GetTextIncludingLineBreak();
            }

            int       newPosSelected = 0;
            ITextEdit edit           = snapshot.TextBuffer.CreateEdit();

            if (bDirectionDown)
            {
                textSnapshotLine = snapshot.GetLineFromLineNumber(lineNumberLastSelected);
                newPosSelected   = textSnapshotLine.EndIncludingLineBreak;
                edit.Insert(newPosSelected, selectedText);
            }
            else
            {
                textSnapshotLine = snapshot.GetLineFromLineNumber(lineNumberFirstSelected);
                newPosSelected   = textSnapshotLine.Start;
                edit.Insert(newPosSelected, selectedText);
            }
            edit.Apply();

            SnapshotPoint newSnapshotPoint = new SnapshotPoint(wpfTextView.TextSnapshot, newPosSelected);
            SnapshotSpan  newSnapshotSpan  = new SnapshotSpan(newSnapshotPoint, selectedText.Length);

            wpfTextView.Selection.Select(newSnapshotSpan, false);
            wpfTextView.Caret.MoveTo(newSnapshotPoint);
        }
Beispiel #9
0
        public DragDropPointerEffects HandleDataDropped(DragDropInfo dragDropInfo)
        {
            try
            {
                SnapshotPoint position = dragDropInfo.VirtualBufferPosition.Position;
                string        header   = string.Format(_template, _ext);

                ITextSnapshotLine line = _view.TextBuffer.CurrentSnapshot.GetLineFromPosition(position);

                if (!line.Extent.IsEmpty)
                {
                    header = Environment.NewLine + header;
                }

                using (ITextUndoTransaction transaction = _undoManager.TextBufferUndoHistory.CreateTransaction($"Dragged {_ext}"))
                    using (ITextEdit edit = _view.TextBuffer.CreateEdit())
                    {
                        edit.Insert(position, header);
                        edit.Apply();
                        transaction.Complete();
                    }

                Telemetry.TrackUserTask("FileDragged");
            }
            catch (Exception ex)
            {
                Telemetry.TrackException("DragDrop", ex);
            }

            return(DragDropPointerEffects.Copy);
        }
Beispiel #10
0
        async void IService.HelloWorld()
        {
            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); //воротаемся в UI поток.


            vproject = ProjectHelpers.GetActiveProject();
            string rootfolder  = vproject.GetRootFolder(); //корневая папка проекта с csproj открытым в студии
            string vsixdllpath = System.Reflection.Assembly.GetExecutingAssembly().CodeBase.Replace("file:///", "");
            string vsixfolder  = Path.GetDirectoryName(vsixdllpath);

            string filename     = "tmp1.cs";
            string path2addfile = Path.Combine(vsixfolder, "Templates", filename);
            var    filetoadd    = new FileInfo(path2addfile);

            ProjectItem projectItem  = null;
            string      fileprojpath = Path.Combine(rootfolder, filename);

            var filedest = new FileInfo(Path.Combine(fileprojpath));

            if (1 == 1)
            {
                if (1 == 1) //добавить файл в проект из VSIX папки
                {
                    ProjectHelpers.CopyTmpToProjectFile(vproject, filetoadd.FullName, filedest.FullName);
                }
                projectItem = vproject.AddFileToProject(filedest);

                vproject.DTE.ItemOperations.OpenFile(fileprojpath); //открыть редактор с новым файлом

                if (true)                                           //добавить текст
                {
                    Microsoft.VisualStudio.Text.Editor.IWpfTextView view = ProjectHelpers.GetCurentTextView();

                    if (view != null)
                    {
                        try
                        {
                            ITextEdit edit = view.TextBuffer.CreateEdit();
                            edit.Insert(0, Environment.NewLine);
                            edit.Apply();
                        }
                        catch (Exception e)
                        {
                        }
                    }
                }
                if (true) //добавление абсолютной ссылки в проект
                {
                    VSProject refproject;
                    refproject = (VSProject)vproject.Object;
                    try
                    {
                        refproject.References.Add(@"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\Microsoft.Build.dll");
                    }
                    catch (Exception ddd)
                    {
                    }
                }
            }
        }
Beispiel #11
0
        public static void Insert(this IWpfTextView obj, int position, string text)
        {
            ITextEdit edit = obj.TextSnapshot.TextBuffer.CreateEdit();

            edit.Insert(position, text);
            edit.Apply();
        }
Beispiel #12
0
            public override void Write(char[] buffer, int index, int count)
            {
                ITextEdit edit = this.textBuffer.CreateEdit();

                edit.Insert(this.textBuffer.CurrentSnapshot.Length, buffer, index, count);
                edit.Apply();
            }
Beispiel #13
0
        /// <summary>
        /// Handler for added text of other editor
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void my_AddedText(object sender, EditedTextEventArgs e)
        {
            if (e.File == filename)
            {
                lock (CoProNetwork.locker)
                {
                    while (e.Seq != cb.ExpectedSequence)//if excpected id is the id i got
                    {
                        System.Threading.Monitor.Wait(CoProNetwork.locker);
                        Debug.WriteLine("Recieved seq : " + e.Seq + " Expected seq : " + cb.ExpectedSequence);
                    }

                    trackDict[e.Editor] = m_textView.TextSnapshot.CreateTrackingPoint(e.Location,
                                                                                      PointTrackingMode.Positive);
                    uiDisp.Invoke(new Action(() =>
                    {
                        ITextEdit edit = m_textView.TextBuffer.CreateEdit();

                        var curTrackPoint = trackDict[e.Editor];


                        edit.Insert(curTrackPoint.GetPosition(m_textView.TextSnapshot), e.Command);

                        mySideCalling = false;
                        edit.Apply();
                        edit.Dispose();
                    }));
                    System.Threading.Monitor.PulseAll(CoProNetwork.locker);
                }
            }
        }
Beispiel #14
0
        public override bool Indent()
        {
            string textToInsert = _editorOptions.IsConvertTabsToSpacesEnabled() ? new string(' ', _editorOptions.GetTabSize()) : "\t";

            if (_startPoint.LineNumber == _endPoint.LineNumber)
            {
                return(_startPoint.InsertIndent());
            }

            using (ITextEdit edit = TextBuffer.AdvancedTextBuffer.CreateEdit())
            {
                ITextSnapshot snapshot = TextBuffer.AdvancedTextBuffer.CurrentSnapshot;
                for (int i = _startPoint.LineNumber; i <= _endPoint.LineNumber; i++)
                {
                    ITextSnapshotLine line = snapshot.GetLineFromLineNumber(i);
                    if ((line.Length > 0) &&
                        (line.Start != _endPoint.CurrentPosition))
                    {
                        if (!edit.Insert(line.Start, textToInsert))
                        {
                            return(false);
                        }
                    }
                }

                edit.Apply();

                if (edit.Canceled)
                {
                    return(false);
                }
            }

            return(true);
        }
Beispiel #15
0
        /// <summary>
        /// Comment out a span using a particular line comment format. If the <paramref name="span"/> is empty, the
        /// entire line containing the span's start point is commented.
        /// </summary>
        /// <remarks>
        /// <para>The default algorithm for line comments is designed to meet the following conditions.</para>
        /// <list type="bullet">
        /// <item>Make sure line comments are indented as far as possible, skipping empty lines as necessary.</item>
        /// <item>Don't comment <em>N</em>+1 lines when only <em>N</em> lines were selected by clicking in the left
        /// margin.</item>
        /// </list>
        /// </remarks>
        /// <param name="span">The span of text to comment.</param>
        /// <param name="edit">The <see cref="ITextEdit"/> to apply the changes to.</param>
        /// <param name="format">The line comment format to use for commenting the code.</param>
        /// <returns>A <see cref="VirtualSnapshotSpan"/> containing the commented code.</returns>
        /// <exception cref="ArgumentNullException">
        /// <para>If <paramref name="edit"/> is <see langword="null"/>.</para>
        /// <para>-or-</para>
        /// <para>If <paramref name="format"/> is <see langword="null"/>.</para>
        /// </exception>
        protected virtual VirtualSnapshotSpan CommentLines(VirtualSnapshotSpan span, ITextEdit edit, LineCommentFormat format)
        {
            Contract.Requires <ArgumentNullException>(edit != null, "edit");
            Contract.Requires <ArgumentNullException>(format != null, "format");

            if (span.End.Position.GetContainingLine().LineNumber > span.Start.Position.GetContainingLine().LineNumber&& span.End.Position.GetContainingLine().Start == span.End.Position)
            {
                VirtualSnapshotPoint start = span.Start;
                VirtualSnapshotPoint end   = new VirtualSnapshotPoint(span.Snapshot.GetLineFromLineNumber(span.End.Position.GetContainingLine().LineNumber - 1).Start);
                if (end < start)
                {
                    start = end;
                }

                span = new VirtualSnapshotSpan(start, end);
            }

            int minindex = (from i in Enumerable.Range(span.Start.Position.GetContainingLine().LineNumber, span.End.Position.GetContainingLine().LineNumber - span.Start.Position.GetContainingLine().LineNumber + 1)
                            where span.Snapshot.GetLineFromLineNumber(i).GetText().Trim().Length > 0
                            select ScanToNonWhitespaceChar(span.Snapshot.GetLineFromLineNumber(i)))
                           .Min();

            //comment each line
            for (int line = span.Start.Position.GetContainingLine().LineNumber; line <= span.End.Position.GetContainingLine().LineNumber; line++)
            {
                if (span.Snapshot.GetLineFromLineNumber(line).GetText().Trim().Length > 0)
                {
                    edit.Insert(span.Snapshot.GetLineFromLineNumber(line).Start + minindex, format.StartText);
                }
            }

            span = new VirtualSnapshotSpan(new SnapshotSpan(span.Start.Position.GetContainingLine().Start, span.End.Position.GetContainingLine().End));
            return(span);
        }
Beispiel #16
0
        private static void CommentRegion(SnapshotPoint start, SnapshotPoint end)
        {
            ITextSnapshot snapshot = start.Snapshot;

            using (ITextEdit edit = snapshot.TextBuffer.CreateEdit())
            {
                int column = int.MaxValue;

                for (int i = start.GetContainingLine().LineNumber; i <= end.GetContainingLine().LineNumber; i++)
                {
                    string text = snapshot.GetLineFromLineNumber(i).GetText();

                    int index = GetIndexOfFirstNoneWhiteSpace(text);

                    if (index >= 0 && index < column)
                    {
                        column = index;
                    }
                }

                for (int i = start.GetContainingLine().LineNumber; i <= end.GetContainingLine().LineNumber; i++)
                {
                    ITextSnapshotLine currentLine = snapshot.GetLineFromLineNumber(i);

                    if (string.IsNullOrEmpty(currentLine.GetText()))
                    {
                        continue;
                    }

                    edit.Insert(currentLine.Start.Position + column, "//");
                }

                edit.Apply();
            }
        }
Beispiel #17
0
        private void FormatSelection(ITextBuffer textBuffer, int insertionIndex, string insertionText)
        {
            Controller.TextViewData viewData = Controller.TextViewConnectionListener.GetTextViewDataForBuffer(textBuffer);
            ITextView textView = viewData.LastActiveView;

            using (ITextEdit textEdit = textBuffer.CreateEdit())
            {
                textEdit.Insert(insertionIndex, insertionText);
                textEdit.Apply();
            }

            IOleCommandTarget commandTarget = Shell.Package.GetGlobalService(typeof(Shell.Interop.SUIHostCommandDispatcher)) as IOleCommandTarget;

            SendFocusToEditor(textView);

            SnapshotSpan snapshotSpan = new SnapshotSpan(textView.TextSnapshot, insertionIndex, insertionText.Length + 1);

            textView.Selection.Select(snapshotSpan, false);

            Guid guidVSStd2K = VSConstants.VSStd2K;

            commandTarget.Exec(
                ref guidVSStd2K,
                (uint)VSConstants.VSStd2KCmdID.FORMATSELECTION,
                (uint)OLECMDEXECOPT.OLECMDEXECOPT_DODEFAULT,
                IntPtr.Zero,
                IntPtr.Zero);

            textView.Selection.Clear();
        }
        /// <summary>
        /// Indent the given box selection
        /// </summary>
        /// <remarks>
        /// This is fairly close to the normal text range indenting logic, except that it also
        /// indents an empty selection at the endline, which the normal text range ignores.
        /// </remarks>
        private bool BoxIndent()
        {
            string textToInsert = _editorOptions.IsConvertTabsToSpacesEnabled() ? new string(' ', _editorOptions.GetTabSize()) : "\t";

            using (ITextEdit edit = TextBuffer.AdvancedTextBuffer.CreateEdit())
            {
                ITextSnapshot snapshot        = TextBuffer.AdvancedTextBuffer.CurrentSnapshot;
                int           startLineNumber = GetStartPoint().LineNumber;
                int           endLineNumber   = GetEndPoint().LineNumber;

                for (int i = startLineNumber; i <= endLineNumber; i++)
                {
                    ITextSnapshotLine line = snapshot.GetLineFromLineNumber(i);
                    if (line.Length > 0)
                    {
                        if (!edit.Insert(line.Start, textToInsert))
                        {
                            return(false);
                        }
                    }
                }

                edit.Apply();

                if (edit.Canceled)
                {
                    return(false);
                }
            }

            return(true);
        }
Beispiel #19
0
        private ITextEdit FixByMoving(RobotsTxtLineSyntax line, RobotsTxtRecordSyntax record)
        {
            ITextBuffer buffer = line.Record.Document.Snapshot.TextBuffer;

            // default insertion point at record start
            SnapshotPoint insertionPoint = record.Span.Start;

            // find last User-agent line
            var last = record.Lines
                       .TakeWhile(l => l.NameToken.Value.Equals("User-agent", StringComparison.InvariantCultureIgnoreCase))
                       .LastOrDefault();

            if (last != null) // override insertion point
            {
                insertionPoint = last.Span.End.GetContainingLine().EndIncludingLineBreak;
            }

            // move line up
            ITextEdit edit = buffer.CreateEdit();

            edit.Insert(
                insertionPoint,
                line.Span.Start.GetContainingLine().GetTextIncludingLineBreak()
                );
            edit.Delete(line.Span.Start.GetContainingLine().ExtentIncludingLineBreak);

            return(edit);
        }
        private void AddTechCallback(object sender, EventArgs e)
        {
            ITextBuffer buffer;
            int         selStart, selEnd;
            string      currentCode;
            bool        emptySelection;

            if (GetBufferAndSelection(out buffer, out selStart, out selEnd, out currentCode, out emptySelection))
            {
                ITextEdit edit = buffer.CreateEdit();

                if (emptySelection)
                {
                    string text = "#if " + GetSelectedTechnology() + Environment.NewLine + Environment.NewLine;

                    if (_includeEndIfComment)
                    {
                        text += "#endif" + GetSelectedTechnologyComment() + Environment.NewLine;
                    }
                    else
                    {
                        text += "#endif" + Environment.NewLine;
                    }

                    edit.Insert(selStart, text);
                    edit.Apply();
                }
                else
                {
                    string text = "#if " + GetSelectedTechnology() + Environment.NewLine +
                                  currentCode + Environment.NewLine;

                    if (_includeEndIfComment)
                    {
                        text += "#endif" + GetSelectedTechnologyComment();
                    }
                    else
                    {
                        text += "#endif";
                    }

                    edit.Delete(selStart, selEnd - selStart);
                    edit.Insert(selStart, text);
                    edit.Apply();
                }
            }
        }
            public async Task InsertAsync(string text)
            {
                await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(CancelAllToken);

                _textEdit.Insert(_position, text);
                _textEdit.Apply();
                _textEdit.Dispose();
            }
Beispiel #22
0
 public ITextSnapshot Insert(int position, string text)
 {
     using (ITextEdit textEdit = CreateEdit())
     {
         textEdit.Insert(position, text);
         return(textEdit.Apply());
     }
 }
Beispiel #23
0
        protected virtual SnapshotSpan CommentBlock(SnapshotSpan span, ITextEdit edit, BlockCommentFormat format)
        {
            Contract.Requires <ArgumentNullException>(edit != null, "edit");
            Contract.Requires <ArgumentNullException>(format != null, "format");

            //sp. case no selection
            if (span.IsEmpty)
            {
                span = new SnapshotSpan(span.Start.GetContainingLine().Start + ScanToNonWhitespaceChar(span.Start.GetContainingLine()), span.End.GetContainingLine().End);
            }

            // add start comment
            edit.Insert(span.Start, format.StartText);
            // add end comment
            edit.Insert(span.End, format.EndText);

            return(span);
        }
Beispiel #24
0
        protected virtual SnapshotSpan CommentBlock(SnapshotSpan span, [NotNull] ITextEdit edit, [NotNull] BlockCommentFormat format)
        {
            Requires.NotNull(edit, nameof(edit));
            Requires.NotNull(format, nameof(format));

            //sp. case no selection
            if (span.IsEmpty)
            {
                span = new SnapshotSpan(span.Start.GetContainingLine().Start + ScanToNonWhitespaceChar(span.Start.GetContainingLine()), span.End.GetContainingLine().End);
            }

            // add start comment
            edit.Insert(span.Start, format.StartText);
            // add end comment
            edit.Insert(span.End, format.EndText);

            return(span);
        }
Beispiel #25
0
        private ITextEdit Fix(RobotsTxtLineSyntax line)
        {
            ITextBuffer buffer = line.Record.Document.Snapshot.TextBuffer;

            ITextEdit edit = buffer.CreateEdit();

            edit.Insert(line.NameToken.Span.Span.End, RobotsTxtSyntaxFacts.NameValueDelimiter.ToString());

            return(edit);
        }
Beispiel #26
0
        private void IndentSpan(ITextEdit edit, string indentation, int startLine, int endLine)
        {
            var snapshot = _textView.TextBuffer.CurrentSnapshot;

            for (int i = startLine; i <= endLine; i++)
            {
                var curline = snapshot.GetLineFromLineNumber(i);
                edit.Insert(curline.Start, indentation);
            }
        }
            private void Unminify(ElementNode element, ITextEdit edit)
            {
                for (int i = element.Children.Count - 1; i > -1; i--)
                {
                    var child = element.Children[i];

                    Unminify(child, edit);
                }

                if (_blockElements.Contains(element.Name))
                {
                    int start = element.StartTag.Start;
                    edit.Insert(start, Environment.NewLine);
                }
                else if (_blockElements.Contains(element.Parent.Name) && element.Parent.Children.Count > 1)
                {
                    int start = element.StartTag.Start;
                    edit.Insert(start, Environment.NewLine);
                }
            }
        public void ExtractVariable()
        {
            string        selection = view.Selection.SelectedSpans[0].GetText();
            ITextSnapshot snapshot  = view.TextBuffer.CurrentSnapshot;

            // Verify the selected text doesn't contain mismatched quotes or braces.
            if (!hasIntegrity(selection))
            {
                throw new UnrecognisedExpressionException();
            }

            // Check that what comes after is .,);} or operator
            char next = NextNonWhiteSpaceCharacter(snapshot);

            if (!permissableFollowing.Contains(next))
            {
                throw new UnrecognisedExpressionException();
            }

            // Check that what comes before is (,= or operator
            char prev = PreviousNonWhiteSpaceCharacter(snapshot);

            if (!permissablePreceding.Contains(prev))
            {
                throw new UnrecognisedExpressionException();
            }

            //  Get a variable name from the supplied provider.
            string varName = nameProvider.GetName();

            if (varName == null)
            {
                return;
            }

            int lineNumber = FindLineAfterWhichToInsertDeclaration(snapshot, view.Selection.SelectedSpans[0].Start.Position);

            if (lineNumber < 0)
            {
                throw new FailedInsertionPointException();
            }

            // replace selection with variable name.
            ITextEdit edit = snapshot.TextBuffer.CreateEdit();

            edit.Replace(view.Selection.SelectedSpans[0], varName);

            int indentSize = GetIndentOfNextNonBlankLine(snapshot, lineNumber);

            // Add declaration.
            edit.Insert(snapshot.GetLineFromLineNumber(lineNumber + 1).Start.Position, ("".PadLeft(indentSize) + "var " + varName + " = " + selection + ";\n"));

            edit.Apply();
        }
 /// <summary> Adds edits to comment out each non-blank line, at the given column. </summary>
 void ApplyCommentToNonBlankLines(IEditorOptions options, ITextEdit textEdit, Tuple <ITextSnapshotLine, ITextSnapshotLine> firstAndLastLine, int indentToColumn)
 {
     for (int lineNumber = firstAndLastLine.Item1.LineNumber; lineNumber <= firstAndLastLine.Item2.LineNumber; ++lineNumber)
     {
         var line = firstAndLastLine.Item1.Snapshot.GetLineFromLineNumber(lineNumber);
         if (!line.IsEmptyOrWhitespace())
         {
             var offset = line.GetOffsetForColumn(indentToColumn, options.GetTabSize());
             textEdit.Insert(line.Start + offset, SyntaxFacts.SingleLineComment);
         }
     }
 }
        public void AssignParameterToField()
        {
            ITextSnapshot snapshot = view.TextBuffer.CurrentSnapshot;
            int           pos      = view.Caret.Position.BufferPosition.Position;

            Declaration declaration = FindDeclarationNear(snapshot, pos, new char[] { '(', ',' }, new char[] { ',', ')', '=' });

            if (declaration == null)
            {
                throw new UnrecognisedParameterDeclarationException();
            }

            int assignmentLineNumber = FindLineBeforeWhichToInsertMethodStatement(snapshot, declaration.Span.End);

            if (assignmentLineNumber < 0)
            {
                throw new FailedInsertionPointException("Failed to find insertion point before assignment.");
            }
            ITextSnapshotLine assignmentLine = snapshot.GetLineFromLineNumber(assignmentLineNumber);

            int lineNumber = FindLineAfterWhichToInsertFieldDeclaration(snapshot, assignmentLine.Start.Position);

            if (lineNumber < 0)
            {
                throw new FailedInsertionPointException();
            }

            // add assignment of parameter to method.
            ITextEdit edit             = snapshot.TextBuffer.CreateEdit();
            int       assignmentIndent = FindIndentOfLine(assignmentLine.GetText()) + TabSize;

            edit.Insert(assignmentLine.Start.Position, ("".PadLeft(assignmentIndent) + "this." + declaration.VariableName + " = " + declaration.VariableName + ";\n"));

            // Add declaration.
            int indentSize = GetIndentOfNextNonBlankLine(snapshot, lineNumber);

            edit.Insert(snapshot.GetLineFromLineNumber(lineNumber + 1).Start.Position, ("".PadLeft(indentSize) + "private " + declaration.ToString() + ";\n"));

            edit.Apply();
        }
        /// <summary>
        /// Inserts a newline at the end of the file, if it doesn't already exist.
        /// </summary>
        /// <param name="snapshot">The snapshot of the document to enforce.</param>
        /// <param name="edit">The edit context of the document to enforce.</param>
        /// <param name="eol">The eol character to add.</param>
        internal void InsertFinalNewline(ITextSnapshot snapshot, ITextEdit edit, string eol)
        {
            var line = snapshot.Lines.LastOrDefault();

            if (line != null && !string.IsNullOrWhiteSpace(line.GetText()))
            {
                if (eol == null)
                    eol = Environment.NewLine;

                edit.Insert(line.End.Position, eol);
            }
        }
		protected override void Modify(ITextEdit edit, ITextSnapshotLine line)
		{
			edit.Insert(line.Start.Position, "#");
		}
            private void Unminify(ElementNode element, ITextEdit edit)
            {
                for (int i = element.Children.Count - 1; i > -1; i--)
                {
                    var child = element.Children[i];

                    Unminify(child, edit);
                }

                if (_blockElements.Contains(element.Name))
                {
                    int start = element.StartTag.Start;
                    edit.Insert(start, Environment.NewLine);
                }
                else if (_blockElements.Contains(element.Parent.Name) && element.Parent.Children.Count > 1)
                {
                    int start = element.StartTag.Start;
                    edit.Insert(start, Environment.NewLine);
                }
            }
Beispiel #34
0
 private void IndentSpan(ITextEdit edit, string indentation, int startLine, int endLine) {
     var snapshot = _textView.TextBuffer.CurrentSnapshot;
     for (int i = startLine; i <= endLine; i++) {
         var curline = snapshot.GetLineFromLineNumber(i);
         edit.Insert(curline.Start, indentation);
     }
 }
Beispiel #35
0
 /// <summary>
 /// Performs an insert in a document.
 /// </summary>
 /// <param name="model">The model.</param>
 private void Insert(DocumentModel doc, OpInsertMessage model, ITextEdit edit)
 {
     //doc.BlockEvent = true;
     var start = model.Index > edit.Snapshot.Length ? edit.Snapshot.Length : model.Index;
     edit.Insert(start, model.Content);
 }
Beispiel #36
0
 /// <summary>
 /// Undoes a delete operation.
 /// </summary>
 /// <param name="model">The model.</param>
 private void UndoDelete(DocumentModel doc, OpDeleteMessage model, ITextEdit edit)
 {
     //doc.BlockEvent = true;
     edit.Insert(model.Index, model.OldContent);
 }
        protected virtual SnapshotSpan CommentLines(SnapshotSpan span, ITextEdit edit, LineCommentFormat format)
        {
            Contract.Requires<ArgumentNullException>(edit != null, "edit");
            Contract.Requires<ArgumentNullException>(format != null, "format");

            /*
             * Rules for line comments:
             *  Make sure line comments are indented as far as possible, skipping empty lines as necessary
             *  Don't comment N+1 lines when only N lines were selected my clicking in the left margin
             */
            if (span.End.GetContainingLine().LineNumber > span.Start.GetContainingLine().LineNumber && span.End.GetContainingLine().Start == span.End)
            {
                SnapshotPoint start = span.Start;
                SnapshotPoint end = span.Snapshot.GetLineFromLineNumber(span.End.GetContainingLine().LineNumber - 1).Start;
                if (end < start)
                    start = end;

                span = new SnapshotSpan(start, end);
            }

            int minindex = (from i in Enumerable.Range(span.Start.GetContainingLine().LineNumber, span.End.GetContainingLine().LineNumber - span.Start.GetContainingLine().LineNumber + 1)
                            where span.Snapshot.GetLineFromLineNumber(i).GetText().Trim().Length > 0
                            select ScanToNonWhitespaceChar(span.Snapshot.GetLineFromLineNumber(i)))
                           .Min();

            //comment each line
            for (int line = span.Start.GetContainingLine().LineNumber; line <= span.End.GetContainingLine().LineNumber; line++)
            {
                if (span.Snapshot.GetLineFromLineNumber(line).GetText().Trim().Length > 0)
                    edit.Insert(span.Snapshot.GetLineFromLineNumber(line).Start + minindex, format.StartText);
            }

            span = new SnapshotSpan(span.Start.GetContainingLine().Start, span.End.GetContainingLine().End);
            return span;
        }
Beispiel #38
0
        /// <summary>
        /// Comment out a span of text using the specified block comment format. If the <paramref name="span"/> is
        /// empty, the entire line containing the span's start point is commented.
        /// </summary>
        /// <param name="span">The span of text to comment.</param>
        /// <param name="edit">The <see cref="ITextEdit"/> to use for applying changes.</param>
        /// <param name="format">The block comment format.</param>
        /// <returns>A <see cref="VirtualSnapshotSpan"/> containing the commented code.</returns>
        /// <exception cref="ArgumentNullException">
        /// <para>If <paramref name="edit"/> is <see langword="null"/>.</para>
        /// <para>-or-</para>
        /// <para>If <paramref name="format"/> is <see langword="null"/>.</para>
        /// </exception>
        protected virtual VirtualSnapshotSpan CommentBlock(VirtualSnapshotSpan span, ITextEdit edit, BlockCommentFormat format)
        {
            Contract.Requires<ArgumentNullException>(edit != null, "edit");
            Contract.Requires<ArgumentNullException>(format != null, "format");

            //special case no selection
            if (span.IsEmpty)
            {
                VirtualSnapshotPoint start = new VirtualSnapshotPoint(span.Start.Position.GetContainingLine().Start + ScanToNonWhitespaceChar(span.Start.Position.GetContainingLine()));
                VirtualSnapshotPoint end = span.IsInVirtualSpace ? span.End : new VirtualSnapshotPoint(span.End.Position.GetContainingLine().End);
                span = new VirtualSnapshotSpan(start, end);
            }

            // add start comment
            edit.Insert(span.Start.Position, format.StartText);
            // add end comment
            edit.Insert(span.End.Position, format.EndText);

            return span;
        }
Beispiel #39
0
        /// <summary>
        /// Comment out a span using a particular line comment format. If the <paramref name="span"/> is empty, the
        /// entire line containing the span's start point is commented.
        /// </summary>
        /// <remarks>
        /// <para>The default algorithm for line comments is designed to meet the following conditions.</para>
        /// <list type="bullet">
        /// <item>Make sure line comments are indented as far as possible, skipping empty lines as necessary.</item>
        /// <item>Don't comment <em>N</em>+1 lines when only <em>N</em> lines were selected by clicking in the left
        /// margin.</item>
        /// </list>
        /// </remarks>
        /// <param name="span">The span of text to comment.</param>
        /// <param name="edit">The <see cref="ITextEdit"/> to apply the changes to.</param>
        /// <param name="format">The line comment format to use for commenting the code.</param>
        /// <returns>A <see cref="VirtualSnapshotSpan"/> containing the commented code.</returns>
        /// <exception cref="ArgumentNullException">
        /// <para>If <paramref name="edit"/> is <see langword="null"/>.</para>
        /// <para>-or-</para>
        /// <para>If <paramref name="format"/> is <see langword="null"/>.</para>
        /// </exception>
        protected virtual VirtualSnapshotSpan CommentLines(VirtualSnapshotSpan span, ITextEdit edit, LineCommentFormat format)
        {
            Contract.Requires<ArgumentNullException>(edit != null, "edit");
            Contract.Requires<ArgumentNullException>(format != null, "format");

            if (span.End.Position.GetContainingLine().LineNumber > span.Start.Position.GetContainingLine().LineNumber && span.End.Position.GetContainingLine().Start == span.End.Position)
            {
                VirtualSnapshotPoint start = span.Start;
                VirtualSnapshotPoint end = new VirtualSnapshotPoint(span.Snapshot.GetLineFromLineNumber(span.End.Position.GetContainingLine().LineNumber - 1).Start);
                if (end < start)
                    start = end;

                span = new VirtualSnapshotSpan(start, end);
            }

            int minindex = (from i in Enumerable.Range(span.Start.Position.GetContainingLine().LineNumber, span.End.Position.GetContainingLine().LineNumber - span.Start.Position.GetContainingLine().LineNumber + 1)
                            where span.Snapshot.GetLineFromLineNumber(i).GetText().Trim().Length > 0
                            select ScanToNonWhitespaceChar(span.Snapshot.GetLineFromLineNumber(i)))
                           .Min();

            //comment each line
            for (int line = span.Start.Position.GetContainingLine().LineNumber; line <= span.End.Position.GetContainingLine().LineNumber; line++)
            {
                if (span.Snapshot.GetLineFromLineNumber(line).GetText().Trim().Length > 0)
                    edit.Insert(span.Snapshot.GetLineFromLineNumber(line).Start + minindex, format.StartText);
            }

            span = new VirtualSnapshotSpan(new SnapshotSpan(span.Start.Position.GetContainingLine().Start, span.End.Position.GetContainingLine().End));
            return span;
        }
        protected virtual SnapshotSpan CommentBlock(SnapshotSpan span, ITextEdit edit, BlockCommentFormat format)
        {
            Contract.Requires<ArgumentNullException>(edit != null, "edit");
            Contract.Requires<ArgumentNullException>(format != null, "format");

            //sp. case no selection
            if (span.IsEmpty)
            {
                span = new SnapshotSpan(span.Start.GetContainingLine().Start + ScanToNonWhitespaceChar(span.Start.GetContainingLine()), span.End.GetContainingLine().End);
            }

            // add start comment
            edit.Insert(span.Start, format.StartText);
            // add end comment
            edit.Insert(span.End, format.EndText);

            return span;
        }
        private void ReplaceLines(ITextEdit edit, int startOldLine, int endOldLine, int startNewLine, int endNewLine) {
            int oldLineCount = endOldLine - startOldLine;
            int newLineCount = endNewLine - startNewLine;

            // replace one line at a time instead of all of the lines at once so that we preserve breakpoints
            int excessNewLineStart = startNewLine - startOldLine;
            for (int i = startOldLine; i < endOldLine && i < (endNewLine - startNewLine + startOldLine); i++) {
                edit.Replace(
                    _snapshot.GetLineFromLineNumber(_startingReplacementLine + i).Extent,
                    _newLines[startNewLine + i - startOldLine]
                );
                excessNewLineStart = startNewLine + i - startOldLine + 1;
            }

            if (oldLineCount > newLineCount) {
                // we end up w/ less lines, we need to delete some text
                edit.Delete(
                    Span.FromBounds(
                        _snapshot.GetLineFromLineNumber(_startingReplacementLine + endOldLine - (oldLineCount - newLineCount)).Start.Position,
                        _snapshot.GetLineFromLineNumber(_startingReplacementLine + endOldLine - 1).EndIncludingLineBreak.Position
                    )
                );
            } else if (oldLineCount < newLineCount) {
                // we end up w/ more lines, we need to insert some text
                edit.Insert(
                    _snapshot.GetLineFromLineNumber(_startingReplacementLine + endOldLine - 1).EndIncludingLineBreak,
                    string.Join(
                        _view.Options.GetNewLineCharacter(),
                        _newLines,
                        excessNewLineStart,
                        endNewLine - excessNewLineStart
                    ) + _view.Options.GetNewLineCharacter()
                );
            }
        }