AbstractBlockCommentEditingCommandHandler.cs 2.6 KB
Newer Older
1 2 3 4 5 6 7 8 9
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System;
using Microsoft.CodeAnalysis.Editor.Commands;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Operations;
using Roslyn.Utilities;

10
namespace Microsoft.CodeAnalysis.Editor.Implementation.BlockCommentEditing
11
{
12
    internal abstract class AbstractBlockCommentEditingCommandHandler : ICommandHandler<ReturnKeyCommandArgs>
13 14 15 16
    {
        private readonly ITextUndoHistoryRegistry _undoHistoryRegistry;
        private readonly IEditorOperationsFactoryService _editorOperationsFactoryService;

17
        protected AbstractBlockCommentEditingCommandHandler(
18 19 20 21 22 23 24 25 26 27 28 29 30
            ITextUndoHistoryRegistry undoHistoryRegistry,
            IEditorOperationsFactoryService editorOperationsFactoryService)
        {
            Contract.ThrowIfNull(undoHistoryRegistry);
            Contract.ThrowIfNull(editorOperationsFactoryService);

            _undoHistoryRegistry = undoHistoryRegistry;
            _editorOperationsFactoryService = editorOperationsFactoryService;
        }

        public CommandState GetCommandState(ReturnKeyCommandArgs args, Func<CommandState> nextHandler) => nextHandler();

        public void ExecuteCommand(ReturnKeyCommandArgs args, Action nextHandler)
P
Paul Chen 已提交
31 32 33 34 35 36 37 38 39 40
        {
            if (TryHandleReturnKey(args))
            {
                return;
            }

            nextHandler();
        }

        private bool TryHandleReturnKey(ReturnKeyCommandArgs args)
41 42 43 44 45 46 47
        {
            var subjectBuffer = args.SubjectBuffer;
            var textView = args.TextView;

            var caretPosition = textView.GetCaretPoint(subjectBuffer);
            if (caretPosition == null)
            {
P
Paul Chen 已提交
48
                return false;
49 50 51 52 53
            }

            var exteriorText = GetExteriorTextForNextLine(caretPosition.Value);
            if (exteriorText == null)
            {
P
Paul Chen 已提交
54
                return false;
55 56 57 58 59 60 61 62 63 64
            }

            using (var transaction = _undoHistoryRegistry.GetHistory(args.TextView.TextBuffer).CreateTransaction(EditorFeaturesResources.InsertNewLine))
            {
                var editorOperations = _editorOperationsFactoryService.GetEditorOperations(args.TextView);

                editorOperations.InsertNewLine();
                editorOperations.InsertText(exteriorText);

                transaction.Complete();
P
Paul Chen 已提交
65
                return true;
66 67 68 69 70 71
            }
        }

        protected abstract string GetExteriorTextForNextLine(SnapshotPoint caretPosition);
    }
}