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

BraceCompletionManager.cs « BraceCompletion « Impl « Text « src - github.com/microsoft/vs-editor-api.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: b5f96891fce57e522ef165eb9d395624ecd8ae12 (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
//
//  Copyright (c) Microsoft Corporation. All rights reserved.
//  Licensed under the MIT License. See License.txt in the project root for license information.
//
// This file contain implementations details that are subject to change without notice.
// Use at your own risk.
//
namespace Microsoft.VisualStudio.Text.BraceCompletion.Implementation
{
    using Microsoft.VisualStudio.Text.Editor;
    using Microsoft.VisualStudio.Text.Utilities;
    using Microsoft.VisualStudio.Utilities;
    using System;
    using System.Diagnostics;

    /// <summary>
    /// A per view manager for brace completion. This is called by the command filter in the 
    /// editor pkg.
    /// </summary>
    internal sealed class BraceCompletionManager : IBraceCompletionManager
    {
        #region Private Members

        private readonly IBraceCompletionStack _stack;
        private readonly IBraceCompletionAggregatorFactory _sessionFactory;
        private readonly IBraceCompletionAggregator _sessionAggregator;
        private readonly ITextView _textView;
        private readonly IGuardedOperations _guardedOperations;

        private bool _braceCompletionEnabled;

        private IBraceCompletionSession _postSession;
        private IBraceCompletionSession _waitingSession;
        private SnapshotPoint? _waitingSessionOpeningPoint;

        #endregion

        #region Constructors

        internal BraceCompletionManager(ITextView textView, IBraceCompletionStack stack, IBraceCompletionAggregatorFactory sessionFactory, IGuardedOperations guardedOperations)
        {
            _textView = textView;
            _stack = stack;
            _sessionFactory = sessionFactory;
            _guardedOperations = guardedOperations;
            _sessionAggregator = sessionFactory.CreateAggregator();

            GetOptions();
            RegisterEvents();
        }

        #endregion

        #region IBraceCompletionManager

        public bool Enabled
        {
            get
            {
                return _braceCompletionEnabled;
            }
        }

        public string ClosingBraces
        {
            get
            {
                return _sessionAggregator.ClosingBraces;
            }
        }

        public bool HasActiveSessions
        {
            get { return _stack.TopSession != null; }
        }

        public string OpeningBraces
        {
            get
            {
                return _sessionAggregator.OpeningBraces;
            }
        }

        public void PreTypeChar(char character, out bool handledCommand)
        {
            bool handled = false;

            bool hasSelection = HasSelection;

            Debug.Assert(_postSession == null, "_postSession should have been cleared");

            // give the existing session a chance to handle the character first

            if (_stack.TopSession != null && !hasSelection)
            {
                IBraceCompletionSession session = _stack.TopSession;

                // check for an existing session first
                _guardedOperations.CallExtensionPoint(() =>
                {
                    if (session.ClosingBrace.Equals(character) && IsCaretOnBuffer(session.SubjectBuffer))
                    {
                        session.PreOverType(out handled);

                        if (!handled)
                        {
                            _postSession = session;
                        }
                    }
                });
            }

            handledCommand = handled;

            // otherwise check if this starts a new session
            if (_postSession == null && !handled && Enabled && !hasSelection
                && _sessionAggregator.OpeningBraces.IndexOf(character) > -1 && !HasForwardTypingOnLine)
            {
                SnapshotPoint? openingPoint = _textView.Caret.Position.Point.GetInsertionPoint((b => _sessionAggregator.IsSupportedContentType(b.ContentType, character)));

                if (openingPoint.HasValue)
                {
                    IBraceCompletionSession session = null;
                    if (_sessionAggregator.TryCreateSession(_textView, openingPoint.Value, character, out session))
                    {
                        // add the session after the current keystroke completes
                        _waitingSession = session;
                        _waitingSessionOpeningPoint = openingPoint;
                    }
                }
            }
        }

        public void PostTypeChar(char character)
        {
            // check for any waiting sessions
            if (_waitingSession != null)
            {
                // Verify the session is still valid before starting it
                // and inserting the closing brace.
                if (ValidateStart(_waitingSessionOpeningPoint, character))
                {
                    _stack.PushSession(_waitingSession);
                }

                _waitingSession = null;
                _waitingSessionOpeningPoint = null;
            }
            else if (_postSession != null)
            {
                _guardedOperations.CallExtensionPoint(() =>
                {
                    if (_postSession.ClosingBrace.Equals(character))
                    {
                        _postSession.PostOverType();
                    }
                });

                _postSession = null;
            }
        }

        public void PreTab(out bool handledCommand)
        {
            bool handled = false;

            Debug.Assert(_postSession == null, "_postSession should have been cleared");

            // tab should only be handled by brace completion if there is no selection and both braces on the same line still
            if (_stack.TopSession != null && !HasSelection)
            {
                IBraceCompletionSession session = _stack.TopSession;

                _guardedOperations.CallExtensionPoint(() =>
                {
                    if (IsSingleLine(session.OpeningPoint, session.ClosingPoint))
                    {
                        session.PreTab(out handled);

                        if (!handled)
                        {
                            _postSession = session;
                        }
                    }
                });
            }

            handledCommand = handled;
        }

        public void PostTab()
        {
            if (_postSession != null)
            {
                _guardedOperations.CallExtensionPoint(() =>
                {
                    _postSession.PostTab();
                });

                _postSession = null;
            }
        }

        public void PreBackspace(out bool handledCommand)
        {
            bool handled = false;

            Debug.Assert(_postSession == null, "_postSession should have been cleared");

            if (_stack.TopSession != null && !HasSelection)
            {
                IBraceCompletionSession session = _stack.TopSession;

                _guardedOperations.CallExtensionPoint(() => 
                {
                    if (session.OpeningPoint != null && session.ClosingPoint != null)
                    {
                        session.PreBackspace(out handled);

                        if (!handled)
                        {
                            _postSession = session;
                        }
                    }
                });
            }

            handledCommand = handled;
        }

        public void PostBackspace()
        {
            if (_postSession != null)
            {
                _guardedOperations.CallExtensionPoint(() =>
                {
                    _postSession.PostBackspace();
                });

                _postSession = null;
            }
        }

        public void PreDelete(out bool handledCommand)
        {
            bool handled = false;

            Debug.Assert(_postSession == null, "_postSession should have been cleared");

            if (_stack.TopSession != null && !HasSelection)
            {
                IBraceCompletionSession session = _stack.TopSession;

                _guardedOperations.CallExtensionPoint(() =>
                {
                    if (session.OpeningPoint != null && session.ClosingPoint != null)
                    {
                        session.PreDelete(out handled);

                        if (!handled)
                        {
                            _postSession = session;
                        }
                    }
                });
            }

            handledCommand = handled;
        }

        public void PostDelete()
        {
            if (_postSession != null)
            {
                _guardedOperations.CallExtensionPoint(() =>
                {
                    _postSession.PostDelete();
                });

                _postSession = null;
            }
        }

        public void PreReturn(out bool handledCommand)
        {
            bool handled = false;

            Debug.Assert(_postSession == null, "_postSession should have been cleared");

            if (_stack.TopSession != null && !HasSelection)
            {
                IBraceCompletionSession session = _stack.TopSession;

                _guardedOperations.CallExtensionPoint(() =>
                {
                    if (IsSingleLine(session.OpeningPoint, session.ClosingPoint))
                    {
                        session.PreReturn(out handled);

                        if (!handled)
                        {
                            _postSession = session;
                        }
                    }
                });
            }

            handledCommand = handled;
        }

        public void PostReturn()
        {
            if (_postSession != null)
            {
                _guardedOperations.CallExtensionPoint(() =>
                {
                    _postSession.PostReturn();
                });

                _postSession = null;
            }
        }

        #endregion

        #region Events/Options

        private void RegisterEvents()
        {
            _textView.Closed += textView_Closed;
            _textView.Options.OptionChanged += Options_OptionChanged;
        }

        private void textView_Closed(object sender, EventArgs e)
        {
            UnregisterEvents();
        }

        private void UnregisterEvents()
        {
            _textView.Closed -= textView_Closed;
            _textView.Options.OptionChanged -= Options_OptionChanged;
        }

        private void Options_OptionChanged(object sender, EditorOptionChangedEventArgs e)
        {
            GetOptions();
        }

        private void GetOptions()
        {
            bool beforeEnabled = _braceCompletionEnabled;

            _braceCompletionEnabled = _textView.Options.GetOptionValue(DefaultTextViewOptions.BraceCompletionEnabledOptionId);

            // if completion was disabled, clear out the stack
            if (beforeEnabled && !_braceCompletionEnabled)
            {
                _waitingSession = null;
                _postSession = null;
                _stack.Clear();
            }
        }

        #endregion

        #region Private Helpers

        private bool IsCaretOnBuffer(ITextBuffer buffer)
        {
            return _textView.Caret.Position.Point.GetPoint(buffer, PositionAffinity.Successor).HasValue;
        }

        private bool HasSelection
        {
            get
            {
                return !_textView.Selection.IsEmpty;
            }
        }

        // Determine if the line has text on it apart from any active braces in this view
        private bool HasForwardTypingOnLine
        {
            get
            {
                SnapshotPoint start = _textView.Caret.Position.BufferPosition;
                SnapshotPoint end = _textView.Caret.ContainingTextViewLine.End;

                if (start != end)
                {
                    // if we have an active session use that brace as the end
                    if (_stack.TopSession != null)
                    {
                        ITrackingPoint closingPoint = null;
                        IBraceCompletionSession session = _stack.TopSession;

                        _guardedOperations.CallExtensionPoint(() =>
                        {
                            // only set these if they are on the same buffer
                            if (session.OpeningPoint != null && session.ClosingPoint != null
                                && session.OpeningPoint.TextBuffer == session.ClosingPoint.TextBuffer)
                            {
                                closingPoint = session.ClosingPoint;
                            }
                        });

                        if (closingPoint != null)
                        {
                            SnapshotPoint? innerBraceEnd = closingPoint.GetPoint(closingPoint.TextBuffer.CurrentSnapshot);

                            if (innerBraceEnd.HasValue && _stack.TopSession.SubjectBuffer != _textView.TextBuffer)
                            {
                                // map the closing point to the text buffer for the check
                                innerBraceEnd = _textView.BufferGraph.MapUpToBuffer(innerBraceEnd.Value,
                                    closingPoint.TrackingMode, PositionAffinity.Predecessor, _textView.TextBuffer);
                            }

                            if (innerBraceEnd.HasValue && innerBraceEnd.Value.Position <= end && innerBraceEnd.Value.Position > 0)
                            {
                                end = innerBraceEnd.Value.Subtract(1);
                            }
                        }
                    }

                    // check if we aren't the last closing brace
                    if (start == end)
                    {
                        return false;
                    }
                    else if (start < end)
                    {
                        SnapshotSpan span = new SnapshotSpan(start, end);

                        if (!span.IsEmpty)
                        {
                            return !string.IsNullOrWhiteSpace(span.GetText());
                        }
                    }
                    else
                    {
                        Debug.Fail("unable to check for forward typing");
                        // shouldn't happen, but if it does count it as forward typing to avoid
                        // further action
                        return true;
                    }
                }

                return false;
            }
        }

        private static bool IsSingleLine(ITrackingPoint openingPoint, ITrackingPoint closingPoint)
        {
            if (openingPoint != null && closingPoint != null)
            {
                ITextSnapshot snapshot = openingPoint.TextBuffer.CurrentSnapshot;

                return openingPoint.GetPoint(snapshot).GetContainingLine().End.Position >= closingPoint.GetPoint(snapshot).Position;
            }

            return false;
        }

        // Verify that we are about to insert the closing brace right after the opening one
        private bool ValidateStart(SnapshotPoint? openingPoint, char openingChar)
        {
            if (openingPoint.HasValue)
            {
                ITextBuffer subjectBuffer = openingPoint.Value.Snapshot.TextBuffer;

                // Get the position based on the predecessor which should be the opening brace
                SnapshotPoint? caretPosition = _textView.Caret.Position.Point.GetPoint(subjectBuffer, PositionAffinity.Predecessor);

                // verify that the opening brace is right behind the caret
                if (caretPosition.HasValue && caretPosition.Value.Position > 0)
                {
                    SnapshotPoint openingBrace = caretPosition.Value.Subtract(1);
                    return (openingBrace.GetChar() == openingChar);
                }
            }

            return false;
        }

        #endregion
    }
}