Ejemplo n.º 1
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)
                    {
                    }
                }
            }
        }
Ejemplo n.º 2
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();
                    }
                }
            }
        }
Ejemplo n.º 3
0
        static void DeleteExistingDefinition(ITextSnapshot snapshot, Parser.Result result)
        {
            DTE2      dte  = Global.GetDTE2();
            ITextEdit edit = snapshot.TextBuffer.CreateEdit();

            try
            {
                ITextSnapshotLine currentLine;
                for (int i = result.StartLine - 1; i <= result.EndLine - 1; i++)
                {
                    currentLine = snapshot.GetLineFromLineNumber(i);
                    edit.Delete(currentLine.Start.Position, currentLine.LengthIncludingLineBreak);
                }

                //remove separating empty line if found
                if (snapshot.LineCount > result.EndLine)
                {
                    currentLine = snapshot.GetLineFromLineNumber(result.EndLine);
                    if (string.IsNullOrWhiteSpace(currentLine.GetText()))
                    {
                        edit.Delete(currentLine.Start.Position, currentLine.LengthIncludingLineBreak);
                    }
                }

                edit.Apply();
            }
            catch
            {
                edit.Cancel();
            }

            dte.ActiveDocument.Save();
        }
        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();
                }
            }
        }
        public void SuppressError(string errorCode)
        {
            if (string.IsNullOrEmpty(errorCode) || _document.Suppressions.Contains(errorCode))
            {
                return;
            }

            var range = new Span(0, 0);
            IEnumerable <string> errorCodes = _document.Suppressions.Union(new[] { errorCode }).OrderBy(c => c);

            if (_document.Suppressions.Any())
            {
                int position           = _document.ParseItems.First().Span.Start;
                ITextSnapshotLine line = _document.TextBuffer.CurrentSnapshot.GetLineFromPosition(position);
                range = Span.FromBounds(line.Start, line.EndIncludingLineBreak);
            }

            string text = string.Format("# Suppress: {0}", string.Join(" ", errorCodes)) + Environment.NewLine;

            using (ITextEdit edit = _document.TextBuffer.CreateEdit())
            {
                edit.Replace(range, text);
                edit.Apply();
            }
        }
Ejemplo n.º 6
0
        public async override void Invoke(CancellationToken cancellationToken)
        {
            ImageCompressor compressor = new ImageCompressor();

            bool isDataUri = Attribute.Value.StartsWith("data:image/", StringComparison.Ordinal);

            if (isDataUri)
            {
                string dataUri = await compressor.CompressDataUriAsync(Attribute.Value);

                if (dataUri.Length < Attribute.Value.Length)
                {
                    using (WebEssentialsPackage.UndoContext(this.DisplayText))
                        using (ITextEdit edit = TextBuffer.CreateEdit())
                        {
                            Span span = Span.FromBounds(Attribute.ValueRangeUnquoted.Start, Attribute.ValueRangeUnquoted.End);
                            edit.Replace(span, dataUri);
                            edit.Apply();
                        }
                }
            }
            else
            {
                var fileName = ImageQuickInfo.GetFullUrl(Attribute.Value, TextBuffer);

                if (string.IsNullOrEmpty(fileName) || !ImageCompressor.IsFileSupported(fileName) || !File.Exists(fileName))
                {
                    return;
                }

                await compressor.CompressFilesAsync(fileName);
            }
        }
Ejemplo n.º 7
0
        private void RemoveTrailingWhitespace(ITextBuffer buffer)
        {
            bool foundWhitespace = false;

            using (ITextEdit edit = buffer.CreateEdit())
            {
                ITextSnapshot snap = edit.Snapshot;

                foreach (ITextSnapshotLine line in snap.Lines)
                {
                    string text   = line.GetText();
                    int    length = text.Length;
                    while (--length >= 0 && Char.IsWhiteSpace(text[length]))
                    {
                        ;
                    }
                    if (length < text.Length - 1)
                    {
                        int start = line.Start.Position;
                        edit.Delete(start + length + 1, text.Length - length - 1);
                        foundWhitespace = true;
                    }
                }

                edit.Apply();
            }

            if (foundWhitespace)
            {
                Telemetry.TrackEvent("On save");
            }
        }
Ejemplo n.º 8
0
        /// <inheritdoc />
        public void Commit()
        {
            if (!session.SelectedCompletionSet.SelectionStatus.IsSelected)
            {
                return;
            }

            ITrackingSpan applicableTo = session.SelectedCompletionSet.ApplicableTo;

            using (ITextEdit edit = applicableTo.TextBuffer.CreateEdit())
            {
                // The insertion text is inserted without the \xFF character (if any)
                string insertionText = InsertionText.Replace("\xFF", "");
                edit.Replace(applicableTo.GetSpan(edit.Snapshot), insertionText);
                ITextSnapshot applied = edit.Apply();

                // The original position of the \xFF character determines the placement of the caret
                int caretOffset = InsertionText.IndexOf('\xFF');

                if (caretOffset >= 0)
                {
                    SnapshotPoint startPoint = applicableTo.GetStartPoint(applied);
                    SnapshotPoint caretPoint = startPoint + caretOffset;
                    session.TextView.Caret.MoveTo(caretPoint, PositionAffinity.Predecessor);
                }
            }
        }
Ejemplo n.º 9
0
        public override bool Capitalize()
        {
            int startPosition = _startPoint.CurrentPosition;

            if (IsEmpty)
            {
                int       endPosition   = _endPoint.CurrentPosition;
                TextRange currentWord   = _startPoint.GetCurrentWord();
                string    nextCharacter = _startPoint.GetNextCharacter();
                if (_startPoint.CurrentPosition == currentWord.GetStartPoint().CurrentPosition)
                {
                    nextCharacter = nextCharacter.ToUpper(CultureInfo.CurrentCulture);
                }
                else
                {
                    nextCharacter = nextCharacter.ToLower(CultureInfo.CurrentCulture);
                }
                if (!PrimitivesUtilities.Replace(TextBuffer.AdvancedTextBuffer, new Span(_startPoint.CurrentPosition, nextCharacter.Length), nextCharacter))
                {
                    return(false);
                }
                _endPoint.MoveTo(endPosition);
            }
            else
            {
                using (ITextEdit edit = TextBuffer.AdvancedTextBuffer.CreateEdit())
                {
                    TextRange currentWord = _startPoint.GetCurrentWord();

                    // If the current word extends past this range, go to the next word
                    if (currentWord.GetStartPoint().CurrentPosition < _startPoint.CurrentPosition)
                    {
                        currentWord = currentWord.GetEndPoint().GetNextWord();
                    }

                    while (currentWord.GetStartPoint().CurrentPosition < _endPoint.CurrentPosition)
                    {
                        string wordText     = currentWord.GetText();
                        string startElement = StringInfo.GetNextTextElement(wordText);
                        wordText = startElement.ToUpper(CultureInfo.CurrentCulture) + wordText.Substring(startElement.Length).ToLower(CultureInfo.CurrentCulture);
                        if (!edit.Replace(currentWord.AdvancedTextRange.Span, wordText))
                        {
                            edit.Cancel();
                            return(false);
                        }

                        currentWord = currentWord.GetEndPoint().GetNextWord();
                    }

                    edit.Apply();

                    if (edit.Canceled)
                    {
                        return(false);
                    }
                }
            }
            _startPoint.MoveTo(startPosition);
            return(true);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Removes white space from both ends of a line.
        /// </summary>
        private void StripWhiteSpace(ITextSnapshotLine line)
        {
            ITextSnapshot snapshot = line.Snapshot;
            ITextBuffer   buffer   = snapshot.TextBuffer;

            int forwardIterator;
            int backwardIterator;

            // Detect spaces at the beginning
            forwardIterator = line.Start.Position;
            while (forwardIterator < line.End.Position && IsSpaceCharacter(snapshot[forwardIterator]))
            {
                ++forwardIterator;
            }

            // Detect spaces at the end
            backwardIterator = line.End.Position - 1;
            while (backwardIterator > forwardIterator && IsSpaceCharacter(snapshot[backwardIterator]))
            {
                --backwardIterator;
            }

            if ((backwardIterator != line.End.Position - 1) || (forwardIterator != line.Start.Position))
            {
                using (ITextEdit edit = buffer.CreateEdit())
                {
                    edit.Delete(Span.FromBounds(backwardIterator + 1, line.End.Position));
                    edit.Delete(Span.FromBounds(line.Start.Position, forwardIterator));

                    edit.Apply();
                }
            }
        }
Ejemplo n.º 11
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);
        }
Ejemplo n.º 12
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);
        }
        /// <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);
        }
        public override void Invoke(CancellationToken cancellationToken)
        {
            string mimeType  = FileHelpers.GetMimeTypeFromBase64(Attribute.Value);
            string extension = FileHelpers.GetExtension(mimeType) ?? "png";

            string 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();
                }
            }
        }
        /// <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;

                _beforeVersion = null;
                _afterVersion  = TextBuffer.CurrentSnapshot.Version.VersionNumber;
            }

            bool editCanceled = false;
            using (ITextEdit edit = TextBuffer.CreateEdit(EditOptions.None, _beforeVersion, typeof(TextBufferChangeUndoPrimitive)))
            {
                foreach (ITextChange textChange in _textChanges)
                {
                    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 (_beforeVersion == null)
            {
                _beforeVersion = TextBuffer.CurrentSnapshot.Version.VersionNumber;
            }

            _canUndo = false;
        }
Ejemplo n.º 16
0
        private void StripWhiteSpace(ITextSnapshotLine line)
        {
            ITextSnapshot snapshot   = line.Snapshot;
            ITextBuffer   textBuffer = snapshot.TextBuffer;
            int           position   = line.Start.Position;

            while (position < line.End.Position && IsSpaceCharacter(snapshot[position]))
            {
                ++position;
            }
            int index = line.End.Position - 1;

            while (index > position && IsSpaceCharacter(snapshot[index]))
            {
                --index;
            }
            if (index == line.End.Position - 1 && position == line.Start.Position)
            {
                return;
            }
            using (ITextEdit edit = textBuffer.CreateEdit())
            {
                edit.Delete(Span.FromBounds(index + 1, line.End.Position));
                edit.Delete(Span.FromBounds(line.Start.Position, position));
                edit.Apply();
            }
        }
Ejemplo n.º 17
0
        private async Task <bool> MakePrettierAsync()
        {
            string input  = _view.TextBuffer.CurrentSnapshot.GetText();
            string output = await _node.ExecuteProcessAsync(input, _encoding, _filePath);

            VirtualSnapshotPoint snapshotPoint = _view.Selection.ActivePoint;

            if (string.IsNullOrEmpty(output) || input == output)
            {
                return(false);
            }

            using (ITextEdit edit = _view.TextBuffer.CreateEdit())
                using (ITextUndoTransaction undo = _undoManager.TextBufferUndoHistory.CreateTransaction("Make Prettier"))
                {
                    edit.Replace(0, _view.TextBuffer.CurrentSnapshot.Length, output);
                    edit.Apply();

                    undo.Complete();
                }

            var newSnapshotPoint = new SnapshotPoint(_view.TextBuffer.CurrentSnapshot, snapshotPoint.Position.Position);

            _view.Caret.MoveTo(newSnapshotPoint);
            _view.ViewScroller.EnsureSpanVisible(new SnapshotSpan(newSnapshotPoint, 0));

            return(true);
        }
Ejemplo n.º 18
0
        public override void Invoke(CancellationToken cancellationToken)
        {
            var content = Element.GetText(Element.InnerRange).Trim();
            int start   = Element.Start;
            int length  = content.Length;

            try
            {
                ProjectHelpers.DTE.UndoContext.Open(DisplayText);
                using (ITextEdit edit = TextBuffer.CreateEdit())
                {
                    edit.Replace(Element.OuterRange.ToSpan(), content);
                    edit.Apply();
                }

                SnapshotSpan span = new SnapshotSpan(TextView.TextBuffer.CurrentSnapshot, start, length);

                TextView.Selection.Select(span, false);
                ProjectHelpers.DTE.ExecuteCommand("Edit.FormatSelection");
                TextView.Caret.MoveTo(new SnapshotPoint(TextView.TextBuffer.CurrentSnapshot, start));
                TextView.Selection.Clear();
            }
            finally
            {
                ProjectHelpers.DTE.UndoContext.Close();
            }
        }
        private async Task MakeChanges(string root, string fileName)
        {
            string text      = Element.GetText(Element.InnerRange).Trim();
            string reference = GetReference(Element, fileName, root);

            try
            {
                ProjectHelpers.DTE.UndoContext.Open(DisplayText);
                using (ITextEdit edit = TextBuffer.CreateEdit())
                {
                    edit.Replace(new Span(Element.Start, Element.Length), reference);
                    edit.Apply();
                }

                File.WriteAllText(fileName, text);
                ProjectHelpers.AddFileToActiveProject(fileName);
                ProjectHelpers.DTE.ItemOperations.OpenFile(fileName);

                await Dispatcher.CurrentDispatcher.BeginInvoke(new Action(() =>
                {
                    ProjectHelpers.DTE.ExecuteCommand("Edit.FormatDocument");
                }), DispatcherPriority.ApplicationIdle, null);
            }
            finally
            {
                ProjectHelpers.DTE.UndoContext.Close();
            }
        }
Ejemplo n.º 20
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();
        }
        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 == "id");

                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);
            }
        }
Ejemplo n.º 22
0
        public override async void Invoke(CancellationToken cancellationToken)
        {
            try
            {
                await LibraryHelpers.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         = arrayElement.PreviousSibling as JSONArrayElement;
                    var next         = arrayElement.NextSibling 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(), Microsoft.Web.LibraryManager.Contracts.LogLevel.Error);
            }
        }
Ejemplo n.º 23
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 (commentLineStart.IsMatch(lineText) && (commentLineStart.IsMatch(nextLine) || change.OldEnd != line.End.Position))
                    {
                        int asteriskIndex = 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 + asteriskIndex) > change.OldEnd)
                        {
                            return;
                        }

                        int tabsStopIndex = -1;
                        if (asteriskIndex >= 0 || lineText.Contains("/**"))
                        {
                            // There's no slash, or its open-comment line, so it's a jsdoc comment. We need asteriskIndex here.
                            tabsStopIndex = asteriskIndex;
                        }

                        string newTabs = tabsStopIndex >= 0 ? lineText.Substring(0, tabsStopIndex) : "";
                        newTabs = newTabs.Replace('/', ' ');
                        editor.Replace(change.NewSpan, Environment.NewLine + newTabs + "* ");
                        editor.Apply();
                    }
                }
                catch (Exception) { }
            }
        }
Ejemplo n.º 24
0
        internal override void Execute(EmacsCommandContext context)
        {
            SnapshotSpan?previousWord = context.TextStructureNavigator.GetPreviousWord(context.TextView);

            if (!previousWord.HasValue ||
                !previousWord.Value.IntersectsWith(new Span(context.TextView.GetCaretPosition(), 1)))
            {
                return;
            }
            SnapshotSpan?nextWord = context.TextStructureNavigator.GetNextWord(previousWord.Value.End);

            if (!nextWord.HasValue)
            {
                return;
            }
            string text1 = context.TextView.TextSnapshot.GetText(previousWord.Value);
            string text2 = context.TextView.TextSnapshot.GetText(nextWord.Value);

            using (ITextEdit edit = context.TextView.TextBuffer.CreateEdit())
            {
                edit.Replace(nextWord.Value, text1);
                edit.Replace(previousWord.Value, text2);
                edit.Apply();
            }
            context.TextView.Caret.MoveTo(new SnapshotPoint(context.TextView.TextSnapshot, nextWord.Value.End));
            context.TextView.Caret.EnsureVisible();
        }
Ejemplo n.º 25
0
        public static void Insert(this IWpfTextView obj, int position, string text)
        {
            ITextEdit edit = obj.TextSnapshot.TextBuffer.CreateEdit();

            edit.Insert(position, text);
            edit.Apply();
        }
Ejemplo n.º 26
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();
            }
Ejemplo n.º 27
0
        private bool Format(SnapshotSpan span)
        {
            if (span.Snapshot.TextBuffer != this.textBuffer || span.IsEmpty || !this.CanFormatSpan(span))
            {
                return(false);
            }

            SnapshotPoint startLinePoint = span.Start.GetContainingLine().Start;

            span = new SnapshotSpan(startLinePoint, span.End);

            SourceText sourceText = this.core.SourceTextCache.Get(this.textBuffer.CurrentSnapshot);

            Range range = new Range(span.Start.Position, span.Length);

            FormattingOptions formattingOptions = this.GetFormattingOptions(this.core.FormattingUserSettings);

            List <TextEditInfo> edits = this.core.FeatureContainer.Formatter.Format(sourceText, range, formattingOptions);

            using (ITextEdit textEdit = this.textBuffer.CreateEdit())
            {
                foreach (TextEditInfo edit in edits)
                {
                    textEdit.Replace(edit.Start, edit.Length, edit.ReplacingWith);
                }

                textEdit.Apply();
            }

            return(true);
        }
Ejemplo n.º 28
0
        private static void UnCommentRegion(SnapshotPoint start, SnapshotPoint end)
        {
            ITextSnapshot snapshot = start.Snapshot;

            using (ITextEdit edit = snapshot.TextBuffer.CreateEdit())
            {
                for (int i = start.GetContainingLine().LineNumber; i <= end.GetContainingLine().LineNumber; i++)
                {
                    ITextSnapshotLine currentLine = snapshot.GetLineFromLineNumber(i);
                    string            lineText    = currentLine.GetText();

                    for (int j = 0; j < lineText.Length - 1; j++)
                    {
                        if (!char.IsWhiteSpace(lineText[j]))
                        {
                            if (lineText[j] == '/' && lineText[j + 1] == '/')
                            {
                                edit.Delete(currentLine.Start.Position + j, 2);
                                break;
                            }
                        }
                    }
                }

                edit.Apply();
            }
        }
Ejemplo n.º 29
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();
            }
        }
Ejemplo n.º 30
0
        public void Edit(Project project)
        {
            string str = Path.Combine(ProjectExtensions.GetFullPath(project), "web.config");

            if (project.DTE.SourceControl.IsItemUnderSCC(str) && !project.DTE.SourceControl.IsItemCheckedOut(str) && !project.DTE.SourceControl.CheckOutItem(str))
            {
                return;
            }
            IEditorInterfaces orOpenDocument = this.VisualStudio.Editor.GetOrOpenDocument(str);

            Marshal.ThrowExceptionForHR(orOpenDocument.VsTextBuffer.Reload(1));
            ITextBuffer textBuffer = orOpenDocument.TextBuffer;

            using (ITextEdit textEdit = textBuffer.CreateEdit())
            {
                string editedText = this.GetEditedText(textEdit.Snapshot.GetText());
                if (editedText != null)
                {
                    textEdit.Replace(new Span(0, textBuffer.CurrentSnapshot.Length), editedText);
                    textEdit.Apply();
                    this.VisualStudio.Editor.FormatDocument(str);
                    Document document = project.DTE.Documents.Item(str);
                    document.Save("");
                }
            }
        }
        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 static ITextSnapshot ApplyEdit(ITextEdit edit)
 {
     using (edit)
         return edit.Apply();
 }