private void FormatRoot(ITextEdit edit, int keywordLength)
 {
     if (_document.Root != null)
     {
         FormatProperty(_document.Root, Math.Max(keywordLength, 0), edit);
     }
 }
Пример #2
0
        /// <summary>
        /// Builds the comment stub and inserts it into the editor.
        /// </summary>
        /// <param name="position">The position of the last slash.</param>
        private void CreateStub(int position, ITextChange change)
        {
            string text = this._view.TextSnapshot.ToString();

            using (ITextEdit editor = this._view.TextBuffer.CreateEdit())
            {
                try
                {
                    this.tabs = StubUtils.GetIndention(position, this._view.TextSnapshot);
                    string summaryTag  = generateSummaryTag();
                    string parameters  = getFunctionParameters(position);
                    string returnTag   = getReturnTag(position);
                    string autoComment = summaryTag + parameters + returnTag;

                    int  lineStart     = this._view.TextSnapshot.GetLineFromPosition(position).Start.Position;
                    var  caretPosition = autoComment.IndexOf(StubUtils.CaretPlaceholder);
                    Span firstLineSpan = new Span(lineStart, change.NewSpan.End - lineStart);
                    autoComment = autoComment.Replace(StubUtils.CaretPlaceholder, "");

                    editor.Replace(firstLineSpan, autoComment);
                    ITextSnapshotLine prevLine = this._view.TextSnapshot.GetLineFromPosition(position);

                    StubUtils.MoveCaretAfterChange(this._view, this.editor, lineStart + caretPosition);

                    var after = editor.Apply();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(errorMsgPrefix + ex.Message);
                }
            }
        }
        public bool Format()
        {
            _spaceBeforeEquals = EditorConfigPackage.FormatterOptions.SpacesBeforeEquals;
            _spaceAfterEquals  = EditorConfigPackage.FormatterOptions.SpacesAfterEquals;
            _spaceBeforeColon  = EditorConfigPackage.FormatterOptions.SpacesBeforeColon;
            _spaceAfterColon   = EditorConfigPackage.FormatterOptions.SpacesAfterColon;

            // Trim lines
            bool changed = TrimLines();

            // Format properties
            using (ITextEdit edit = _document.TextBuffer.CreateEdit())
            {
                int keywordLength = GetKeywordLength();

                FormatSection(edit, keywordLength);
                FormatRoot(edit, keywordLength);

                if (edit.HasEffectiveChanges)
                {
                    changed = true;
                    edit.Apply();
                }
            }

            return(changed);
        }
        private bool TrimLines()
        {
            bool changed = false;

            using (ITextEdit edit = _document.TextBuffer.CreateEdit())
            {
                foreach (ITextSnapshotLine line in _document.TextBuffer.CurrentSnapshot.Lines)
                {
                    string originalText = line.GetText();
                    string newText      = line.Extent.IsEmpty ? string.Empty : originalText.Trim();

                    if (originalText != newText)
                    {
                        edit.Replace(line.Start, line.Length, newText);
                    }
                }

                if (edit.HasEffectiveChanges)
                {
                    changed = true;
                    edit.Apply();
                }
            }

            return(changed);
        }
Пример #5
0
        /// <summary>
        /// Given a list of <see cref="ITrackingSpan"/>s, deletes them from the buffer.
        /// </summary>
        protected bool DeleteSpans(IList <ITrackingSpan> spans)
        {
            if (spans == null)
            {
                throw new ArgumentNullException(nameof(spans));
            }

            ITextSnapshot mostRecentSnapshot = _cocoaTextView.TextSnapshot;

            using (ITextEdit textEdit = _cocoaTextView.TextBuffer.CreateEdit())
            {
                foreach (ITrackingSpan span in spans)
                {
                    if (!textEdit.Delete(span.GetSpan(mostRecentSnapshot)))
                    {
                        return(false);
                    }
                }

                textEdit.Apply();

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

            return(true);
        }
        private void FormatProperty(Property property, int keywordLength, ITextEdit edit)
        {
            string originalText = edit.Snapshot.GetText(property.Span);
            string newText      = property.Keyword.Text.PadRight(keywordLength);

            string spaceBeforeEquals = string.Empty.PadRight(_spaceBeforeEquals);
            string spaceAfterEquals  = string.Empty.PadRight(_spaceAfterEquals);
            string spaceBeforeColon  = string.Empty.PadRight(_spaceBeforeColon);
            string spaceAfterColon   = string.Empty.PadRight(_spaceAfterColon);

            if (property.Value != null)
            {
                newText += $"{spaceBeforeEquals}={spaceAfterEquals}{property.Value.Text}";
            }

            if (property.Severity != null)
            {
                newText += $"{spaceBeforeColon}:{spaceAfterColon}{property.Severity.Text}";
            }

            if (originalText != newText)
            {
                edit.Replace(property.Span, newText);
            }
        }
        /// <summary>
        /// Undo the text buffer change action.
        /// </summary>
        /// <exception cref="InvalidOperationException">Operation cannot be undone.</exception>
        public override void Undo()
        {
            // Validate that we can undo this change
            if (!CanUndo)
            {
                throw new InvalidOperationException(Strings.CannotUndo);
            }

#if DEBUG
            // sanity check
            Debug.Assert(TextBuffer.CurrentSnapshot.Length == _bufferLengthAfterChange,
                         "The buffer is in a different state than when this TextBufferUndoChangePrimitive was created!");
#endif

            // For undo-in-closed-files scenarios where we are done/undone on a buffer other
            // than the one we were originally created on.
            if (AttachedToNewBuffer)
            {
                AttachedToNewBuffer = false;

                this.BeforeReiteratedVersionNumber = null;
                this.AfterReiteratedVersionNumber  = TextBuffer.CurrentSnapshot.Version.VersionNumber;
            }

            bool editCanceled = false;
            using (ITextEdit edit = TextBuffer.CreateEdit(EditOptions.None, this.BeforeReiteratedVersionNumber, UndoTag.Tag))
            {
                foreach (ITextChange textChange in this.Changes)
                {
                    if (!edit.Replace(new Span(textChange.NewPosition, textChange.NewLength), textChange.OldText))
                    {
                        // undo canceled by readonly region
                        editCanceled = true;
                        break;
                    }
                }

                if (!editCanceled)
                {
                    edit.Apply();

                    if (edit.Canceled)
                    {
                        editCanceled = true;
                    }
                }
            }

            if (editCanceled)
            {
                throw new OperationCanceledException("Undo failed due to readonly regions or canceled edit.");
            }

            if (this.BeforeReiteratedVersionNumber == null)
            {
                this.BeforeReiteratedVersionNumber = TextBuffer.CurrentSnapshot.Version.VersionNumber;
            }

            _canUndo = false;
        }
Пример #8
0
        public bool ApplyChanges(ITextEdit textEdit, FormatLinesResult result)
        {
            var lineEnding = DetectLineEnding(textEdit.Snapshot);

            var sb     = new StringBuilder();
            var indent = new string(' ', result.Indent);

            foreach (var line in result.Lines)
            {
                if (sb.Length > 0)
                {
                    sb.Append(lineEnding);
                }
                sb.Append(indent);
                sb.Append(result.CommentType.TextPrefix);
                sb.Append(line);
            }
            var commentText = sb.ToString();
            var oldSpan     = result.SnapshotSpan.Span;
            var oldText     = textEdit.Snapshot.GetText(oldSpan);

            if (oldText == commentText)
            {
                return(false);
            }

            textEdit.Replace(oldSpan, commentText);
            return(true);
        }
Пример #9
0
        /// <summary>
        ///  Handler for removed text by other editor
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void my_RemovedText(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.Delete(e.Location, int.Parse(e.Command.Split(';')[1]));

                        mySideCalling = false;
                        edit.Apply();
                        edit.Dispose();
                    }));
                    System.Threading.Monitor.PulseAll(CoProNetwork.locker);
                }
            }
        }
Пример #10
0
        private void CreateNewCommentLine(ITextChange change)
        {
            using (ITextEdit editor = this._view.TextBuffer.CreateEdit())
            {
                try
                {
                    ITextSnapshotLine line     = this._view.TextSnapshot.GetLineFromPosition(change.OldEnd);
                    string            lineText = line.GetText();
                    string            nextLine = this._view.TextSnapshot.GetLineFromLineNumber(line.LineNumber + 1).GetText();
                    if (lineText.Trim().StartsWith("///") && (nextLine.Trim().StartsWith("///") || change.OldEnd != line.End.Position))
                    {
                        int slashIndex = lineText.IndexOf('/');
                        //Only add a new comment line if the newline char is after the triple slash
                        //(how Visual Studio in C# works)
                        if ((line.Start.Position + 3 + slashIndex) > change.OldEnd)
                        {
                            return;
                        }

                        string newTabs = lineText.Substring(0, slashIndex);
                        editor.Replace(change.NewSpan, Environment.NewLine + newTabs + "/// ");
                        editor.Apply();
                    }
                }
                catch (Exception) { }
            }
        }
        private ITextEdit Fix(RobotsTxtLineSyntax line)
        {
            ITextBuffer buffer = line.Record.Document.Snapshot.TextBuffer;

            string value = line.ValueToken.Value;

            // fix
            string newValue = value;

            // example: * -> /
            if (value == "*")
            {
                newValue = "/";
            }

            // example: /folder/* -> /folder/
            else if (value.EndsWith("/*"))
            {
                newValue = value.Remove(value.Length - 1);
            }

            ITextEdit edit = buffer.CreateEdit();

            edit.Replace(
                line.ValueToken.Span.Span,
                newValue
                );

            return(edit);
        }
        public override void Invoke(CancellationToken cancellationToken)
        {
            string mimeType  = FileHelpers.GetMimeTypeFromBase64(Attribute.Value);
            string extension = FileHelpers.GetExtension(mimeType) ?? "png";

            var fileName = FileHelpers.ShowDialog(extension);

            if (!string.IsNullOrEmpty(fileName) && FileHelpers.SaveDataUriToFile(Attribute.Value, fileName))
            {
                string relative = FileHelpers.RelativePath(TextBuffer.GetFileName(), fileName);

                try
                {
                    ProjectHelpers.DTE.UndoContext.Open(DisplayText);
                    using (ITextEdit edit = TextBuffer.CreateEdit())
                    {
                        edit.Replace(Attribute.ValueRangeUnquoted.ToSpan(), relative.ToLowerInvariant());
                        edit.Apply();
                    }
                }
                finally
                {
                    ProjectHelpers.DTE.UndoContext.Close();
                }
            }
        }
		protected override void Modify(ITextEdit edit, ITextSnapshotLine line)
		{
			if (line.GetText().StartsWith("#"))
			{
				edit.Delete(line.Start, 1);
			}
		}
Пример #14
0
 public void _runInit()
 {
     PlatformSingleton platformSingleton_ = __singleton<PlatformSingleton>._instance();
     string textEditUrl_ = @"uid://notepad.include.window:window.optimal.TextEdit";
     mTextEdit = platformSingleton_._findInterface<ITextEdit>(textEditUrl_);
     mTextEdit._setDockStyle("Fill");
 }
        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();
        }
Пример #16
0
        public override void Invoke(CancellationToken cancellationToken)
        {
            if (_disabled)
            {
                return;
            }

            try
            {
                var             dependencies = Dependencies.FromConfigFile(_provider.ConfigFilePath);
                IProvider       provider     = dependencies.GetProvider(_provider.InstallationState.ProviderId);
                ILibraryCatalog catalog      = provider?.GetCatalog();

                if (catalog == null)
                {
                    return;
                }

                JSONMember member = _provider.LibraryObject.Children.OfType <JSONMember>().FirstOrDefault(m => m.UnquotedNameText == ManifestConstants.Library);

                if (member != null)
                {
                    using (ITextEdit edit = TextBuffer.CreateEdit())
                    {
                        edit.Replace(new Span(member.Value.Start, member.Value.Length), "\"" + _updatedLibraryId + "\"");
                        edit.Apply();
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.LogEvent(ex.ToString(), LogLevel.Error);
            }
        }
Пример #17
0
        public override async void Invoke(CancellationToken cancellationToken)
        {
            try
            {
                await _libraryCommandService.UninstallAsync(_provider.ConfigFilePath, _provider.InstallationState.LibraryId, cancellationToken).ConfigureAwait(false);

                await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

                using (ITextEdit edit = TextBuffer.CreateEdit())
                {
                    var arrayElement = _provider.LibraryObject.Parent as JSONArrayElement;
                    var prev         = GetPreviousSibling(arrayElement) as JSONArrayElement;
                    var next         = GetNextSibling(arrayElement) as JSONArrayElement;

                    int start = TextBuffer.CurrentSnapshot.GetLineFromPosition(arrayElement.Start).Start;
                    int end   = TextBuffer.CurrentSnapshot.GetLineFromPosition(arrayElement.AfterEnd).EndIncludingLineBreak;

                    if (next == null && prev?.Comma != null)
                    {
                        start = prev.Comma.Start;
                        end   = TextBuffer.CurrentSnapshot.GetLineFromPosition(arrayElement.AfterEnd).End;
                    }

                    edit.Delete(Span.FromBounds(start, end));
                    edit.Apply();
                }
            }
            catch (Exception ex)
            {
                Logger.LogEvent(ex.ToString(), LibraryManager.Contracts.LogLevel.Error);
            }
        }
Пример #18
0
        public static void Insert(this IWpfTextView obj, int position, string text)
        {
            ITextEdit edit = obj.TextSnapshot.TextBuffer.CreateEdit();

            edit.Insert(position, text);
            edit.Apply();
        }
        private void AdjustIndentationForSpan(
            Document document, ITextEdit edit, TextSpan visibleSpan, IFormattingRule baseIndentationRule, OptionSet options)
        {
            var root = document.GetSyntaxRootSynchronously(CancellationToken.None);

            using (var rulePool = SharedPools.Default <List <IFormattingRule> > ().GetPooledObject())
                using (var spanPool = SharedPools.Default <List <TextSpan> > ().GetPooledObject()) {
                    var venusFormattingRules = rulePool.Object;
                    var visibleSpans         = spanPool.Object;

                    venusFormattingRules.Add(baseIndentationRule);
                    venusFormattingRules.Add(ContainedDocumentPreserveFormattingRule.Instance);

                    var formattingRules = venusFormattingRules.Concat(Formatter.GetDefaultFormattingRules(document));

                    var workspace = document.Project.Solution.Workspace;
                    var changes   = Formatter.GetFormattedTextChanges(
                        root, new TextSpan [] { CommonFormattingHelpers.GetFormattingSpan(root, visibleSpan) },
                        workspace, options, formattingRules, CancellationToken.None);

                    visibleSpans.Add(visibleSpan);
                    var newChanges = FilterTextChanges(document.GetTextAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None), visibleSpans, new ReadOnlyCollection <TextChange>(changes)).Where(t => visibleSpan.Contains(t.Span));

                    foreach (var change in newChanges)
                    {
                        edit.Replace(new Span(change.Span.Start, change.Span.Length), change.NewText);
                    }
                }
        }
Пример #20
0
        /// Takes current text buffer and new text then builds list of changed
        /// regions and applies them to the buffer. This way we can avoid
        /// destruction of bookmarks and other markers. Complete
        /// buffer replacement deletes all markers which causes
        /// loss of bookmarks, breakpoints and other similar markers.
        public static void ApplyChange(
            ITextBuffer textBuffer,
            int position,
            int length,
            string newText,
            string transactionName,
            ISelectionTracker selectionTracker,
            int maxMilliseconds)
        {
            var    snapshot  = textBuffer.CurrentSnapshot;
            int    oldLength = Math.Min(length, snapshot.Length - position);
            string oldText   = snapshot.GetText(position, oldLength);

            var changes = TextChanges.BuildChangeList(oldText, newText, maxMilliseconds);

            if (changes != null && changes.Count > 0)
            {
                using (var selectionUndo = new SelectionUndo(selectionTracker, transactionName, automaticTracking: false)) {
                    using (ITextEdit edit = textBuffer.CreateEdit()) {
                        // Replace ranges in reverse so relative positions match
                        for (int i = changes.Count - 1; i >= 0; i--)
                        {
                            TextChange tc = changes[i];
                            edit.Replace(tc.Position + position, tc.Length, tc.NewText);
                        }

                        edit.Apply();
                    }
                }
            }
        }
Пример #21
0
        private void DeleteWhiteSpace(ITextBuffer textBuffer)
        {
            ITextEdit EditBuffer = textBuffer.CreateEdit();

            foreach (ITextSnapshotLine Line in EditBuffer.Snapshot.Lines)
            {
                string sLine = Line.GetText();
                int    i     = Line.Length;
                //If this line is empty then move on
                if (i == 0)
                {
                    continue;
                }
                //Start at the end of the line and find the starting index of the whitespace
                while (--i >= 0 && Char.IsWhiteSpace(sLine[i]))
                {
                }
                ;
                ++i;
                //If we found whitespace then remove it, this if check is unnecessary, but avoids us having to call Delete below unnecessarily
                if (i != Line.Length)
                {
                    EditBuffer.Delete(Line.Start.Position + i, Line.Length - i);
                }
            }
            EditBuffer.Apply();
        }
Пример #22
0
        private void UpdateVendorValues(ParseItem item)
        {
            Declaration dec = item.FindType <Declaration>();

            if (dec != null && Cache.Contains(dec) && !dec.IsVendorSpecific())
            {
                // Find all vendor specifics that isn't the standard property.
                var matches = Cache.Where(d => d.IsValid && d != dec && d.Parent == dec.Parent && GetStandardName(d) == dec.PropertyName.Text && d.PropertyName.Text != dec.PropertyName.Text);

                // Undo sometimes messes with the positions, so we have to make this check before proceeding.
                if (!matches.Any() || dec.Text.Length < dec.Colon.AfterEnd - dec.Start || dec.Colon.AfterEnd < dec.Start)
                {
                    return;
                }

                string text = dec.Text.Substring(dec.Colon.AfterEnd - dec.Start, dec.AfterEnd - dec.Colon.AfterEnd);
                using (ITextEdit edit = _buffer.CreateEdit())
                {
                    foreach (Declaration match in matches.Reverse())
                    {
                        SnapshotSpan span = new SnapshotSpan(_buffer.CurrentSnapshot, match.Colon.AfterEnd, match.AfterEnd - match.Colon.AfterEnd);
                        if (span.GetText() != text)
                        {
                            edit.Replace(span, text);
                        }
                    }

                    edit.Apply();
                }
            }
        }
Пример #23
0
 public ITextSnapshot Replace(Span replaceSpan, string replaceWith)
 {
     using (ITextEdit textEdit = CreateEdit())
     {
         textEdit.Replace(replaceSpan, replaceWith);
         return(textEdit.Apply());
     }
 }
Пример #24
0
 public ITextSnapshot Delete(Span deleteSpan)
 {
     using (ITextEdit textEdit = CreateEdit())
     {
         textEdit.Delete(deleteSpan);
         return(textEdit.Apply());
     }
 }
Пример #25
0
 public ITextSnapshot Insert(int position, string text)
 {
     using (ITextEdit textEdit = CreateEdit())
     {
         textEdit.Insert(position, text);
         return(textEdit.Apply());
     }
 }
 /// <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);
     }
 }
Пример #27
0
        public static void SetText(this ITextBuffer buffer, params string[] lines)
        {
            string    text = string.Join(Environment.NewLine, lines);
            ITextEdit edit = buffer.CreateEdit(EditOptions.DefaultMinimalChange, 0, null);

            edit.Replace(new Span(0, buffer.CurrentSnapshot.Length), text);
            edit.Apply();
        }
Пример #28
0
        public void Execute()
        {
            IWpfTextView textView = txtMgr.GetTextView();

            ITextSnapshot snapshot = textView.TextSnapshot;

            if (snapshot != snapshot.TextBuffer.CurrentSnapshot)
            {
                return;
            }

            int selectionLastLineNumber  = 0;
            int selectionFirstLineNumber = 0;

            if (!textView.Selection.IsEmpty)
            {
                selectionLastLineNumber  = textView.Selection.End.Position.GetContainingLine().LineNumber;
                selectionFirstLineNumber = textView.Selection.Start.Position.GetContainingLine().LineNumber;
            }
            else
            {
                selectionFirstLineNumber    =
                    selectionLastLineNumber = textView.GetCaretLine().End.GetContainingLine().LineNumber;
            }

            textView.Selection.Clear();

            try
            {
                using (ITextEdit edit = textView.TextBuffer.CreateEdit())
                {
                    for (int i = selectionLastLineNumber; i >= selectionFirstLineNumber; i--)
                    {
                        var line = textView.GetLine(i);
                        edit.Delete(new Span(line.Start.Position, line.LengthIncludingLineBreak));
                    }
                    edit.Apply();
                }
            }
            catch
            {
            }

            ////ITextSnapshotLine currentLineContent = snapshot.GetLineFromPosition(textView.Caret.Position.BufferPosition);
            //ITextViewLine currentLineContent = textView.Caret.ContainingTextViewLine;

            //double initialStartPosition =  textView.Caret.Left;

            //ITextEdit edit = snapshot.TextBuffer.CreateEdit();
            //edit.Delete(currentLineContent.Start.Position, currentLineContent.LengthIncludingLineBreak);
            //edit.Apply();

            //ITextSnapshotLine newCurrentLineContent = snapshot.GetLineFromPosition(textView.Caret.Position.BufferPosition);

            ////make a new selection
            //ITextViewLine line = textView.Caret.ContainingTextViewLine;
            //textView.Caret.MoveTo(line, initialStartPosition - 1);
        }
        void UncommentSpan(SnapshotSpan span, ITextEdit textEdit, List <ITrackingSpan> spansToSelect)
        {
            if (TryUncommentSingleLineComments(span, textEdit, spansToSelect))
            {
                return;
            }

            TryUncommentContainingBlockComment(span, textEdit, spansToSelect);
        }
Пример #30
0
            public void PreOverType(out bool handledCommand)
            {
                handledCommand = false;
                if (ClosingPoint == null)
                {
                    return;
                }

                // Brace completion is not cancellable.
                var cancellationToken = CancellationToken.None;
                var snapshot          = this.SubjectBuffer.CurrentSnapshot;
                var document          = snapshot.GetOpenDocumentInCurrentContextWithChanges();

                SnapshotPoint closingSnapshotPoint = ClosingPoint.GetPoint(snapshot);

                if (!HasForwardTyping && _session.AllowOverType(this, cancellationToken))
                {
                    SnapshotPoint?caretPos = this.GetCaretPosition();

                    Debug.Assert(caretPos.HasValue && caretPos.Value.Position < closingSnapshotPoint.Position);

                    // ensure that we are within the session before clearing
                    if (caretPos.HasValue && caretPos.Value.Position < closingSnapshotPoint.Position && closingSnapshotPoint.Position > 0)
                    {
                        using (ITextUndoTransaction undo = CreateUndoTransaction())
                        {
                            _editorOperations.AddBeforeTextBufferChangePrimitive();

                            SnapshotSpan span = new SnapshotSpan(caretPos.Value, closingSnapshotPoint.Subtract(1));

                            using (ITextEdit edit = SubjectBuffer.CreateEdit())
                            {
                                edit.Delete(span);

                                if (edit.HasFailedChanges)
                                {
                                    Debug.Fail("Unable to clear closing brace");
                                    edit.Cancel();
                                    undo.Cancel();
                                }
                                else
                                {
                                    handledCommand = true;

                                    edit.Apply();

                                    MoveCaretToClosingPoint();

                                    _editorOperations.AddAfterTextBufferChangePrimitive();

                                    undo.Complete();
                                }
                            }
                        }
                    }
                }
            }
        private void CreateMethodComment(ITextChange change)
        {
            int    position = change.NewEnd;
            string text     = this.view.TextSnapshot.ToString();

            using (ITextEdit editor = this.view.TextBuffer.CreateEdit())
            {
                try
                {
                    this.tabs = StubUtils.GetIndention(position, this.view.TextSnapshot);
                    string summaryString = StubUtils.Options.MultiLineSummary ? NewLine() : "";


                    string parameters = GetFunctionParameters(position);
                    string returnTag  = GetReturnTag(position);


                    string commentBody = summaryString + parameters + returnTag;
                    string autoComment = this.tabs + "/**" + commentBody;
                    if (!String.IsNullOrEmpty(commentBody))
                    {
                        autoComment += Environment.NewLine + this.tabs;
                    }

                    autoComment += " */";


                    int  lineStart     = this.view.TextSnapshot.GetLineFromPosition(position).Start.Position;
                    Span firstLineSpan = new Span(lineStart, change.NewSpan.End - lineStart);
                    editor.Replace(firstLineSpan, autoComment);

                    ITextSnapshot after = editor.Apply();

                    ////Move the caret back at the comment description

                    //int lineNumber = after.GetLineNumberFromPosition(change.NewPosition);
                    //var lineSnapShotPoint = after.GetLineFromLineNumber(lineNumber).End;
                    //this.view.Caret.MoveTo(lineSnapShotPoint);

                    //view.Caret.MoveTo(
                    //    view.GetTextViewLineContainingBufferPosition(
                    //        after.GetLineFromPosition(
                    //            after.GetText().IndexOf(autoComment)).Start));


                    //view.Caret.MoveTo(
                    //    view.GetTextViewLineContainingBufferPosition(
                    //        view.TextSnapshot.GetLineFromPosition(
                    //            view.TextSnapshot.GetText().IndexOf(fn)).Start));
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ERROR_MSG_PREFIX + ex.Message);
                }
            }
        }
Пример #32
0
        public override bool Unindent()
        {
            if (_startPoint.LineNumber == _endPoint.LineNumber)
            {
                return(_startPoint.RemovePreviousIndent());
            }

            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) && (_endPoint.CurrentPosition != line.Start))
                    {
                        if (snapshot[line.Start] == '\t')
                        {
                            if (!edit.Delete(new Span(line.Start, 1)))
                            {
                                return(false);
                            }
                        }
                        else
                        {
                            int spacesToRemove = 0;
                            for (; (line.Start + spacesToRemove < snapshot.Length) && (spacesToRemove < _editorOptions.GetTabSize());
                                 spacesToRemove++)
                            {
                                if (snapshot[line.Start + spacesToRemove] != ' ')
                                {
                                    break;
                                }
                            }

                            if (spacesToRemove > 0)
                            {
                                if (!edit.Delete(new Span(line.Start, spacesToRemove)))
                                {
                                    return(false);
                                }
                            }
                        }
                    }
                }

                edit.Apply();

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

            return(true);
        }
Пример #33
0
    public bool ApplyChanges(ITextEdit textEdit, FormatLinesResult result) {
      var lineEnding = DetectLineEnding(textEdit.Snapshot);

      var sb = new StringBuilder();
      var indent = new string(' ', result.Indent);
      foreach (var line in result.Lines) {
        if (sb.Length > 0)
          sb.Append(lineEnding);
        sb.Append(indent);
        sb.Append(result.CommentType.TextPrefix);
        sb.Append(line);
      }
      var commentText = sb.ToString();
      var oldSpan = result.SnapshotSpan.Span;
      var oldText = textEdit.Snapshot.GetText(oldSpan);
      if (oldText == commentText)
        return false;

      textEdit.Replace(oldSpan, commentText);
      return true;
    }
Пример #34
0
 public Edit(ITextEdit edit)
 {
     m_edit = edit;
 }
Пример #35
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);
     }
 }
Пример #36
0
 public TextDockWidget()
 {
     mTextEdit = null;
 }
Пример #37
0
 private static void DeleteFirstCommentChar(ITextEdit edit, ITextSnapshotLine curLine)
 {
     var text = curLine.GetText();
     for (int j = 0; j < text.Length; j++) {
         if (!Char.IsWhiteSpace(text[j])) {
             if (text[j] == '#') {
                 edit.Delete(curLine.Start.Position + j, 1);
             }
             break;
         }
     }
 }
Пример #38
0
 public TacticReplaceStatus ReplaceSingleTacticCall(ITextEdit tedit)
 {
   Contract.Requires(tedit != null);
   if (!MemberReady || _tacticCall==null) return TacticReplaceStatus.NoTactic;
   
   string expanded;
   var expandedStatus = ExpandSingleTacticCall(_tacticCall.Item1, out expanded);
   if (expandedStatus != TacticReplaceStatus.Success)
     return expandedStatus;
   
   tedit.Replace(_tacticCall.Item2, _tacticCall.Item3 - _tacticCall.Item2, expanded);
   return TacticReplaceStatus.Success;
 }
Пример #39
0
 public void SetText(ITextSnapshotLine line, int startIndex, int length, string newText, ITextEdit edit)
 {
     var replaceSpan = new Span(line.Extent.Start.Position + startIndex, length);
     edit.Replace(replaceSpan, newText);
 }
        internal void TrimTrailingWhitespace(ITextSnapshot snapshot, ITextEdit edit)
        {
            foreach (ITextSnapshotLine line in snapshot.Lines)
            {
                var text = line.GetText();

                if (text != null)
                {
                    int index = text.Length - 1;

                    while (index >= 0 && char.IsWhiteSpace(text[index]))
                        index--;

                    if (index < text.Length - 1)
                        edit.Delete(line.Start.Position + index + 1, text.Length - index - 1);
                }
            }
        }
        /// <summary>
        /// Enforce line endings to follow the rules defined in the EditorConfig file.
        /// </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 line ending to enforce.</param>
        internal void FixLineEndings(ITextSnapshot snapshot, ITextEdit edit, string eol)
        {
            if (eol == null)
            {
                return;
            }

            foreach (ITextSnapshotLine line in snapshot.Lines)
            {
                var lineBreak = line.GetLineBreakText();

                if (!string.IsNullOrEmpty(lineBreak) && lineBreak != eol)
                    edit.Replace(line.End.Position, line.LineBreakLength, eol);
            }
        }
Пример #42
0
        /// <summary>
        /// Comment out the code in a single <see cref="VirtualSnapshotSpan"/>.
        /// </summary>
        /// <remarks>
        /// <para>The default implementation uses line comments if <see cref="UseLineComments"/> is
        /// <see langword="true"/> and one of the following is true.</para>
        /// <list type="number">
        /// <item>There is no selected text.</item>
        /// <item>
        /// On the line where the selection starts, there is only whitespace up to the selection start point,
        /// <strong>and</strong> one of the following is true.
        /// <list type="bullet">
        /// <item>On the line where the selection ends, there is only whitespace up to the selection end point,
        /// <strong>or</strong></item>
        /// <item>There is only whitespace from the selection end point to the end of the line.</item>
        /// </list>
        /// </item>
        /// </list>
        ///
        /// <para>The default implementation uses block comments if <em>all</em> of the following are true.</para>
        /// <list type="bullet">
        /// <item>We are not using line comments.</item>
        /// <item><see cref="PreferredBlockFormat"/> is not <see langword="null"/>.</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>
        /// <returns>A <see cref="VirtualSnapshotSpan"/> containing the commented code.</returns>
        protected virtual VirtualSnapshotSpan CommentSpan(VirtualSnapshotSpan span, ITextEdit edit)
        {
            Contract.Requires<ArgumentNullException>(edit != null, "edit");

            span = span.TranslateTo(edit.Snapshot, SpanTrackingMode.EdgeExclusive);

            var startContainingLine = span.Start.Position.GetContainingLine();
            var endContainingLine = span.End.Position.GetContainingLine();

            if (UseLineComments
                && (span.IsEmpty ||
                    (string.IsNullOrWhiteSpace(startContainingLine.GetText().Substring(0, span.Start.Position - startContainingLine.Start))
                        && (string.IsNullOrWhiteSpace(endContainingLine.GetText().Substring(0, span.End.Position - endContainingLine.Start))
                            || string.IsNullOrWhiteSpace(endContainingLine.GetText().Substring(span.End.Position - endContainingLine.Start)))
                   )))
            {
                span = CommentLines(span, edit, PreferredLineFormat);
            }
            else if (PreferredBlockFormat != null)
            {
                span = CommentBlock(span, edit, PreferredBlockFormat);
            }

            return span;
        }
Пример #43
0
        /// <summary>
        /// Attempt to uncomment a span of text using any of a collection of line comment formats.
        /// </summary>
        /// <param name="span">The span of text to uncomment.</param>
        /// <param name="edit">The <see cref="ITextEdit"/> instance to use for applying changes.</param>
        /// <param name="formats">The line comment formats to use for attempting to uncomment the code.</param>
        /// <param name="result">Upon return, a <see cref="VirtualSnapshotSpan"/> containing the uncommented
        /// code.</param>
        /// <returns>
        /// <para><see langword="true"/> if one or more lines of the span of text were successfully uncommented using
        /// one of the specified line comment <paramref name="formats"/>.</para>
        /// <para>-or-</para>
        /// <para><see langword="false"/> if none of the lines in the span of text could be uncommented using any of the
        /// specified <paramref name="formats"/>.</para>
        /// </returns>
        /// <exception cref="ArgumentNullException">
        /// <para>If <paramref name="edit"/> is <see langword="null"/>.</para>
        /// <para>-or-</para>
        /// <para>If <paramref name="formats"/> is <see langword="null"/>.</para>
        /// </exception>
        /// <exception cref="ArgumentException">If <paramref name="formats"/> contains any <see langword="null"/>
        /// values.</exception>
        protected virtual bool TryUncommentLines(VirtualSnapshotSpan span, ITextEdit edit, ReadOnlyCollection<LineCommentFormat> formats, out VirtualSnapshotSpan result)
        {
            Contract.Requires<ArgumentNullException>(edit != null, "edit");
            Contract.Requires<ArgumentNullException>(formats != null, "formats");
            Contract.Requires(Contract.ForAll(formats, i => i != null));

            if (span.End.Position.GetContainingLine().LineNumber > span.Start.Position.GetContainingLine().LineNumber && span.End.Position == span.End.Position.GetContainingLine().Start)
            {
                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);
            }

            // Remove line comments
            bool containedComments = false;
            for (int line = span.Start.Position.GetContainingLine().LineNumber; line <= span.End.Position.GetContainingLine().LineNumber; line++)
            {
                int i = ScanToNonWhitespaceChar(span.Snapshot.GetLineFromLineNumber(line));
                string text = span.Snapshot.GetLineFromLineNumber(line).GetText();
                foreach (var format in formats)
                {
                    int clen = format.StartText.Length;
                    if ((text.Length > i + clen) && text.Substring(i, clen).Equals(format.StartText, StringComparison.Ordinal))
                    {
                        // remove line comment.
                        edit.Delete(span.Snapshot.GetLineFromLineNumber(line).Start.Position + i, clen);
                        containedComments = true;
                        break;
                    }
                }
            }

            span = new VirtualSnapshotSpan(new SnapshotSpan(span.Start.Position.GetContainingLine().Start, span.End.Position.GetContainingLine().End));
            result = span;
            return containedComments;
        }
Пример #44
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;
        }
Пример #45
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;
        }
        private int SwapItemWithNextSibling(ParseItem item, ITextEdit edit)
        {
            RuleSet next = item.NextSibling as RuleSet;
            if (next == null)
                return -1;

            ITextSnapshot snapshot = _textView.TextBuffer.CurrentSnapshot;
            string whitespace = snapshot.GetText(item.AfterEnd, next.Start - item.AfterEnd);
            string text = next.Text + whitespace + item.Text;

            edit.Replace(item.Start, next.AfterEnd - item.Start, text);
            edit.Apply();

            return item.Start + next.Length + whitespace.Length;
        }
            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);
                }
            }
Пример #48
0
        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;
        }
Пример #49
0
        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()
                );
            }
        }
Пример #50
0
        protected virtual SnapshotSpan UncommentSpan(SnapshotSpan span, ITextEdit edit)
        {
            Contract.Requires<ArgumentNullException>(edit != null, "edit");

            span = span.TranslateTo(edit.Snapshot, SpanTrackingMode.EdgeExclusive);
            bool useLineComments = true;
            var startContainingLine = span.Start.GetContainingLine();
            var endContainingLine = span.End.GetContainingLine();

            // special case: empty span
            if (span.IsEmpty)
            {
                if (useLineComments)
                    span = UncommentLines(span, edit, LineFormats);
            }
            else
            {
                SnapshotSpan resultSpan;
                if (TryUncommentBlock(span, edit, BlockFormats, out resultSpan))
                    return resultSpan;

                if (useLineComments)
                {
                    span = UncommentLines(span, edit, LineFormats);
                }
            }

            return span;
        }
        /// <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);
            }
        }
Пример #52
0
        private void AdjustIndentationForSpan(
            Document document, ITextEdit edit, TextSpan visibleSpan, IFormattingRule baseIndentationRule, OptionSet options)
        {
            var root = document.GetSyntaxRootAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None);

            using (var rulePool = SharedPools.Default<List<IFormattingRule>>().GetPooledObject())
            using (var spanPool = SharedPools.Default<List<TextSpan>>().GetPooledObject())
            {
                var venusFormattingRules = rulePool.Object;
                var visibleSpans = spanPool.Object;

                venusFormattingRules.Add(baseIndentationRule);
                venusFormattingRules.Add(ContainedDocumentPreserveFormattingRule.Instance);

                var formattingRules = venusFormattingRules.Concat(Formatter.GetDefaultFormattingRules(document));

                var workspace = document.Project.Solution.Workspace;
                var changes = Formatter.GetFormattedTextChanges(
                    root, new TextSpan[] { CommonFormattingHelpers.GetFormattingSpan(root, visibleSpan) },
                    workspace, options, formattingRules, CancellationToken.None);

                visibleSpans.Add(visibleSpan);
                var newChanges = FilterTextChanges(document.GetTextAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None), visibleSpans, changes.ToReadOnlyCollection()).Where(t => visibleSpan.Contains(t.Span));

                foreach (var change in newChanges)
                {
                    edit.Replace(change.Span.ToSpan(), change.NewText);
                }
            }
        }
Пример #53
0
        protected virtual SnapshotSpan CommentSpan(SnapshotSpan span, ITextEdit edit)
        {
            Contract.Requires<ArgumentNullException>(edit != null, "edit");

            span = span.TranslateTo(edit.Snapshot, SpanTrackingMode.EdgeExclusive);

            /*
             * Use line comments if:
             *  UseLineComments is true
             *  AND one of the following is true:
             *
             *  1. there is no selected text
             *  2. on the line where the selection starts, there is only whitespace up to the selection start point
             *     AND on the line where the selection ends, there is only whitespace up to the selection end point,
             *         OR there is only whitespace from the selection end point to the end of the line
             *
             * Use block comments if:
             *  We are not using line comments
             *  AND some text is selected
             *  AND PreferredBlockFormat is not null
             */
            var startContainingLine = span.Start.GetContainingLine();
            var endContainingLine = span.End.GetContainingLine();

            if (UseLineComments
                && (span.IsEmpty ||
                    (string.IsNullOrWhiteSpace(startContainingLine.GetText().Substring(0, span.Start - startContainingLine.Start))
                        && (string.IsNullOrWhiteSpace(endContainingLine.GetText().Substring(0, span.End - endContainingLine.Start))
                            || string.IsNullOrWhiteSpace(endContainingLine.GetText().Substring(span.End - endContainingLine.Start)))
                   )))
            {
                span = CommentLines(span, edit, PreferredLineFormat);
            }
            else if (
                span.Length > 0
                && PreferredBlockFormat != null
                )
            {
                span = CommentBlock(span, edit, PreferredBlockFormat);
            }

            return span;
        }
 private static ITextSnapshot ApplyEdit(ITextEdit edit)
 {
     using (edit)
         return edit.Apply();
 }
Пример #55
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;
        }
Пример #56
0
        protected virtual bool TryUncommentBlock(SnapshotSpan span, ITextEdit edit, ReadOnlyCollection<BlockCommentFormat> formats, out SnapshotSpan result)
        {
            Contract.Requires<ArgumentNullException>(edit != null, "edit");
            Contract.Requires<ArgumentNullException>(formats != null, "formats");
            Contract.Requires(Contract.ForAll(formats, i => i != null));

            foreach (var format in formats)
            {
                if (TryUncommentBlock(span, edit, format, out result))
                    return true;
            }

            result = default(SnapshotSpan);
            return false;
        }
Пример #57
0
        protected virtual SnapshotSpan UncommentLines(SnapshotSpan span, ITextEdit edit, ReadOnlyCollection<LineCommentFormat> formats)
        {
            Contract.Requires<ArgumentNullException>(edit != null, "edit");
            Contract.Requires<ArgumentNullException>(formats != null, "formats");
            Contract.Requires(Contract.ForAll(formats, i => i != null));

            if (span.End.GetContainingLine().LineNumber > span.Start.GetContainingLine().LineNumber && span.End == span.End.GetContainingLine().Start)
            {
                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);
            }

            // Remove line comments
            for (int line = span.Start.GetContainingLine().LineNumber; line <= span.End.GetContainingLine().LineNumber; line++)
            {
                int i = ScanToNonWhitespaceChar(span.Snapshot.GetLineFromLineNumber(line));
                string text = span.Snapshot.GetLineFromLineNumber(line).GetText();
                foreach (var format in formats)
                {
                    int clen = format.StartText.Length;
                    if ((text.Length > i + clen) && text.Substring(i, clen) == format.StartText)
                    {
                        // remove line comment.
                        edit.Delete(span.Snapshot.GetLineFromLineNumber(line).Start.Position + i, clen);
                        break;
                    }
                }
            }

            span = new SnapshotSpan(span.Start.GetContainingLine().Start, span.End.GetContainingLine().End);
            return span;
        }
Пример #58
0
 private int SpacesOnLine(ITextEdit edit, ITextSnapshotLine line)
 {
     int spaces = 0;
     for (int c = line.Start; c < line.End; c++)
     {
         if (edit.Snapshot[c] == ' ')
             spaces++;
         else break;
     }
     return spaces;
 }
Пример #59
0
        protected virtual bool TryUncommentBlock(SnapshotSpan span, ITextEdit edit, BlockCommentFormat format, out SnapshotSpan result)
        {
            Contract.Requires<ArgumentNullException>(edit != null, "edit");
            Contract.Requires<ArgumentNullException>(format != null, "format");

            string blockStart = format.StartText;
            string blockEnd = format.EndText;

            int startLen = span.Start.GetContainingLine().Length;
            int endLen = span.End.GetContainingLine().Length;

            TrimSpan(ref span);

            //sp. case no selection, try and uncomment the current line.
            if (span.IsEmpty)
            {
                span = new SnapshotSpan(span.Start.GetContainingLine().Start + ScanToNonWhitespaceChar(span.Start.GetContainingLine()), span.End.GetContainingLine().End);
            }

            // Check that comment start and end blocks are possible.
            if ((span.Start - span.Start.GetContainingLine().Start) + blockStart.Length <= startLen && (span.End - span.End.GetContainingLine().Start) - blockStart.Length >= 0)
            {
                string startText = span.Snapshot.GetText(span.Start.Position, blockStart.Length);

                if (startText == blockStart)
                {
                    SnapshotSpan linespan = span;
                    linespan = new SnapshotSpan(span.End - blockEnd.Length, span.End);
                    string endText = linespan.GetText();
                    if (endText == blockEnd)
                    {
                        //yes, block comment selected; remove it
                        edit.Delete(linespan);
                        edit.Delete(span.Start.Position, blockStart.Length);
                        result = span;
                        return true;
                    }
                }
            }

            result = default(SnapshotSpan);
            return false;
        }
		protected abstract void Modify(ITextEdit edit, ITextSnapshotLine line);