Repository navigation
Expand file tree
/
Copy pathInteractiveWindow.cs
More file actions
3160 lines (2622 loc) · 111 KB
/
Copy pathInteractiveWindow.cs
File metadata and controls
3160 lines (2622 loc) · 111 KB
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
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
// Dumps commands in QueryStatus and Exec.
// #define DUMP_COMMANDS
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Threading;
using Microsoft.VisualStudio.Language.Intellisense;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Editor.OptionsExtensionMethods;
using Microsoft.VisualStudio.Text.Operations;
using Microsoft.VisualStudio.Text.Projection;
using Microsoft.VisualStudio.Utilities;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.InteractiveWindow
{
// TODO: We should condense committed language buffers into a single language buffer and save the
// classifications from the previous language buffer if the perf of having individual buffers
// starts having problems w/ a large number of inputs.
/// <summary>
/// Provides implementation of a Repl Window built on top of the VS editor using projection buffers.
/// </summary>
internal class InteractiveWindow : IInteractiveWindow
{
private bool _adornmentToMinimize = false;
// true iff code is being executed:
private bool _isRunning;
private bool _isInitializing;
private Task<ExecutionResult> _currentTask;
private DispatcherTimer _executionTimer;
private Cursor _oldCursor;
private readonly IWpfTextView _textView;
private readonly IEditorOperations _editorOperations;
private readonly InteractiveOperations _interactiveOperations;
private readonly History _history;
private readonly TaskScheduler _uiScheduler;
public event EventHandler<SubmissionBufferAddedEventArgs> SubmissionBufferAdded;
////
//// Services
////
private readonly IInteractiveWindowEditorFactoryService _host;
private readonly IContentTypeRegistryService _contentTypeRegistry;
private readonly IEditorOperationsFactoryService _editorOperationsFactory;
private readonly ITextEditorFactoryService _editorFactory;
private readonly IIntellisenseSessionStackMapService _intellisenseSessionStackMap;
private readonly ISmartIndentationService _smartIndenterService;
// the language engine and content type of the active submission:
private bool _engineInitialized;
private IInteractiveEvaluator _engine;
private IIntellisenseSessionStack _sessionStack; // TODO: remove
public PropertyCollection Properties { get; }
////
//// Buffer composition.
////
private readonly ITextBufferFactoryService _bufferFactory; // Factory for creating output, std input, prompt and language buffers.
private readonly IProjectionBufferFactoryService _projectionBufferFactory;
private readonly ITextBuffer _outputBuffer;
private readonly IProjectionBuffer _projectionBuffer;
private readonly ITextBuffer _stdInputBuffer;
private ITextBuffer _currentLanguageBuffer;
private string _historySearch;
// Read-only regions protecting initial span of the corresponding buffers:
private readonly IReadOnlyRegion[] _stdInputProtection = new IReadOnlyRegion[2];
private readonly IReadOnlyRegion[] _outputProtection = new IReadOnlyRegion[2];
// List of projection buffer spans - the projection buffer doesn't allow us to enumerate spans so we need to track them manually:
private readonly List<ReplSpan> _projectionSpans = new List<ReplSpan>();
private readonly PromptLineMapping _promptLineMapping = new PromptLineMapping();
////
//// Submissions.
////
// Pending submissions to be processed whenever the REPL is ready to accept submissions.
private Queue<PendingSubmission> _pendingSubmissions;
////
//// Standard input.
////
// non-null if reading from stdin - position in the _inputBuffer where we map stdin
private int? _stdInputStart; // TODO (tomat): this variable is not used in thread-safe manner
private int _currentInputId = 1;
private SnapshotSpan? _inputValue;
private string _uncommittedInput;
private readonly AutoResetEvent _inputEvent = new AutoResetEvent(false);
////
//// Output.
////
private readonly OutputBuffer _buffer;
private readonly TextWriter _outputWriter;
private readonly TextWriter _errorOutputWriter;
private int _currentOutputProjectionSpan;
private int _outputTrackingCaretPosition;
private readonly ReplSpan _lineBreakOutputSpan;
private readonly ReplSpan _emptySubmissionSpan;
private static readonly char[] s_whitespaceChars = new[] { '\r', '\n', ' ', '\t' };
private const string BoxSelectionCutCopyTag = "MSDEVColumnSelect";
#region Initialization
public InteractiveWindow(
IInteractiveWindowEditorFactoryService host,
IContentTypeRegistryService contentTypeRegistry,
ITextBufferFactoryService bufferFactory,
IProjectionBufferFactoryService projectionBufferFactory,
IEditorOperationsFactoryService editorOperationsFactory,
ITextEditorFactoryService editorFactory,
IIntellisenseSessionStackMapService intellisenseSessionStackMap,
ISmartIndentationService smartIndenterService,
IInteractiveEvaluator evaluator)
{
_host = host;
this.Properties = new PropertyCollection();
_history = new History();
_interactiveOperations = new InteractiveOperations(this);
_projectionBufferFactory = projectionBufferFactory;
_bufferFactory = bufferFactory;
_editorFactory = editorFactory;
_contentTypeRegistry = contentTypeRegistry;
_editorOperationsFactory = editorOperationsFactory;
_intellisenseSessionStackMap = intellisenseSessionStackMap;
_smartIndenterService = smartIndenterService;
var textContentType = contentTypeRegistry.GetContentType("text");
var replContentType = contentTypeRegistry.GetContentType(PredefinedInteractiveContentTypes.InteractiveContentTypeName);
var replOutputContentType = contentTypeRegistry.GetContentType(PredefinedInteractiveContentTypes.InteractiveOutputContentTypeName);
_outputBuffer = bufferFactory.CreateTextBuffer(replOutputContentType);
_stdInputBuffer = bufferFactory.CreateTextBuffer();
var projBuffer = projectionBufferFactory.CreateProjectionBuffer(
new EditResolver(this),
SpecializedCollections.EmptyList<object>(),
ProjectionBufferOptions.None,
replContentType);
// we need to set IReplPromptProvider property before TextViewHost is instantiated so that ReplPromptTaggerProvider can bind to it
projBuffer.Properties.AddProperty(typeof(InteractiveWindow), this);
_projectionBuffer = projBuffer;
AppendNewOutputProjectionBuffer();
projBuffer.Changed += new EventHandler<TextContentChangedEventArgs>(ProjectionBufferChanged);
_textView = host.CreateTextView(this, projBuffer, CreateRoleSet());
TextView.Caret.PositionChanged += CaretPositionChanged;
TextView.Options.SetOptionValue(DefaultTextViewHostOptions.HorizontalScrollBarId, false);
TextView.Options.SetOptionValue(DefaultTextViewHostOptions.LineNumberMarginId, false);
TextView.Options.SetOptionValue(DefaultTextViewHostOptions.OutliningMarginId, false);
TextView.Options.SetOptionValue(DefaultTextViewHostOptions.GlyphMarginId, false);
TextView.Options.SetOptionValue(DefaultTextViewOptions.WordWrapStyleId, WordWrapStyles.WordWrap);
string lineBreak = TextView.Options.GetNewLineCharacter();
_lineBreakOutputSpan = new ReplSpan(lineBreak, ReplSpanKind.Output);
_emptySubmissionSpan = new ReplSpan(lineBreak, ReplSpanKind.Language);
_editorOperations = editorOperationsFactory.GetEditorOperations(TextView);
_uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();
_outputTrackingCaretPosition = -1;
_buffer = new OutputBuffer(this);
_outputWriter = new InteractiveWindowWriter(this, spans: null);
SortedSpans errorSpans = new SortedSpans();
_errorOutputWriter = new InteractiveWindowWriter(this, errorSpans);
OutputClassifierProvider.AttachToBuffer(_outputBuffer, errorSpans);
this.Evaluator = evaluator;
}
public async Task<ExecutionResult> InitializeAsync()
{
RequiresUIThread();
if (_engineInitialized)
{
throw new InvalidOperationException(InteractiveWindowResources.AlreadyInitialized);
}
_isInitializing = true;
_engineInitialized = true;
ExecutionResult result;
try
{
// Anything that reads options should wait until after this call so the evaluator can set the options first
result = await _engine.InitializeAsync().ConfigureAwait(continueOnCapturedContext: true);
}
finally
{
_isInitializing = false;
}
_engineInitialized = true;
Debug.Assert(Dispatcher.CheckAccess());
if (result.IsSuccessful)
{
PrepareForInput();
}
return result;
}
private ITextViewRoleSet CreateRoleSet()
{
return _editorFactory.CreateTextViewRoleSet(
PredefinedTextViewRoles.Analyzable,
PredefinedTextViewRoles.Editable,
PredefinedTextViewRoles.Interactive,
PredefinedTextViewRoles.Zoomable,
PredefinedInteractiveTextViewRoles.InteractiveTextViewRole);
}
public void Close()
{
Caret.PositionChanged -= CaretPositionChanged;
TextView.Close();
}
#endregion
#region Misc Helpers
private string LineBreak
{
get { return _lineBreakOutputSpan.InertValue; }
}
private IIntellisenseSessionStack SessionStack
{
get
{
if (_sessionStack == null)
{
_sessionStack = _intellisenseSessionStackMap.GetStackForTextView(TextView);
}
return _sessionStack;
}
}
public ITextBuffer TextBuffer
{
get { return TextView.TextBuffer; }
}
public ITextSnapshot CurrentSnapshot
{
get { return TextBuffer.CurrentSnapshot; }
}
public ITextBuffer CurrentLanguageBuffer
{
get { return _currentLanguageBuffer; }
}
private void RequiresLanguageBuffer()
{
if (_currentLanguageBuffer == null)
{
Environment.FailFast("Language buffer not available");
}
}
public void Dispose()
{
if (_buffer != null)
{
_buffer.Dispose();
}
}
public static InteractiveWindow FromBuffer(ITextBuffer buffer)
{
object result;
buffer.Properties.TryGetProperty(typeof(InteractiveWindow), out result);
return result as InteractiveWindow;
}
#endregion
#region IInteractiveWindow
public event Action ReadyForInput;
public IWpfTextView TextView
{
get
{
return _textView;
}
}
public ITextBuffer OutputBuffer
{
get { return _outputBuffer; }
}
public TextWriter OutputWriter
{
get { return _outputWriter; }
}
public TextWriter ErrorOutputWriter
{
get { return _errorOutputWriter; }
}
public IInteractiveEvaluator Evaluator
{
get
{
return _engine;
}
set
{
RequiresUIThread();
if (value == null)
{
throw new ArgumentNullException("engine");
}
if (_engine != value)
{
value.CurrentWindow = this;
_engine = value;
_engineInitialized = false;
}
}
}
public void ClearHistory()
{
if (!CheckAccess())
{
Dispatcher.Invoke(new Action(ClearHistory));
return;
}
_history.Clear();
}
public void ClearView()
{
UIThread(() => ClearView(insertInputPrompt: !_isRunning));
}
private void ClearView(bool insertInputPrompt)
{
Debug.Assert(CheckAccess());
if (_stdInputStart != null)
{
CancelStandardInput();
}
_adornmentToMinimize = false;
InlineAdornmentProvider.RemoveAllAdornments(TextView);
// remove all the spans except our initial span from the projection buffer
_promptLineMapping.Clear();
_currentInputId = 1;
_uncommittedInput = null;
// Clear the projection and buffers last as this might trigger events that might access other state of the REPL window:
RemoveProtection(_outputBuffer, _outputProtection);
RemoveProtection(_stdInputBuffer, _stdInputProtection);
using (var edit = _outputBuffer.CreateEdit(EditOptions.None, null, s_suppressPromptInjectionTag))
{
edit.Delete(0, _outputBuffer.CurrentSnapshot.Length);
edit.Apply();
}
_buffer.Reset();
OutputClassifierProvider.ClearSpans(_outputBuffer);
_outputTrackingCaretPosition = 0;
using (var edit = _stdInputBuffer.CreateEdit(EditOptions.None, null, s_suppressPromptInjectionTag))
{
edit.Delete(0, _stdInputBuffer.CurrentSnapshot.Length);
edit.Apply();
}
RemoveProjectionSpans(0, _projectionSpans.Count);
// Insert an empty output buffer.
// We do it for two reasons:
// 1) When output is written to asynchronously we need a buffer to store it.
// This may happen when clearing screen while background thread is writing to the console.
// 2) We need at least one non-inert span due to bugs in projection buffer.
AppendNewOutputProjectionBuffer();
_history.ForgetOriginalBuffers();
if (insertInputPrompt)
{
PrepareForInput();
}
}
public void InsertCode(string text)
{
if (!CheckAccess())
{
Dispatcher.BeginInvoke(new Action(() => InsertCode(text)));
return;
}
if (_stdInputStart == null)
{
if (_isRunning)
{
AppendUncommittedInput(text);
}
else
{
if (!TextView.Selection.IsEmpty)
{
CutOrDeleteSelection(isCut: false);
}
_editorOperations.InsertText(text);
}
}
}
public Task SubmitAsync(IEnumerable<string> inputs)
{
var completion = new TaskCompletionSource<object>();
var submissions = inputs.ToArray();
PendingSubmission[] pendingSubmissions = new PendingSubmission[submissions.Length];
if (submissions.Length == 0)
{
completion.SetResult(null);
}
else
{
for (int i = 0; i < submissions.Length; i++)
{
if (i == submissions.Length - 1)
{
pendingSubmissions[i] = new PendingSubmission(submissions[i], completion);
}
else
{
pendingSubmissions[i] = new PendingSubmission(submissions[i], null);
}
}
}
Submit(pendingSubmissions);
return completion.Task;
}
private void Submit(PendingSubmission[] pendingSubmissions)
{
if (!CheckAccess())
{
Dispatcher.BeginInvoke(new Action(() => Submit(pendingSubmissions)));
return;
}
if (_stdInputStart == null)
{
if (!_isRunning && _currentLanguageBuffer != null)
{
StoreUncommittedInput();
PendSubmissions(pendingSubmissions);
ProcessPendingSubmissions();
}
else
{
PendSubmissions(pendingSubmissions);
}
}
}
private class PendingSubmission
{
public readonly string Input;
public readonly TaskCompletionSource<object> Completion; // only set on the last submission to
// inform caller about completion of batch
public PendingSubmission(string input, TaskCompletionSource<object> completion)
{
Input = input;
Completion = completion;
}
}
private void PendSubmissions(IEnumerable<PendingSubmission> inputs)
{
if (_pendingSubmissions == null)
{
_pendingSubmissions = new Queue<PendingSubmission>();
}
foreach (var input in inputs)
{
_pendingSubmissions.Enqueue(input);
}
}
public void AddInput(string command)
{
if (_isRunning || _currentLanguageBuffer == null)
{
AddLanguageBuffer();
_currentLanguageBuffer.Insert(0, command);
}
else
{
StoreUncommittedInput();
SetActiveCode(command);
}
FinishCurrentSubmissionInput();
_history.Add(_currentLanguageBuffer.CurrentSnapshot.GetExtent());
}
public Task<ExecutionResult> ResetAsync(bool initialize = true)
{
if (!CheckAccess())
{
return UIThread(() => ResetAsync(initialize));
}
Debug.Assert(CheckAccess());
if (_stdInputStart != null)
{
CancelStandardInput();
}
_buffer.Flush();
// replace the task being interrupted by a "reset" task:
_isRunning = true;
_isInitializing = true;
_currentTask = _engine.ResetAsync(initialize);
_currentTask.ContinueWith(FinishExecute, _uiScheduler);
return _currentTask;
}
public void FlushOutput()
{
_buffer.Flush();
}
#endregion
#region Commands
/// <summary>
/// Clears the current input
/// </summary>
public void Cancel()
{
ClearInput();
_editorOperations.MoveToEndOfDocument(false);
_uncommittedInput = null;
_historySearch = null;
}
public void HistoryPrevious(string search = null)
{
if (_currentLanguageBuffer == null)
{
return;
}
var previous = _history.GetPrevious(search);
if (previous != null)
{
if (string.IsNullOrWhiteSpace(search))
{
// don't store search as an uncommitted history item
StoreUncommittedInputForHistory();
}
SetActiveCodeToHistory(previous);
_editorOperations.MoveToEndOfDocument(false);
}
}
public void HistoryNext(string search = null)
{
if (_currentLanguageBuffer == null)
{
return;
}
var next = _history.GetNext(search);
if (next != null)
{
if (string.IsNullOrWhiteSpace(search))
{
// don't store search as an uncommitted history item
StoreUncommittedInputForHistory();
}
SetActiveCodeToHistory(next);
_editorOperations.MoveToEndOfDocument(false);
}
else
{
string code = _history.UncommittedInput;
_history.UncommittedInput = null;
if (!string.IsNullOrEmpty(code))
{
SetActiveCode(code);
_editorOperations.MoveToEndOfDocument(false);
}
}
}
public void HistorySearchNext()
{
EnsureHistorySearch();
HistoryNext(_historySearch);
}
public void HistorySearchPrevious()
{
EnsureHistorySearch();
HistoryPrevious(_historySearch);
}
private void EnsureHistorySearch()
{
if (_historySearch == null)
{
_historySearch = CurrentLanguageBuffer.CurrentSnapshot.GetText();
}
}
private void StoreUncommittedInputForHistory()
{
if (_history.UncommittedInput == null)
{
string activeCode = GetActiveCode();
if (activeCode.Length > 0)
{
_history.UncommittedInput = activeCode;
}
}
}
/// <summary>
/// Moves to the beginning of the line.
/// </summary>
public void Home(bool extendSelection)
{
var caret = Caret;
// map the end of subject buffer line:
var subjectLineEnd = TextView.BufferGraph.MapDownToFirstMatch(
caret.Position.BufferPosition.GetContainingLine().End,
PointTrackingMode.Positive,
snapshot => snapshot.TextBuffer != _projectionBuffer,
PositionAffinity.Successor).Value;
ITextSnapshotLine subjectLine = subjectLineEnd.GetContainingLine();
var projectedSubjectLineStart = TextView.BufferGraph.MapUpToBuffer(
subjectLine.Start,
PointTrackingMode.Positive,
PositionAffinity.Successor,
_projectionBuffer).Value;
// If the caret is already at the first non-whitespace character or the line is
// entirely whitespace, move to the start of the view line. See
// (EditorOperations.MoveToHome).
//
// If the caret is in the prompt move the caret to the beginning of the language
// line.
int firstNonWhiteSpace = IndexOfNonWhiteSpaceCharacter(subjectLine);
SnapshotPoint moveTo;
if (firstNonWhiteSpace == -1 ||
projectedSubjectLineStart.Position + firstNonWhiteSpace == caret.Position.BufferPosition ||
caret.Position.BufferPosition < projectedSubjectLineStart.Position)
{
moveTo = projectedSubjectLineStart;
}
else
{
moveTo = projectedSubjectLineStart + firstNonWhiteSpace;
}
if (extendSelection)
{
VirtualSnapshotPoint anchor = TextView.Selection.AnchorPoint;
caret.MoveTo(moveTo);
TextView.Selection.Select(anchor.TranslateTo(TextView.TextSnapshot), TextView.Caret.Position.VirtualBufferPosition);
}
else
{
TextView.Selection.Clear();
caret.MoveTo(moveTo);
}
}
/// <summary>
/// Moves to the end of the line.
/// </summary>
public void End(bool extendSelection)
{
var caret = Caret;
// map the end of the subject buffer line:
var subjectLineEnd = TextView.BufferGraph.MapDownToFirstMatch(
caret.Position.BufferPosition.GetContainingLine().End,
PointTrackingMode.Positive,
snapshot => snapshot.TextBuffer != _projectionBuffer,
PositionAffinity.Successor).Value;
ITextSnapshotLine subjectLine = subjectLineEnd.GetContainingLine();
var moveTo = TextView.BufferGraph.MapUpToBuffer(
subjectLine.End,
PointTrackingMode.Positive,
PositionAffinity.Successor,
_projectionBuffer).Value;
if (extendSelection)
{
VirtualSnapshotPoint anchor = TextView.Selection.AnchorPoint;
caret.MoveTo(moveTo);
TextView.Selection.Select(anchor.TranslateTo(TextView.TextSnapshot), TextView.Caret.Position.VirtualBufferPosition);
}
else
{
TextView.Selection.Clear();
caret.MoveTo(moveTo);
}
}
public void SelectAll()
{
SnapshotSpan? span = GetContainingRegion(TextView.Caret.Position.BufferPosition);
// if the span is already selected select all text in the projection buffer:
if (span == null || (TextView.Selection.SelectedSpans.Count == 1 && TextView.Selection.SelectedSpans[0] == span.Value))
{
span = new SnapshotSpan(TextBuffer.CurrentSnapshot, new Span(0, TextBuffer.CurrentSnapshot.Length));
}
TextView.Selection.Select(span.Value, isReversed: false);
}
/// <summary>
/// Given a point in projection buffer calculate a span that includes the point and comprises of
/// subsequent projection spans forming a region, i.e. a sequence of output spans in between two subsequent submissions,
/// a language input block, or standard input block.
///
/// Internal for testing.
/// </summary>
internal SnapshotSpan? GetContainingRegion(SnapshotPoint point)
{
int closestPrecedingPrimaryPromptIndex;
ReplSpan projectionSpan = GetClosestPrecedingInputSpan(point, out closestPrecedingPrimaryPromptIndex);
if (projectionSpan == null)
{
return null;
}
var inputSnapshot = projectionSpan.TrackingSpan.TextBuffer.CurrentSnapshot;
// Language input block is a projection of the entire snapshot;
// std input block is a projection of a single span:
SnapshotPoint inputBufferEnd = (projectionSpan.Kind == ReplSpanKind.Language) ?
new SnapshotPoint(inputSnapshot, inputSnapshot.Length) :
projectionSpan.TrackingSpan.GetEndPoint(inputSnapshot);
SnapshotPoint projectedInputBufferEnd = TextView.BufferGraph.MapUpToBuffer(
inputBufferEnd,
PointTrackingMode.Positive,
PositionAffinity.Predecessor,
TextBuffer).Value;
// point is between the primary prompt (including) and the last character of the corresponding language/stdin buffer:
if (point <= projectedInputBufferEnd)
{
var projectedLanguageBufferStart = TextView.BufferGraph.MapUpToBuffer(
new SnapshotPoint(inputSnapshot, 0),
PointTrackingMode.Positive,
PositionAffinity.Successor,
TextBuffer).Value;
var promptProjectionSpan = _projectionSpans[_promptLineMapping[closestPrecedingPrimaryPromptIndex].Value];
if (point < projectedLanguageBufferStart - promptProjectionSpan.Length)
{
// cursor is before the first language buffer:
return new SnapshotSpan(new SnapshotPoint(TextBuffer.CurrentSnapshot, 0), projectedLanguageBufferStart - promptProjectionSpan.Length);
}
// cursor is within the language buffer:
return new SnapshotSpan(projectedLanguageBufferStart, projectedInputBufferEnd);
}
// this was the last primary/stdin prompt - select the part of the projection buffer behind the end of the language/stdin buffer:
if (closestPrecedingPrimaryPromptIndex + 1 == _promptLineMapping.Count)
{
return new SnapshotSpan(
projectedInputBufferEnd,
new SnapshotPoint(TextBuffer.CurrentSnapshot, TextBuffer.CurrentSnapshot.Length));
}
ReplSpan lastSpanBeforeNextPrompt = _projectionSpans[_promptLineMapping[closestPrecedingPrimaryPromptIndex + 1].Value - 1];
Debug.Assert(lastSpanBeforeNextPrompt.Kind == ReplSpanKind.Output);
// select all text in between the language buffer and the next prompt:
var trackingSpan = lastSpanBeforeNextPrompt.TrackingSpan;
return new SnapshotSpan(
projectedInputBufferEnd,
TextView.BufferGraph.MapUpToBuffer(
trackingSpan.GetEndPoint(trackingSpan.TextBuffer.CurrentSnapshot),
PointTrackingMode.Positive,
PositionAffinity.Predecessor,
TextBuffer).Value);
}
/// <summary>
/// Pastes from the clipboard into the text view
/// </summary>
public bool Paste()
{
return UIThread(() =>
{
MoveCaretToClosestEditableBuffer();
string format = _engine.FormatClipboard();
if (format != null)
{
InsertCode(format);
}
else if (Clipboard.ContainsText())
{
InsertCode(Clipboard.GetText());
}
else
{
return false;
}
return true;
});
}
/// <summary>
/// Indents the line where the caret is currently located.
/// </summary>
/// <remarks>
/// We don't send this command to the editor since smart indentation doesn't work along with
/// BufferChanged event. Instead, we need to implement indentation ourselves. We still use
/// ISmartIndentProvider provided by the language.
/// </remarks>
private void IndentCurrentLine(SnapshotPoint caretPosition)
{
Debug.Assert(_currentLanguageBuffer != null);
var caretLine = caretPosition.GetContainingLine();
var indentation = _smartIndenterService.GetDesiredIndentation(TextView, caretLine);
if (indentation != null)
{
if (caretPosition == caretLine.End)
{
// create virtual space:
TextView.Caret.MoveTo(new VirtualSnapshotPoint(caretPosition, indentation.Value));
}
else
{
var langCaret = GetPositionInLanguageBuffer(caretPosition);
if (langCaret == null)
{
return;
}
// insert whitespace indentation:
string whitespace = GetWhiteSpaceForVirtualSpace(indentation.Value);
_currentLanguageBuffer.Insert(langCaret.Value, whitespace);
}
}
}
private SnapshotPoint? GetPositionInLanguageBuffer(SnapshotPoint point)
{
Debug.Assert(_currentLanguageBuffer != null);
return GetPositionInBuffer(point, _currentLanguageBuffer);
}
private SnapshotPoint? GetPositionInStdInputBuffer(SnapshotPoint point)
{
Debug.Assert(_stdInputBuffer != null);
return GetPositionInBuffer(point, _stdInputBuffer);
}
private SnapshotPoint? GetPositionInBuffer(SnapshotPoint point, ITextBuffer buffer)
{
return TextView.BufferGraph.MapDownToBuffer(
point,
PointTrackingMode.Positive,
buffer,
PositionAffinity.Successor);
}
// Mimics EditorOperations.GetWhiteSpaceForPositionAndVirtualSpace.
private string GetWhiteSpaceForVirtualSpace(int virtualSpaces)
{
string textToInsert;
if (!TextView.Options.IsConvertTabsToSpacesEnabled())
{
int tabSize = TextView.Options.GetTabSize();
int spacesAfterPreviousTabStop = virtualSpaces % tabSize;
int columnOfPreviousTabStop = virtualSpaces - spacesAfterPreviousTabStop;
int requiredTabs = (columnOfPreviousTabStop + tabSize - 1) / tabSize;
if (requiredTabs > 0)
{
textToInsert = new string('\t', requiredTabs) + new string(' ', spacesAfterPreviousTabStop);
}
else
{
textToInsert = new string(' ', virtualSpaces);
}
}
else
{
textToInsert = new string(' ', virtualSpaces);
}
return textToInsert;
}
/// <summary>
/// Deletes characters preceding the current caret position in the current language buffer.
/// </summary>
private void DeletePreviousCharacter()
{
SnapshotPoint? point = MapToEditableBuffer(TextView.Caret.Position.BufferPosition);
// We are not in an editable buffer, or we are at the start of the buffer, nothing to delete.
if (point == null || point.Value == 0)
{
return;
}
var line = point.Value.GetContainingLine();
int characterSize;
if (line.Start.Position == point.Value.Position)
{
Debug.Assert(line.LineNumber != 0);
characterSize = line.Snapshot.GetLineFromLineNumber(line.LineNumber - 1).LineBreakLength;
}
else
{