Welcome to mirror list, hosted at ThFree Co, Russian Federation.

CompletionCommandHandlers.cs « AsyncCompletion « Language « Impl « Language « src - github.com/microsoft/vs-editor-api.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: e0599f1e1d3951c6de91dcaa56f8560ee9a852df (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
using System;
using System.ComponentModel.Composition;
using Microsoft.VisualStudio.Commanding;
using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Editor.Commanding.Commands;
using Microsoft.VisualStudio.Text.Operations;
using Microsoft.VisualStudio.Text.Utilities;
using Microsoft.VisualStudio.Utilities;
using CommonImplementation = Microsoft.VisualStudio.Language.Intellisense.Implementation;

namespace Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Implementation
{
    /// <summary>
    /// Reacts to the down arrow command and attempts to scroll the completion list.
    /// </summary>
    [Name(PredefinedCompletionNames.CompletionCommandHandler)]
    [ContentType("text")]
    [TextViewRole(PredefinedTextViewRoles.Interactive)]
    [Export(typeof(ICommandHandler))]
    internal sealed class CompletionCommandHandler :
        ICommandHandler<DownKeyCommandArgs>,
        ICommandHandler<PageDownKeyCommandArgs>,
        ICommandHandler<PageUpKeyCommandArgs>,
        ICommandHandler<UpKeyCommandArgs>,
        IChainedCommandHandler<BackspaceKeyCommandArgs>,
        IDynamicCommandHandler<BackspaceKeyCommandArgs>,
        ICommandHandler<EscapeKeyCommandArgs>,
        IDynamicCommandHandler<EscapeKeyCommandArgs>,
        ICommandHandler<InvokeCompletionListCommandArgs>,
        ICommandHandler<CommitUniqueCompletionListItemCommandArgs>,
        ICommandHandler<InsertSnippetCommandArgs>,
        ICommandHandler<SurroundWithCommandArgs>,
        ICommandHandler<ToggleCompletionModeCommandArgs>,
        IChainedCommandHandler<DeleteKeyCommandArgs>,
        IDynamicCommandHandler<DeleteKeyCommandArgs>,
        ICommandHandler<WordDeleteToEndCommandArgs>,
        ICommandHandler<WordDeleteToStartCommandArgs>,
        ICommandHandler<SaveCommandArgs>,
        ICommandHandler<SelectAllCommandArgs>,
        ICommandHandler<RenameCommandArgs>,
        ICommandHandler<UndoCommandArgs>,
        ICommandHandler<RedoCommandArgs>,
        IChainedCommandHandler<ReturnKeyCommandArgs>,
        IDynamicCommandHandler<ReturnKeyCommandArgs>,
        IChainedCommandHandler<TabKeyCommandArgs>,
        IDynamicCommandHandler<TabKeyCommandArgs>,
        IChainedCommandHandler<TypeCharCommandArgs>,
        IDynamicCommandHandler<TypeCharCommandArgs>
    {
        [Import]
        private IAsyncCompletionBroker Broker;

        [Import]
        private ITextUndoHistoryRegistry UndoHistoryRegistry;

        [Import]
        private IEditorOperationsFactoryService EditorOperationsFactoryService;

        [Import]
        private CompletionAvailabilityUtility CompletionAvailability;

        string INamed.DisplayName => CommonImplementation.Strings.CompletionCommandHandlerName;

        /// <summary>
        /// Helper method that returns command state for commands
        /// that are always available - unless the completion feature is available.
        /// </summary>
        private CommandState GetCommandStateIfCompletionIsAvailable(IContentType contentType, ITextView textView)
        {
            return CompletionAvailability.IsAvailable(contentType, textView)
                ? CommandState.Available
                : CommandState.Unspecified;
        }

        /// <summary>
        /// Helper method that returns command state
        /// for commands that are available IF AND ONLY IF completion is active,
        /// even if the commands would be otherwise unavailable.
        /// </summary>
        /// <remarks>
        /// For commands whose availability is not influenced by completion, use <see cref="CommandState.Unspecified"/>
        /// </remarks>
        private CommandState GetCommandStateIfCompletionIsActive(ITextView textView)
        {
            return Broker.IsCompletionActive(textView)
                ? CommandState.Available
                : CommandState.Unspecified;
        }

        /// <summary>
        /// Helper method that returns command state for commands that are available when completion is
        /// either currently active, or available.
        /// This is used by commands that may trigger completion session on a specified buffer, or interact with an active completion session on another buffer
        /// </summary>
        private CommandState GetCommandStateIfCompletionIsActiveOrAvailable(IContentType contentType, ITextView textView)
        {
            return Broker.IsCompletionActive(textView) || CompletionAvailability.IsAvailable(contentType, textView)
                ? CommandState.Available
                : CommandState.Unspecified;
        }

        /// <summary>
        /// Helper method that returns command state for the suggestion mode toggle button.
        /// This command state controls not only whether the toggle button is enabled, but also if it's toggled.
        /// </summary>
        private CommandState GetCommandStateForSuggestionModeToggle(IContentType contentType, ITextView textView)
        {
            var isAvailable = CompletionAvailability.IsAvailable(contentType, textView);
            var isChecked = CompletionUtilities.IsDebuggerTextView(textView)
                ? CompletionUtilities.GetSuggestionModeOption(textView)
                : CompletionUtilities.GetSuggestionModeInDebuggerCompletionOption(textView);
            return new CommandState(isAvailable, isChecked);
        }

        /// <summary>
        /// Realizes the virtual space and updates session's applicable to span
        /// </summary>
        private void RealizeVirtualSpaceUpdateApplicableToSpan(IAsyncCompletionSessionOperations session, ITextView textView)
        {
            if (session == null // We may only act if we have internal reference to the session
                || !textView.Caret.InVirtualSpace // We only act if caret is in virtual space
                || !session.ApplicableToSpan.GetSpan(textView.TextSnapshot).IsEmpty) // We only act if the applicable to span is of zero length (at the beginning of the line)
            {
                return;
            }

            // Realize the virtual space before triggering the session by inserting nothing through the editor opertaions.
            IEditorOperations editorOperations = EditorOperationsFactoryService.GetEditorOperations(textView);
            editorOperations?.InsertText("");

            // ApplicableToSpan just grew to include the realized white space.
            // We know that ApplicableToSpan was zero length, so let's recreate a zero length span at the caret location
            session.ApplicableToSpan = textView.TextSnapshot.CreateTrackingSpan(
                start: textView.Caret.Position.BufferPosition.Position,
                length: 0,
                trackingMode: SpanTrackingMode.EdgePositive);
        }

        // ----- Command handlers:

        CommandState IChainedCommandHandler<BackspaceKeyCommandArgs>.GetCommandState(BackspaceKeyCommandArgs args, Func<CommandState> nextCommandHandler)
           => CommandState.Unspecified;

        bool IDynamicCommandHandler<BackspaceKeyCommandArgs>.CanExecuteCommand(BackspaceKeyCommandArgs args)
            => Broker.IsCompletionActive(args.TextView);

        void IChainedCommandHandler<BackspaceKeyCommandArgs>.ExecuteCommand(BackspaceKeyCommandArgs args, Action nextCommandHandler, CommandExecutionContext executionContext)
        {
            // Execute other commands in the chain to see the change in the buffer.
            nextCommandHandler();

            var session = Broker.GetSession(args.TextView);
            if (session != null)
            {
                var trigger = new InitialTrigger(InitialTriggerReason.Deletion);
                var location = args.TextView.Caret.Position.BufferPosition;
                session.OpenOrUpdate(trigger, location, executionContext.OperationContext.UserCancellationToken);
            }
        }

        CommandState ICommandHandler<EscapeKeyCommandArgs>.GetCommandState(EscapeKeyCommandArgs args)
            => GetCommandStateIfCompletionIsActive(args.TextView);

        bool IDynamicCommandHandler<EscapeKeyCommandArgs>.CanExecuteCommand(EscapeKeyCommandArgs args)
            => Broker.IsCompletionActive(args.TextView);

        bool ICommandHandler<EscapeKeyCommandArgs>.ExecuteCommand(EscapeKeyCommandArgs args, CommandExecutionContext executionContext)
        {
            var session = Broker.GetSession(args.TextView);
            if (session != null)
            {
                session.Dismiss();
                return true;
            }
            return false;
        }

        CommandState ICommandHandler<InvokeCompletionListCommandArgs>.GetCommandState(InvokeCompletionListCommandArgs args)
            => GetCommandStateIfCompletionIsAvailable(args.SubjectBuffer.ContentType, args.TextView);

        bool ICommandHandler<InvokeCompletionListCommandArgs>.ExecuteCommand(InvokeCompletionListCommandArgs args, CommandExecutionContext executionContext)
        {
            if (!GetCommandStateIfCompletionIsAvailable(args.SubjectBuffer.ContentType, args.TextView).IsAvailable)
                return false;

            var trigger = new InitialTrigger(InitialTriggerReason.Invoke);
            var location = args.TextView.Caret.Position.BufferPosition;
            var session = Broker.TriggerCompletion(args.TextView, location, default, executionContext.OperationContext.UserCancellationToken);
            if (session is IAsyncCompletionSessionOperations sessionInternal)
            {
                RealizeVirtualSpaceUpdateApplicableToSpan(sessionInternal, args.TextView);
                location = args.TextView.Caret.Position.BufferPosition; // Buffer may have changed. Update the location.
                sessionInternal.OpenOrUpdate(trigger, location, executionContext.OperationContext.UserCancellationToken);
                return true;
            }
            return false;
        }

        CommandState ICommandHandler<CommitUniqueCompletionListItemCommandArgs>.GetCommandState(CommitUniqueCompletionListItemCommandArgs args)
            => GetCommandStateIfCompletionIsAvailable(args.SubjectBuffer.ContentType, args.TextView);

        bool ICommandHandler<CommitUniqueCompletionListItemCommandArgs>.ExecuteCommand(CommitUniqueCompletionListItemCommandArgs args, CommandExecutionContext executionContext)
        {
            if (!GetCommandStateIfCompletionIsAvailable(args.SubjectBuffer.ContentType, args.TextView).IsAvailable)
                return false;

            var trigger = new InitialTrigger(InitialTriggerReason.InvokeAndCommitIfUnique);
            var location = args.TextView.Caret.Position.BufferPosition;
            var session = Broker.TriggerCompletion(args.TextView, location, default, executionContext.OperationContext.UserCancellationToken);
            if (session is IAsyncCompletionSessionOperations sessionInternal)
            {
                RealizeVirtualSpaceUpdateApplicableToSpan(sessionInternal, args.TextView);
                location = args.TextView.Caret.Position.BufferPosition; // Buffer may have changed. Update the location.
                sessionInternal.InvokeAndCommitIfUnique(trigger, location, executionContext.OperationContext.UserCancellationToken);
                return true;
            }
            return false;
        }

        CommandState ICommandHandler<InsertSnippetCommandArgs>.GetCommandState(InsertSnippetCommandArgs args)
            => CommandState.Unspecified;

        bool ICommandHandler<InsertSnippetCommandArgs>.ExecuteCommand(InsertSnippetCommandArgs args, CommandExecutionContext executionContext)
        {
            Broker.GetSession(args.TextView)?.Dismiss();
            return false;
        }

        CommandState ICommandHandler<SurroundWithCommandArgs>.GetCommandState(SurroundWithCommandArgs args)
            => CommandState.Unspecified;

        bool ICommandHandler<SurroundWithCommandArgs>.ExecuteCommand(SurroundWithCommandArgs args, CommandExecutionContext executionContext)
        {
            Broker.GetSession(args.TextView)?.Dismiss();
            return false;
        }

        CommandState ICommandHandler<ToggleCompletionModeCommandArgs>.GetCommandState(ToggleCompletionModeCommandArgs args)
            => GetCommandStateForSuggestionModeToggle(args.SubjectBuffer.ContentType, args.TextView);

        bool ICommandHandler<ToggleCompletionModeCommandArgs>.ExecuteCommand(ToggleCompletionModeCommandArgs args, CommandExecutionContext executionContext)
        {
            var toggledValue = !CompletionUtilities.GetSuggestionModeOption(args.TextView);
            CompletionUtilities.SetSuggestionModeOption(args.TextView, toggledValue);

            if (Broker.GetSession(args.TextView) is IAsyncCompletionSessionOperations sessionInternal) // we are accessing an internal method
            {
                sessionInternal.SetSuggestionMode(toggledValue);
                return true;
            }
            return false;
        }

        CommandState IChainedCommandHandler<DeleteKeyCommandArgs>.GetCommandState(DeleteKeyCommandArgs args, Func<CommandState> nextCommandHandler)
            => CommandState.Unspecified;

        bool IDynamicCommandHandler<DeleteKeyCommandArgs>.CanExecuteCommand(DeleteKeyCommandArgs args)
            => Broker.IsCompletionActive(args.TextView);

        void IChainedCommandHandler<DeleteKeyCommandArgs>.ExecuteCommand(DeleteKeyCommandArgs args, Action nextCommandHandler, CommandExecutionContext executionContext)
        {
            // Execute other commands in the chain to see the change in the buffer.
            nextCommandHandler();

            var session = Broker.GetSession(args.TextView);
            if (session != null)
            {
                var trigger = new InitialTrigger(InitialTriggerReason.Deletion);
                var location = args.TextView.Caret.Position.BufferPosition;
                session.OpenOrUpdate(trigger, location, executionContext.OperationContext.UserCancellationToken);
            }
        }

        CommandState ICommandHandler<WordDeleteToEndCommandArgs>.GetCommandState(WordDeleteToEndCommandArgs args)
            => CommandState.Unspecified;

        bool ICommandHandler<WordDeleteToEndCommandArgs>.ExecuteCommand(WordDeleteToEndCommandArgs args, CommandExecutionContext executionContext)
        {
            Broker.GetSession(args.TextView)?.Dismiss();
            return false;
        }

        CommandState ICommandHandler<WordDeleteToStartCommandArgs>.GetCommandState(WordDeleteToStartCommandArgs args)
            => CommandState.Unspecified;

        bool ICommandHandler<WordDeleteToStartCommandArgs>.ExecuteCommand(WordDeleteToStartCommandArgs args, CommandExecutionContext executionContext)
        {
            Broker.GetSession(args.TextView)?.Dismiss();
            return false;
        }

        CommandState ICommandHandler<SaveCommandArgs>.GetCommandState(SaveCommandArgs args)
            => CommandState.Unspecified;

        bool ICommandHandler<SaveCommandArgs>.ExecuteCommand(SaveCommandArgs args, CommandExecutionContext executionContext)
        {
            Broker.GetSession(args.TextView)?.Dismiss();
            return false;
        }

        CommandState ICommandHandler<SelectAllCommandArgs>.GetCommandState(SelectAllCommandArgs args)
            => CommandState.Unspecified;

        bool ICommandHandler<SelectAllCommandArgs>.ExecuteCommand(SelectAllCommandArgs args, CommandExecutionContext executionContext)
        {
            Broker.GetSession(args.TextView)?.Dismiss();
            return false;
        }

        CommandState ICommandHandler<RenameCommandArgs>.GetCommandState(RenameCommandArgs args)
            => CommandState.Unspecified;

        bool ICommandHandler<RenameCommandArgs>.ExecuteCommand(RenameCommandArgs args, CommandExecutionContext executionContext)
        {
            Broker.GetSession(args.TextView)?.Dismiss();
            return false;
        }

        CommandState ICommandHandler<UndoCommandArgs>.GetCommandState(UndoCommandArgs args)
            => CommandState.Unspecified;

        bool ICommandHandler<UndoCommandArgs>.ExecuteCommand(UndoCommandArgs args, CommandExecutionContext executionContext)
        {
            Broker.GetSession(args.TextView)?.Dismiss();
            return false;
        }

        CommandState ICommandHandler<RedoCommandArgs>.GetCommandState(RedoCommandArgs args)
            => CommandState.Unspecified;

        bool ICommandHandler<RedoCommandArgs>.ExecuteCommand(RedoCommandArgs args, CommandExecutionContext executionContext)
        {
            Broker.GetSession(args.TextView)?.Dismiss();
            return false;
        }

        CommandState IChainedCommandHandler<ReturnKeyCommandArgs>.GetCommandState(ReturnKeyCommandArgs args, Func<CommandState> nextCommandHandler)
            => GetCommandStateIfCompletionIsActiveOrAvailable(args.SubjectBuffer.ContentType, args.TextView);

        bool IDynamicCommandHandler<ReturnKeyCommandArgs>.CanExecuteCommand(ReturnKeyCommandArgs args)
            => Broker.IsCompletionActive(args.TextView) || Broker.IsCompletionSupported(args.SubjectBuffer.ContentType);

        void IChainedCommandHandler<ReturnKeyCommandArgs>.ExecuteCommand(ReturnKeyCommandArgs args, Action nextCommandHandler, CommandExecutionContext executionContext)
        {
            if (!GetCommandStateIfCompletionIsAvailable(args.SubjectBuffer.ContentType, args.TextView).IsAvailable)
            {
                // In IChainedCommandHandler, we have to explicitly call the next command handler
                nextCommandHandler();
                return;
            }
            char typedChar = '\n';

            var session = Broker.GetSession(args.TextView);
            if (session != null)
            {
                var commitBehavior = session.Commit(typedChar, executionContext.OperationContext.UserCancellationToken);
                session.Dismiss();

                // Mark this command as handled (return true),
                // unless extender set the RaiseFurtherCommandHandlers flag - with exception of the debugger text view
                if ((commitBehavior & CommitBehavior.RaiseFurtherReturnKeyAndTabKeyCommandHandlers) == 0
                    || CompletionUtilities.IsDebuggerTextView(args.TextView))
                    return;
            }

            nextCommandHandler();

            // Buffer has changed. Update it for when we try to trigger new session.
            var location = args.TextView.Caret.Position.BufferPosition;

            var trigger = new InitialTrigger(InitialTriggerReason.Insertion, typedChar);
            var newSession = Broker.TriggerCompletion(args.TextView, location, typedChar, executionContext.OperationContext.UserCancellationToken);
            if (newSession is IAsyncCompletionSessionOperations sessionInternal)
            {
                RealizeVirtualSpaceUpdateApplicableToSpan(sessionInternal, args.TextView);
                location = args.TextView.Caret.Position.BufferPosition; // Buffer may have changed. Update the location.
                sessionInternal.OpenOrUpdate(trigger, location, executionContext.OperationContext.UserCancellationToken);
            }
        }

        CommandState IChainedCommandHandler<TabKeyCommandArgs>.GetCommandState(TabKeyCommandArgs args, Func<CommandState> nextCommandHandler)
            => GetCommandStateIfCompletionIsActiveOrAvailable(args.SubjectBuffer.ContentType, args.TextView);

        bool IDynamicCommandHandler<TabKeyCommandArgs>.CanExecuteCommand(TabKeyCommandArgs args)
            => Broker.IsCompletionActive(args.TextView) || Broker.IsCompletionSupported(args.SubjectBuffer.ContentType);

        void IChainedCommandHandler<TabKeyCommandArgs>.ExecuteCommand(TabKeyCommandArgs args, Action nextCommandHandler, CommandExecutionContext executionContext)
        {
            if (!GetCommandStateIfCompletionIsAvailable(args.SubjectBuffer.ContentType, args.TextView).IsAvailable)
            {
                // In IChainedCommandHandler, we have to explicitly call the next command handler
                nextCommandHandler();
                return;
            }
            char typedChar = '\t';

            var session = Broker.GetSession(args.TextView);
            if (session != null)
            {
                var commitBehavior = session.Commit(typedChar, executionContext.OperationContext.UserCancellationToken);
                session.Dismiss();

                // Mark this command as handled (return true),
                // unless extender set the RaiseFurtherCommandHandlers flag - with exception of the debugger text view
                if ((commitBehavior & CommitBehavior.RaiseFurtherReturnKeyAndTabKeyCommandHandlers) == 0
                    || CompletionUtilities.IsDebuggerTextView(args.TextView))
                    return;
            }

            nextCommandHandler();

            // Buffer has changed. Update it for when we try to trigger new session.
            var location = args.TextView.Caret.Position.BufferPosition;

            var trigger = new InitialTrigger(InitialTriggerReason.Insertion, typedChar);
            var newSession = Broker.TriggerCompletion(args.TextView, location, typedChar, executionContext.OperationContext.UserCancellationToken);
            newSession?.OpenOrUpdate(trigger, location, executionContext.OperationContext.UserCancellationToken);
        }

        CommandState IChainedCommandHandler<TypeCharCommandArgs>.GetCommandState(TypeCharCommandArgs args, Func<CommandState> nextCommandHandler)
            => GetCommandStateIfCompletionIsAvailable(args.SubjectBuffer.ContentType, args.TextView);

        bool IDynamicCommandHandler<TypeCharCommandArgs>.CanExecuteCommand(TypeCharCommandArgs args)
            => CompletionAvailability.IsAvailable(args.SubjectBuffer.ContentType, args.TextView);

        void IChainedCommandHandler<TypeCharCommandArgs>.ExecuteCommand(TypeCharCommandArgs args, Action nextCommandHandler, CommandExecutionContext executionContext)
        {
            if (!GetCommandStateIfCompletionIsAvailable(args.SubjectBuffer.ContentType, args.TextView).IsAvailable)
            {
                // In IChainedCommandHandler, we have to explicitly call the next command handler
                nextCommandHandler();
                return;
            }

            var view = args.TextView;
            var location = view.Caret.Position.BufferPosition;
            var initialTextSnapshot = args.SubjectBuffer.CurrentSnapshot;

            // Note regarding undo: When completion and brace completion happen together, completion should be first on the undo stack.
            // Effectively, we want to first undo the completion, leaving brace completion intact. Second undo should undo brace completion.
            // To achieve this, we create a transaction in which we commit and reapply brace completion (via nextCommandHandler).
            // Please read "Note regarding undo" comments in this method that explain the implementation choices.
            // Hopefully an upcoming upgrade of the undo mechanism will allow us to undo out of order and vastly simplify this method.

            // Note regarding undo: In a corner case of typing closing brace over existing closing brace,
            // Roslyn brace completion does not perform an edit. It moves the caret outside of session's applicable span,
            // which dismisses the session. Put the session in a state where it will not dismiss when caret leaves the applicable span.
            var sessionToCommit = Broker.GetSession(args.TextView);
            if (sessionToCommit != null)
            {
                ((AsyncCompletionSession)sessionToCommit).IgnoreCaretMovement(ignore: true);
            }

            // Execute other commands in the chain to see the change in the buffer. This includes brace completion.
            // Note regarding undo: This will be 2nd in the undo stack
            nextCommandHandler();

            // if on different version than initialTextSnapshot, we will NOT rollback and we will NOT replay the nextCommandHandler
            // DP to figure out why ShouldCommit returns false or Commit doesn't do anything
            var braceCompletionSpecialHandling = args.SubjectBuffer.CurrentSnapshot.Version == initialTextSnapshot.Version;

            // Pass location from before calling nextCommandHandler
            // so that extenders get the same view of the buffer in both ShouldCommit and Commit
            if (sessionToCommit?.ShouldCommit(args.TypedChar, location, executionContext.OperationContext.UserCancellationToken) == true)
            {
                // Buffer has changed, update the snapshot
                location = view.Caret.Position.BufferPosition;

                // Note regarding undo: this transaction will be 1st in the undo stack
                using (var undoTransaction = new CaretPreservingEditTransaction("Completion", view, UndoHistoryRegistry, EditorOperationsFactoryService))
                {
                    if (!braceCompletionSpecialHandling)
                        UndoUtilities.RollbackToBeforeTypeChar(initialTextSnapshot, args.SubjectBuffer);
                    // Now the buffer doesn't have the commit character nor the matching brace, if any

                    var commitBehavior = sessionToCommit.Commit(args.TypedChar, executionContext.OperationContext.UserCancellationToken);

                    if (!braceCompletionSpecialHandling && (commitBehavior & CommitBehavior.SuppressFurtherTypeCharCommandHandlers) == 0)
                        nextCommandHandler(); // Replay the key, so that we get brace completion.

                    // Complete the transaction before stopping it.
                    undoTransaction.Complete();
                }
            }

            // Restore the default state where session dismisses when caret is outside of the applicable span.
            if (sessionToCommit != null)
            {
               ((AsyncCompletionSession)sessionToCommit).IgnoreCaretMovement(ignore: false);
            }

            // Buffer might have changed. Update it for when we try to trigger new session.
            location = view.Caret.Position.BufferPosition;

            var trigger = new InitialTrigger(InitialTriggerReason.Insertion, args.TypedChar);
            var session = Broker.GetSession(args.TextView);
            if (session != null)
            {
                session.OpenOrUpdate(trigger, location, executionContext.OperationContext.UserCancellationToken);
            }
            else
            {
                var newSession = Broker.TriggerCompletion(args.TextView, location, args.TypedChar, executionContext.OperationContext.UserCancellationToken);
                newSession?.OpenOrUpdate(trigger, location, executionContext.OperationContext.UserCancellationToken);
            }
        }

        CommandState ICommandHandler<DownKeyCommandArgs>.GetCommandState(DownKeyCommandArgs args)
            => GetCommandStateIfCompletionIsActive(args.TextView);

        bool ICommandHandler<DownKeyCommandArgs>.ExecuteCommand(DownKeyCommandArgs args, CommandExecutionContext executionContext)
        {
            if (Broker.GetSession(args.TextView) is AsyncCompletionSession session) // we are accessing an internal method
            {
                session.SelectDown();
                return true;
            }
            return false;
        }

        CommandState ICommandHandler<PageDownKeyCommandArgs>.GetCommandState(PageDownKeyCommandArgs args)
            => GetCommandStateIfCompletionIsActive(args.TextView);

        bool ICommandHandler<PageDownKeyCommandArgs>.ExecuteCommand(PageDownKeyCommandArgs args, CommandExecutionContext executionContext)
        {
            if (Broker.GetSession(args.TextView) is AsyncCompletionSession session) // we are accessing an internal method
            {
                session.SelectPageDown();
                return true;
            }
            return false;
        }

        CommandState ICommandHandler<PageUpKeyCommandArgs>.GetCommandState(PageUpKeyCommandArgs args)
            => GetCommandStateIfCompletionIsActive(args.TextView);

        bool ICommandHandler<PageUpKeyCommandArgs>.ExecuteCommand(PageUpKeyCommandArgs args, CommandExecutionContext executionContext)
        {
            if (Broker.GetSession(args.TextView) is AsyncCompletionSession session) // we are accessing an internal method
            {
                session.SelectPageUp();
                return true;
            }
            return false;
        }

        CommandState ICommandHandler<UpKeyCommandArgs>.GetCommandState(UpKeyCommandArgs args)
            => GetCommandStateIfCompletionIsActive(args.TextView);

        bool ICommandHandler<UpKeyCommandArgs>.ExecuteCommand(UpKeyCommandArgs args, CommandExecutionContext executionContext)
        {
            if (Broker.GetSession(args.TextView) is AsyncCompletionSession session) // we are accessing an internal method
            {
                session.SelectUp();
                System.Diagnostics.Debug.WriteLine("Completions's UpKey command handler returns true (handled)");
                return true;
            }
            System.Diagnostics.Debug.WriteLine("Completions's UpKey command handler returns false (unhandled)");
            return false;
        }
    }
}