Пример #1
0
        public bool TryCreateSession(ITextView textView, SnapshotPoint openingPoint, char openingBrace, char closingBrace, out IBraceCompletionSession session)
        {
            _threadingContext.ThrowIfNotOnUIThread();
            var textSnapshot = openingPoint.Snapshot;
            var document     = textSnapshot.GetOpenDocumentInCurrentContextWithChanges();

            if (document != null)
            {
                var editorSessionFactory = document.GetLanguageService <IBraceCompletionServiceFactory>();
                if (editorSessionFactory != null)
                {
                    // Brace completion is (currently) not cancellable.
                    var cancellationToken = CancellationToken.None;

                    var editorSession = editorSessionFactory.TryGetServiceAsync(document, openingPoint, openingBrace, cancellationToken).WaitAndGetResult(cancellationToken);
                    if (editorSession != null)
                    {
                        var undoHistory = _undoManager.GetTextBufferUndoManager(textView.TextBuffer).TextBufferUndoHistory;
                        session = new BraceCompletionSession(
                            textView, openingPoint.Snapshot.TextBuffer, openingPoint, openingBrace, closingBrace,
                            undoHistory, _editorOperationsFactoryService,
                            editorSession, _globalOptions, _threadingContext);
                        return(true);
                    }
                }
            }

            session = null;
            return(false);
        }
Пример #2
0
 public ExpandCommand(IWpfTextView view, ICompletionBroker broker, ITextBufferUndoManagerProvider undoProvider, IClassifier classifier)
 {
     _view        = view;
     _broker      = broker;
     _undoManager = undoProvider.GetTextBufferUndoManager(view.TextBuffer);
     _classifier  = classifier;
 }
Пример #3
0
        public bool TryCreateContext(ITextView textView, SnapshotPoint openingPoint, char openingBrace, char closingBrace, out IBraceCompletionContext context)
        {
            this.AssertIsForeground();

            if (IsValidBraceCompletionContext(openingPoint))
            {
                var textSnapshot = openingPoint.Snapshot;
                var document     = textSnapshot.GetOpenDocumentInCurrentContextWithChanges();
                if (document != null)
                {
                    var editorSessionFactory = document.GetLanguageService <IEditorBraceCompletionSessionFactory>();
                    if (editorSessionFactory != null)
                    {
                        // Brace completion is (currently) not cancellable.
                        var cancellationToken = CancellationToken.None;

                        var editorSession = editorSessionFactory.TryCreateSession(document, openingPoint, openingBrace, cancellationToken);
                        if (editorSession != null)
                        {
                            var undoManager = _textBufferUndoManagerProvider.GetTextBufferUndoManager(textView.TextBuffer);
                            context = new BraceCompletionContext(_smartIndentationService, undoManager, editorSession);
                            return(true);
                        }
                    }
                }
            }

            context = null;
            return(false);
        }
Пример #4
0
 public ExpandCommand(IWpfTextView view, ICompletionBroker broker, ITextBufferUndoManagerProvider undoProvider, IClassifier classifier)
 {
     ThreadHelper.ThrowIfNotOnUIThread();
     _view        = view;
     _broker      = broker;
     _undoManager = undoProvider.GetTextBufferUndoManager(view.TextBuffer);
     _classifier  = classifier;
     _dte         = Package.GetGlobalService(typeof(DTE)) as DTE;
 }
Пример #5
0
        /// <summary>
        /// Make sure that on tear down we don't have a current transaction.  Having one indicates
        /// we didn't close it and hence are killing undo in the ITextBuffer
        /// </summary>
        private void CheckForOrphanedUndoHistory(ITextView textView)
        {
            var history = _textBufferUndoManagerProvider.GetTextBufferUndoManager(textView.TextBuffer).TextBufferUndoHistory;

            if (history.CurrentTransaction != null)
            {
                _errorList.Add(new Exception("Failed to close an undo transaction"));
            }
        }
Пример #6
0
 public TextViewUndoManager(IDsWpfTextView textView, ITextViewUndoManagerProvider textViewUndoManagerProvider, ITextBufferUndoManagerProvider textBufferUndoManagerProvider)
 {
     TextView = textView ?? throw new ArgumentNullException(nameof(textView));
     this.textViewUndoManagerProvider   = textViewUndoManagerProvider ?? throw new ArgumentNullException(nameof(textViewUndoManagerProvider));
     this.textBufferUndoManagerProvider = textBufferUndoManagerProvider ?? throw new ArgumentNullException(nameof(textBufferUndoManagerProvider));
     textBufferUndoManager       = textBufferUndoManagerProvider.GetTextBufferUndoManager(TextView.TextBuffer);
     undoRedoCommandTargetFilter = new UndoRedoCommandTargetFilter(this);
     TextView.CommandTarget.AddFilter(undoRedoCommandTargetFilter, CommandTargetFilterOrder.UndoRedo);
     TextView.Closed += TextView_Closed;
 }
Пример #7
0
        private void ApplyChangesToBuffer(ExtractMethodResult extractMethodResult, ITextBuffer subjectBuffer, CancellationToken cancellationToken)
        {
            using var undoTransaction = _undoManager.GetTextBufferUndoManager(subjectBuffer).TextBufferUndoHistory.CreateTransaction("Extract Method");

            // apply extract method code to buffer
            var(document, _) = extractMethodResult.GetFormattedDocumentAsync(cancellationToken).WaitAndGetResult(cancellationToken);
            document.Project.Solution.Workspace.ApplyDocumentChanges(document, cancellationToken);

            // apply changes
            undoTransaction.Complete();
        }
Пример #8
0
        public CompoundUndoAction(ITextView textView, IEditorShell editorShell, bool addRollbackOnCancel = true)
        {
            if (!editorShell.IsUnitTestEnvironment)
            {
                IEditorOperationsFactoryService operationsService = editorShell.GlobalServices.GetService <IEditorOperationsFactoryService>();
                ITextBufferUndoManagerProvider  undoProvider      = editorShell.GlobalServices.GetService <ITextBufferUndoManagerProvider>();

                _editorOperations    = operationsService.GetEditorOperations(textView);
                _undoManager         = undoProvider.GetTextBufferUndoManager(_editorOperations.TextView.TextBuffer);
                _addRollbackOnCancel = addRollbackOnCancel;
            }
        }
Пример #9
0
        public SelectionUndo(ISelectionTracker selectionTracker, ITextBufferUndoManagerProvider undoManagerProvider, string transactionName, bool automaticTracking)
        {
            _selectionTracker = selectionTracker;
            var undoManager = undoManagerProvider.GetTextBufferUndoManager(selectionTracker.TextView.TextBuffer);

            ITextUndoTransaction innerTransaction = undoManager.TextBufferUndoHistory.CreateTransaction(transactionName);

            _transaction = new TextUndoTransactionThatRollsBackProperly(innerTransaction);
            _transaction.AddUndo(new StartSelectionTrackingUndoUnit(selectionTracker));

            _selectionTracker.StartTracking(automaticTracking);
        }
        /// <summary>
        /// Applies an ExtractMethodResult to the editor.
        /// </summary>
        private void ApplyChangesToBuffer(ExtractMethodResult extractMethodResult, ITextBuffer subjectBuffer, CancellationToken cancellationToken)
        {
            using (var undoTransaction = _undoManager.GetTextBufferUndoManager(subjectBuffer).TextBufferUndoHistory.CreateTransaction("Extract Method"))
            {
                // apply extract method code to buffer
                var document = extractMethodResult.Document;
                document.Project.Solution.Workspace.ApplyDocumentChanges(document, cancellationToken);

                // apply changes
                undoTransaction.Complete();
            }
        }
Пример #11
0
        public CompoundUndoAction(ITextView textView, ITextBuffer textBuffer, bool addRollbackOnCancel = true)
        {
            if (!EditorShell.Current.IsUnitTestEnvironment)
            {
                IEditorOperationsFactoryService operationsService = EditorShell.Current.ExportProvider.GetExport <IEditorOperationsFactoryService>().Value;
                ITextBufferUndoManagerProvider  undoProvider      = EditorShell.Current.ExportProvider.GetExport <ITextBufferUndoManagerProvider>().Value;

                _editorOperations    = operationsService.GetEditorOperations(textView);
                _undoManager         = undoProvider.GetTextBufferUndoManager(_editorOperations.TextView.TextBuffer);
                _addRollbackOnCancel = addRollbackOnCancel;
            }
        }
Пример #12
0
 /// <summary>
 /// Default session with a language specific context
 /// </summary>
 public BraceCompletionDefaultSession(ITextView textView, ITextBuffer subjectBuffer,
                                      SnapshotPoint openingPoint, char openingBrace, char closingBrace, ITextBufferUndoManagerProvider undoManager,
                                      IEditorOperationsFactoryService editorOperationsFactoryService, IBraceCompletionContext context)
 {
     _textView         = textView;
     _subjectBuffer    = subjectBuffer;
     _openingBrace     = openingBrace;
     _closingBrace     = closingBrace;
     _closingPoint     = SubjectBuffer.CurrentSnapshot.CreateTrackingPoint(openingPoint.Position, PointTrackingMode.Positive);
     _context          = context;
     _undoManager      = undoManager;
     _undoHistory      = undoManager.GetTextBufferUndoManager(_textView.TextBuffer).TextBufferUndoHistory;
     _editorOperations = editorOperationsFactoryService.GetEditorOperations(_textView);
 }
Пример #13
0
        public async override Task ApplyTextEditsAsync(
            Uri uri,
            ITextSnapshot snapshot,
            IEnumerable <TextEdit> textEdits)
        {
            if (uri is null)
            {
                throw new ArgumentNullException(nameof(uri));
            }

            if (snapshot is null)
            {
                throw new ArgumentNullException(nameof(snapshot));
            }

            if (textEdits is null)
            {
                throw new ArgumentNullException(nameof(textEdits));
            }

            await _joinableTaskFactory.SwitchToMainThreadAsync();

            var undoManager = _undoManagerProvider.GetTextBufferUndoManager(snapshot.TextBuffer);
            var undoHistory = undoManager.TextBufferUndoHistory;

            using var transaction = undoHistory.CreateTransaction("Apply Razor LSP text edits");

            try
            {
                ApplyTextEdits(textEdits, snapshot, snapshot.TextBuffer);

                var cursorPosition = ExtractCursorPlaceholder(snapshot.TextBuffer.CurrentSnapshot, textEdits);
                if (cursorPosition != null)
                {
                    var fullPath = GetLocalFilePath(uri);

                    VsShellUtilities.OpenDocument(_serviceProvider, fullPath, VSConstants.LOGVIEWID.TextView_guid, out _, out _, out var windowFrame);

                    if (windowFrame != null)
                    {
                        var textView = GetActiveVsTextView(windowFrame);
                        MoveCaretToPosition(textView, cursorPosition);
                    }
                }
            }
            finally
            {
                transaction.Complete();
            }
        }
Пример #14
0
		public TextViewUndoManager(IDsWpfTextView textView, ITextViewUndoManagerProvider textViewUndoManagerProvider, ITextBufferUndoManagerProvider textBufferUndoManagerProvider) {
			if (textView == null)
				throw new ArgumentNullException(nameof(textView));
			if (textViewUndoManagerProvider == null)
				throw new ArgumentNullException(nameof(textViewUndoManagerProvider));
			if (textBufferUndoManagerProvider == null)
				throw new ArgumentNullException(nameof(textBufferUndoManagerProvider));
			TextView = textView;
			this.textViewUndoManagerProvider = textViewUndoManagerProvider;
			this.textBufferUndoManagerProvider = textBufferUndoManagerProvider;
			textBufferUndoManager = textBufferUndoManagerProvider.GetTextBufferUndoManager(TextView.TextBuffer);
			undoRedoCommandTargetFilter = new UndoRedoCommandTargetFilter(this);
			TextView.CommandTarget.AddFilter(undoRedoCommandTargetFilter, CommandTargetFilterOrder.UndoRedo);
			TextView.Closed += TextView_Closed;
		}
        private void ApplyChange_OnUIThread(
            Document formattedDocument, ITextBuffer textBuffer, IBackgroundWorkIndicatorContext waitContext)
        {
            _threadingContext.ThrowIfNotOnUIThread();

            var cancellationToken = waitContext.UserCancellationToken;

            using var undoTransaction = _undoManager.GetTextBufferUndoManager(textBuffer).TextBufferUndoHistory.CreateTransaction("Extract Method");

            // We're about to make an edit ourselves.  so disable the cancellation that happens on editing.
            waitContext.CancelOnEdit = false;
            formattedDocument.Project.Solution.Workspace.ApplyDocumentChanges(formattedDocument, cancellationToken);

            // apply changes
            undoTransaction.Complete();
        }
Пример #16
0
            public bool Commit(ITextBufferUndoManagerProvider undoManagerProvider)
            {
                const string transactionName = "Format Document";

                if (!TextBuffer.CheckEditAccess())
                {
                    return(false);
                }

                using (var transaction = undoManagerProvider.GetTextBufferUndoManager(TextBuffer).TextBufferUndoHistory.CreateTransaction(transactionName))
                {
                    ApplyEdits();
                    ValidationUtility.Validate(this.Context, ScriptContext.Parse(TextBuffer.CurrentSnapshot.GetText()));
                    transaction.Complete();
                }
                return(true);
            }
Пример #17
0
        private async Task ApplyChangeAsync(
            ITextBuffer subjectBuffer,
            Document document,
            EncapsulateFieldResult result, CancellationToken cancellationToken)
        {
            var finalSolution = await result.GetSolutionAsync(cancellationToken).ConfigureAwait(false);

            var solution       = document.Project.Solution;
            var workspace      = solution.Workspace;
            var previewService = workspace.Services.GetService <IPreviewDialogService>();

            if (previewService != null)
            {
                await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);

                finalSolution = previewService.PreviewChanges(
                    string.Format(EditorFeaturesResources.Preview_Changes_0, EditorFeaturesResources.Encapsulate_Field),
                    "vs.csharp.refactoring.preview",
                    EditorFeaturesResources.Encapsulate_Field_colon,
                    result.Name,
                    result.Glyph,
                    finalSolution,
                    solution);
            }

            if (finalSolution == null)
            {
                // User clicked cancel.
                return;
            }

            using var undoTransaction = _undoManager.GetTextBufferUndoManager(subjectBuffer).TextBufferUndoHistory.CreateTransaction(EditorFeaturesResources.Encapsulate_Field);

            if (workspace.TryApplyChanges(finalSolution))
            {
                undoTransaction.Complete();
            }
            else
            {
                undoTransaction.Cancel();
            }
        }
Пример #18
0
        public bool ExecuteCommand(PasteCommandArgs args, CommandExecutionContext executionContext)
        {
            if (_site.GetPythonToolsService().FormattingOptions.PasteRemovesReplPrompts)
            {
                var beforePaste = args.TextView.TextSnapshot;
                if (_editOperationsFactory.GetEditorOperations(args.TextView).Paste())
                {
                    var afterPaste = args.TextView.TextSnapshot;
                    var um         = _undoManagerFactory.GetTextBufferUndoManager(afterPaste.TextBuffer);
                    using (var undo = um.TextBufferUndoHistory.CreateTransaction(Strings.RemoveReplPrompts)) {
                        if (ReplPromptHelpers.RemovePastedPrompts(beforePaste, afterPaste))
                        {
                            undo.Complete();
                        }
                    }
                    return(true);
                }
            }

            return(false);
        }
        private bool Execute(EncapsulateFieldCommandArgs args, IWaitContext waitContext)
        {
            var text = args.TextView.TextBuffer.CurrentSnapshot.AsText();
            var cancellationToken = waitContext.CancellationToken;

            if (!Workspace.TryGetWorkspace(text.Container, out var workspace))
            {
                return(false);
            }

            var documentId = workspace.GetDocumentIdInCurrentContext(text.Container);

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

            var document = workspace.CurrentSolution.GetDocument(documentId);

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

            var spans = args.TextView.Selection.GetSnapshotSpansOnBuffer(args.SubjectBuffer);

            var service = document.GetLanguageService <AbstractEncapsulateFieldService>();

            var result = service.EncapsulateFieldAsync(document, spans.First().Span.ToTextSpan(), true, cancellationToken).WaitAndGetResult(cancellationToken);

            if (result == null)
            {
                var notificationService = workspace.Services.GetService <INotificationService>();
                notificationService.SendNotification(EditorFeaturesResources.Please_select_the_definition_of_the_field_to_encapsulate, severity: NotificationSeverity.Error);
                return(false);
            }

            waitContext.AllowCancel = false;

            var finalSolution = result.GetSolutionAsync(cancellationToken).WaitAndGetResult(cancellationToken);

            var previewService = workspace.Services.GetService <IPreviewDialogService>();

            if (previewService != null)
            {
                finalSolution = previewService.PreviewChanges(
                    string.Format(EditorFeaturesResources.Preview_Changes_0, EditorFeaturesResources.Encapsulate_Field),
                    "vs.csharp.refactoring.preview",
                    EditorFeaturesResources.Encapsulate_Field_colon,
                    result.GetNameAsync(cancellationToken).WaitAndGetResult(cancellationToken),
                    result.GetGlyphAsync(cancellationToken).WaitAndGetResult(cancellationToken),
                    finalSolution,
                    document.Project.Solution);
            }

            if (finalSolution == null)
            {
                // User clicked cancel.
                return(true);
            }

            using (var undoTransaction = _undoManager.GetTextBufferUndoManager(args.SubjectBuffer).TextBufferUndoHistory.CreateTransaction(EditorFeaturesResources.Encapsulate_Field))
            {
                if (!workspace.TryApplyChanges(finalSolution))
                {
                    undoTransaction.Cancel();
                    return(false);
                }

                undoTransaction.Complete();
            }

            return(true);
        }
Пример #20
0
 private ITextUndoHistory GetUndoHistory(ITextView textView)
 {
     return(_undoManager.GetTextBufferUndoManager(textView.TextBuffer).TextBufferUndoHistory);
 }
        public async override Task ApplyTextEditsAsync(
            Uri uri,
            ITextSnapshot snapshot,
            IEnumerable <TextEdit> textEdits)
        {
            if (uri is null)
            {
                throw new ArgumentNullException(nameof(uri));
            }

            if (snapshot is null)
            {
                throw new ArgumentNullException(nameof(snapshot));
            }

            if (textEdits is null)
            {
                throw new ArgumentNullException(nameof(textEdits));
            }

            await _joinableTaskFactory.SwitchToMainThreadAsync();

            var undoManager = _undoManagerProvider.GetTextBufferUndoManager(snapshot.TextBuffer);
            var undoHistory = undoManager.TextBufferUndoHistory;

            using var transaction = undoHistory.CreateTransaction("Apply Razor LSP text edits");

            try
            {
                ApplyTextEdits(textEdits, snapshot, snapshot.TextBuffer);

                var cursorPosition = ExtractCursorPlaceholder(snapshot.TextBuffer.CurrentSnapshot, textEdits);
                if (cursorPosition != null)
                {
                    // If we get here it means we are in the host client. Move the cursor.

                    var fullPath = GetLocalFilePath(uri);

                    VsShellUtilities.OpenDocument(_serviceProvider, fullPath, VSConstants.LOGVIEWID.TextView_guid, out _, out _, out var windowFrame);

                    if (windowFrame != null)
                    {
                        var vsTextView = GetActiveVsTextView(windowFrame);

                        // Since we are moving the cursor we should dismiss any existing completion sessions as that is no longer valid.
                        var textView = _adaptersFactoryService.GetWpfTextView(vsTextView);
                        var session  = _completionBroker.GetSession(textView);
                        if (session != null && !session.IsDismissed)
                        {
                            session.Dismiss();
                        }

                        MoveCaretToPosition(vsTextView, cursorPosition);
                    }
                }
            }
            finally
            {
                transaction.Complete();
            }
        }
Пример #22
0
        private int ExecWorker(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut)
        {
            // preprocessing
            if (pguidCmdGroup == VSConstants.GUID_VSStandardCommandSet97)
            {
                switch ((VSConstants.VSStd97CmdID)nCmdID)
                {
                case VSConstants.VSStd97CmdID.Paste:
                    if (!_pyService.AdvancedOptions.PasteRemovesReplPrompts)
                    {
                        // Not stripping prompts, so don't use our logic
                        break;
                    }
                    var beforePaste = _textView.TextSnapshot;
                    if (_editorOps.Paste())
                    {
                        var afterPaste = _textView.TextSnapshot;
                        var um         = _undoManagerProvider.GetTextBufferUndoManager(afterPaste.TextBuffer);
                        using (var undo = um.TextBufferUndoHistory.CreateTransaction(Strings.RemoveReplPrompts)) {
                            if (ReplPromptHelpers.RemovePastedPrompts(beforePaste, afterPaste))
                            {
                                undo.Complete();
                            }
                        }
                        return(VSConstants.S_OK);
                    }
                    break;

                case VSConstants.VSStd97CmdID.GotoDefn: GotoDefinition(); return(VSConstants.S_OK);

                case VSConstants.VSStd97CmdID.FindReferences: FindAllReferences(); return(VSConstants.S_OK);
                }
            }
            else if (pguidCmdGroup == CommonConstants.Std2KCmdGroupGuid)
            {
                SnapshotPoint?pyPoint;
                switch ((VSConstants.VSStd2KCmdID)nCmdID)
                {
                case VSConstants.VSStd2KCmdID.RETURN:
                    pyPoint = _textView.GetPythonCaret();
                    if (pyPoint != null)
                    {
                        // https://github.com/Microsoft/PTVS/issues/241
                        // If the current line is a full line comment and we
                        // are splitting the text, automatically insert the
                        // comment marker on the new line.
                        var line     = pyPoint.Value.GetContainingLine();
                        var lineText = pyPoint.Value.Snapshot.GetText(line.Start, pyPoint.Value - line.Start);
                        int comment  = lineText.IndexOf('#');
                        if (comment >= 0 &&
                            pyPoint.Value < line.End &&
                            line.Start + comment < pyPoint.Value &&
                            string.IsNullOrWhiteSpace(lineText.Remove(comment))
                            )
                        {
                            int extra = lineText.Skip(comment + 1).TakeWhile(char.IsWhiteSpace).Count() + 1;
                            using (var edit = line.Snapshot.TextBuffer.CreateEdit()) {
                                edit.Insert(
                                    pyPoint.Value.Position,
                                    _textView.Options.GetNewLineCharacter() + lineText.Substring(0, comment + extra)
                                    );
                                edit.Apply();
                            }

                            return(VSConstants.S_OK);
                        }
                    }
                    break;

                case VSConstants.VSStd2KCmdID.FORMATDOCUMENT:
                    pyPoint = _textView.GetPythonCaret();
                    if (pyPoint != null)
                    {
                        FormatCode(new SnapshotSpan(pyPoint.Value.Snapshot, 0, pyPoint.Value.Snapshot.Length), false);
                    }
                    return(VSConstants.S_OK);

                case VSConstants.VSStd2KCmdID.FORMATSELECTION:
                    foreach (var span in _textView.BufferGraph.MapDownToFirstMatch(
                                 _textView.Selection.StreamSelectionSpan.SnapshotSpan,
                                 SpanTrackingMode.EdgeInclusive,
                                 EditorExtensions.IsPythonContent
                                 ))
                    {
                        FormatCode(span, true);
                    }
                    return(VSConstants.S_OK);

                case VSConstants.VSStd2KCmdID.SHOWMEMBERLIST:
                case VSConstants.VSStd2KCmdID.COMPLETEWORD:
                    var controller = _textView.Properties.GetProperty <IntellisenseController>(typeof(IntellisenseController));
                    if (controller != null)
                    {
                        IntellisenseController.ForceCompletions = true;
                        try {
                            controller.TriggerCompletionSession(
                                (VSConstants.VSStd2KCmdID)nCmdID == VSConstants.VSStd2KCmdID.COMPLETEWORD,
                                true
                                );
                        } finally {
                            IntellisenseController.ForceCompletions = false;
                        }
                        return(VSConstants.S_OK);
                    }
                    break;

                case VSConstants.VSStd2KCmdID.QUICKINFO:
                    controller = _textView.Properties.GetProperty <IntellisenseController>(typeof(IntellisenseController));
                    if (controller != null)
                    {
                        controller.TriggerQuickInfo();
                        return(VSConstants.S_OK);
                    }
                    break;

                case VSConstants.VSStd2KCmdID.PARAMINFO:
                    controller = _textView.Properties.GetProperty <IntellisenseController>(typeof(IntellisenseController));
                    if (controller != null)
                    {
                        controller.TriggerSignatureHelp();
                        return(VSConstants.S_OK);
                    }
                    break;

                case VSConstants.VSStd2KCmdID.OUTLN_STOP_HIDING_ALL:
                    _textView.GetOutliningTagger()?.Disable();
                    // let VS get the event as well
                    break;

                case VSConstants.VSStd2KCmdID.OUTLN_START_AUTOHIDING:
                    _textView.GetOutliningTagger()?.Enable();
                    // let VS get the event as well
                    break;

                case VSConstants.VSStd2KCmdID.COMMENT_BLOCK:
                case VSConstants.VSStd2KCmdID.COMMENTBLOCK:
                    if (_textView.CommentOrUncommentBlock(comment: true))
                    {
                        return(VSConstants.S_OK);
                    }
                    break;

                case VSConstants.VSStd2KCmdID.UNCOMMENT_BLOCK:
                case VSConstants.VSStd2KCmdID.UNCOMMENTBLOCK:
                    if (_textView.CommentOrUncommentBlock(comment: false))
                    {
                        return(VSConstants.S_OK);
                    }
                    break;

                case VSConstants.VSStd2KCmdID.EXTRACTMETHOD:
                    ExtractMethod();
                    return(VSConstants.S_OK);

                case VSConstants.VSStd2KCmdID.RENAME:
                    RefactorRename();
                    return(VSConstants.S_OK);
                }
            }
            else if (pguidCmdGroup == GuidList.guidPythonToolsCmdSet)
            {
                switch (nCmdID)
                {
                case PkgCmdIDList.cmdidRefactorRenameIntegratedShell:
                    RefactorRename();
                    return(VSConstants.S_OK);

                case PkgCmdIDList.cmdidExtractMethodIntegratedShell:
                    ExtractMethod();
                    return(VSConstants.S_OK);

                case CommonConstants.StartDebuggingCmdId:
                case CommonConstants.StartWithoutDebuggingCmdId:
                    PythonToolsPackage.LaunchFile(_serviceProvider, _textView.GetFilePath(), nCmdID == CommonConstants.StartDebuggingCmdId, true);
                    return(VSConstants.S_OK);
                }
            }

            return(_next.Exec(pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut));
        }
        private bool Execute(EncapsulateFieldCommandArgs args, IUIThreadOperationScope waitScope)
        {
            using var token = _listener.BeginAsyncOperation("EncapsulateField");

            var cancellationToken = waitScope.Context.UserCancellationToken;
            var document          =
                args.SubjectBuffer.CurrentSnapshot.GetFullyLoadedOpenDocumentInCurrentContextWithChanges(
                    waitScope.Context,
                    _threadingContext
                    );

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

            var spans = args.TextView.Selection.GetSnapshotSpansOnBuffer(args.SubjectBuffer);

            var service = document.GetLanguageService <AbstractEncapsulateFieldService>();

            var result = service
                         .EncapsulateFieldsInSpanAsync(
                document,
                spans.First().Span.ToTextSpan(),
                true,
                cancellationToken
                )
                         .WaitAndGetResult(cancellationToken);

            // We are about to show a modal UI dialog so we should take over the command execution
            // wait context. That means the command system won't attempt to show its own wait dialog
            // and also will take it into consideration when measuring command handling duration.
            waitScope.Context.TakeOwnership();

            var workspace = document.Project.Solution.Workspace;

            if (result == null)
            {
                var notificationService = workspace.Services.GetService <INotificationService>();
                notificationService.SendNotification(
                    EditorFeaturesResources.Please_select_the_definition_of_the_field_to_encapsulate,
                    severity: NotificationSeverity.Error
                    );
                return(false);
            }

            waitScope.AllowCancellation = false;
            cancellationToken           = waitScope.Context.UserCancellationToken;

            var finalSolution = result
                                .GetSolutionAsync(cancellationToken)
                                .WaitAndGetResult(cancellationToken);

            var previewService = workspace.Services.GetService <IPreviewDialogService>();

            if (previewService != null)
            {
                finalSolution = previewService.PreviewChanges(
                    string.Format(
                        EditorFeaturesResources.Preview_Changes_0,
                        EditorFeaturesResources.Encapsulate_Field
                        ),
                    "vs.csharp.refactoring.preview",
                    EditorFeaturesResources.Encapsulate_Field_colon,
                    result.Name,
                    result.Glyph,
                    finalSolution,
                    document.Project.Solution
                    );
            }

            if (finalSolution == null)
            {
                // User clicked cancel.
                return(true);
            }

            using (
                var undoTransaction = _undoManager
                                      .GetTextBufferUndoManager(args.SubjectBuffer)
                                      .TextBufferUndoHistory.CreateTransaction(
                    EditorFeaturesResources.Encapsulate_Field
                    )
                )
            {
                if (!workspace.TryApplyChanges(finalSolution))
                {
                    undoTransaction.Cancel();
                    return(false);
                }

                undoTransaction.Complete();
            }

            return(true);
        }
Пример #24
0
 private ITextUndoHistory GetUndoHistory(ITextView textView)
 => _undoManager.GetTextBufferUndoManager(textView.TextBuffer).TextBufferUndoHistory;