-
Notifications
You must be signed in to change notification settings - Fork 27.9k
/
commonCodeEditor.ts
1231 lines (1033 loc) · 43.5 KB
/
commonCodeEditor.ts
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 Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import { onUnexpectedError } from 'vs/base/common/errors';
import { Event, Emitter } from 'vs/base/common/event';
import { Disposable, IDisposable, dispose } from 'vs/base/common/lifecycle';
import { TPromise } from 'vs/base/common/winjs.base';
import { ServicesAccessor, IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection';
import { IContextKey, IContextKeyServiceTarget, IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { CommonEditorConfiguration } from 'vs/editor/common/config/commonEditorConfig';
import { Cursor, CursorStateChangedEvent } from 'vs/editor/common/controller/cursor';
import { CursorColumns, ICursors, CursorConfiguration } from 'vs/editor/common/controller/cursorCommon';
import { Position, IPosition } from 'vs/editor/common/core/position';
import { Range, IRange } from 'vs/editor/common/core/range';
import { Selection, ISelection } from 'vs/editor/common/core/selection';
import * as editorCommon from 'vs/editor/common/editorCommon';
import { ViewModel } from 'vs/editor/common/viewModel/viewModelImpl';
import { hash } from 'vs/base/common/hash';
import { IModelContentChangedEvent, IModelDecorationsChangedEvent, IModelLanguageChangedEvent, IModelOptionsChangedEvent, IModelLanguageConfigurationChangedEvent } from 'vs/editor/common/model/textModelEvents';
import * as editorOptions from 'vs/editor/common/config/editorOptions';
import { ICursorPositionChangedEvent, ICursorSelectionChangedEvent } from 'vs/editor/common/controller/cursorEvents';
import { EditorContextKeys } from 'vs/editor/common/editorContextKeys';
import { VerticalRevealType } from 'vs/editor/common/view/viewEvents';
import { ModelDecorationOptions } from 'vs/editor/common/model/textModel';
import { IEditorWhitespace } from 'vs/editor/common/viewLayout/whitespaceComputer';
import * as modes from 'vs/editor/common/modes';
import { Schemas } from 'vs/base/common/network';
import { ITextModel, EndOfLinePreference, IIdentifiedSingleEditOperation, IModelDecorationsChangeAccessor, IModelDecoration, IModelDeltaDecoration, IModelDecorationOptions } from 'vs/editor/common/model';
let EDITOR_ID = 0;
export abstract class CommonCodeEditor extends Disposable {
private readonly _onDidDispose: Emitter<void> = this._register(new Emitter<void>());
public readonly onDidDispose: Event<void> = this._onDidDispose.event;
private readonly _onDidChangeModelContent: Emitter<IModelContentChangedEvent> = this._register(new Emitter<IModelContentChangedEvent>());
public readonly onDidChangeModelContent: Event<IModelContentChangedEvent> = this._onDidChangeModelContent.event;
private readonly _onDidChangeModelLanguage: Emitter<IModelLanguageChangedEvent> = this._register(new Emitter<IModelLanguageChangedEvent>());
public readonly onDidChangeModelLanguage: Event<IModelLanguageChangedEvent> = this._onDidChangeModelLanguage.event;
private readonly _onDidChangeModelLanguageConfiguration: Emitter<IModelLanguageConfigurationChangedEvent> = this._register(new Emitter<IModelLanguageConfigurationChangedEvent>());
public readonly onDidChangeModelLanguageConfiguration: Event<IModelLanguageConfigurationChangedEvent> = this._onDidChangeModelLanguageConfiguration.event;
private readonly _onDidChangeModelOptions: Emitter<IModelOptionsChangedEvent> = this._register(new Emitter<IModelOptionsChangedEvent>());
public readonly onDidChangeModelOptions: Event<IModelOptionsChangedEvent> = this._onDidChangeModelOptions.event;
private readonly _onDidChangeModelDecorations: Emitter<IModelDecorationsChangedEvent> = this._register(new Emitter<IModelDecorationsChangedEvent>());
public readonly onDidChangeModelDecorations: Event<IModelDecorationsChangedEvent> = this._onDidChangeModelDecorations.event;
private readonly _onDidChangeConfiguration: Emitter<editorOptions.IConfigurationChangedEvent> = this._register(new Emitter<editorOptions.IConfigurationChangedEvent>());
public readonly onDidChangeConfiguration: Event<editorOptions.IConfigurationChangedEvent> = this._onDidChangeConfiguration.event;
protected readonly _onDidChangeModel: Emitter<editorCommon.IModelChangedEvent> = this._register(new Emitter<editorCommon.IModelChangedEvent>());
public readonly onDidChangeModel: Event<editorCommon.IModelChangedEvent> = this._onDidChangeModel.event;
private readonly _onDidChangeCursorPosition: Emitter<ICursorPositionChangedEvent> = this._register(new Emitter<ICursorPositionChangedEvent>());
public readonly onDidChangeCursorPosition: Event<ICursorPositionChangedEvent> = this._onDidChangeCursorPosition.event;
private readonly _onDidChangeCursorSelection: Emitter<ICursorSelectionChangedEvent> = this._register(new Emitter<ICursorSelectionChangedEvent>());
public readonly onDidChangeCursorSelection: Event<ICursorSelectionChangedEvent> = this._onDidChangeCursorSelection.event;
private readonly _onDidLayoutChange: Emitter<editorOptions.EditorLayoutInfo> = this._register(new Emitter<editorOptions.EditorLayoutInfo>());
public readonly onDidLayoutChange: Event<editorOptions.EditorLayoutInfo> = this._onDidLayoutChange.event;
protected readonly _onDidFocusEditorText: Emitter<void> = this._register(new Emitter<void>());
public readonly onDidFocusEditorText: Event<void> = this._onDidFocusEditorText.event;
protected readonly _onDidBlurEditorText: Emitter<void> = this._register(new Emitter<void>());
public readonly onDidBlurEditorText: Event<void> = this._onDidBlurEditorText.event;
protected readonly _onDidFocusEditor: Emitter<void> = this._register(new Emitter<void>());
public readonly onDidFocusEditor: Event<void> = this._onDidFocusEditor.event;
protected readonly _onDidBlurEditor: Emitter<void> = this._register(new Emitter<void>());
public readonly onDidBlurEditor: Event<void> = this._onDidBlurEditor.event;
private readonly _onWillType: Emitter<string> = this._register(new Emitter<string>());
public readonly onWillType = this._onWillType.event;
private readonly _onDidType: Emitter<string> = this._register(new Emitter<string>());
public readonly onDidType = this._onDidType.event;
private readonly _onDidPaste: Emitter<Range> = this._register(new Emitter<Range>());
public readonly onDidPaste = this._onDidPaste.event;
public readonly isSimpleWidget: boolean;
protected readonly domElement: IContextKeyServiceTarget;
protected readonly id: number;
protected readonly _configuration: CommonEditorConfiguration;
protected _contributions: { [key: string]: editorCommon.IEditorContribution; };
protected _actions: { [key: string]: editorCommon.IEditorAction; };
// --- Members logically associated to a model
protected model: ITextModel;
protected listenersToRemove: IDisposable[];
protected hasView: boolean;
protected viewModel: ViewModel;
protected cursor: Cursor;
protected readonly _instantiationService: IInstantiationService;
protected readonly _contextKeyService: IContextKeyService;
/**
* map from "parent" decoration type to live decoration ids.
*/
private _decorationTypeKeysToIds: { [decorationTypeKey: string]: string[] };
private _decorationTypeSubtypes: { [decorationTypeKey: string]: { [subtype: string]: boolean } };
constructor(
domElement: IContextKeyServiceTarget,
options: editorOptions.IEditorOptions,
isSimpleWidget: boolean,
instantiationService: IInstantiationService,
contextKeyService: IContextKeyService
) {
super();
this.domElement = domElement;
this.id = (++EDITOR_ID);
this._decorationTypeKeysToIds = {};
this._decorationTypeSubtypes = {};
this.isSimpleWidget = isSimpleWidget;
options = options || {};
this._configuration = this._register(this._createConfiguration(options));
this._register(this._configuration.onDidChange((e) => {
this._onDidChangeConfiguration.fire(e);
if (e.layoutInfo) {
this._onDidLayoutChange.fire(this._configuration.editor.layoutInfo);
}
}));
this._contextKeyService = this._register(contextKeyService.createScoped(this.domElement));
this._register(new EditorContextKeysManager(this, this._contextKeyService));
this._register(new EditorModeContext(this, this._contextKeyService));
this._instantiationService = instantiationService.createChild(new ServiceCollection([IContextKeyService, this._contextKeyService]));
this._attachModel(null);
this._contributions = {};
this._actions = {};
}
protected abstract _createConfiguration(options: editorOptions.IEditorOptions): CommonEditorConfiguration;
public getId(): string {
return this.getEditorType() + ':' + this.id;
}
public getEditorType(): string {
return editorCommon.EditorType.ICodeEditor;
}
public dispose(): void {
let keys = Object.keys(this._contributions);
for (let i = 0, len = keys.length; i < len; i++) {
let contributionId = keys[i];
this._contributions[contributionId].dispose();
}
this._contributions = {};
// editor actions don't need to be disposed
this._actions = {};
this._removeDecorationTypes();
this._postDetachModelCleanup(this._detachModel());
this._onDidDispose.fire();
super.dispose();
}
public invokeWithinContext<T>(fn: (accessor: ServicesAccessor) => T): T {
return this._instantiationService.invokeFunction(fn);
}
public updateOptions(newOptions: editorOptions.IEditorOptions): void {
this._configuration.updateOptions(newOptions);
}
public getConfiguration(): editorOptions.InternalEditorOptions {
return this._configuration.editor;
}
public getRawConfiguration(): editorOptions.IEditorOptions {
return this._configuration.getRawOptions();
}
public getValue(options: { preserveBOM: boolean; lineEnding: string; } = null): string {
if (this.model) {
let preserveBOM: boolean = (options && options.preserveBOM) ? true : false;
let eolPreference = EndOfLinePreference.TextDefined;
if (options && options.lineEnding && options.lineEnding === '\n') {
eolPreference = EndOfLinePreference.LF;
} else if (options && options.lineEnding && options.lineEnding === '\r\n') {
eolPreference = EndOfLinePreference.CRLF;
}
return this.model.getValue(eolPreference, preserveBOM);
}
return '';
}
public setValue(newValue: string): void {
if (this.model) {
this.model.setValue(newValue);
}
}
public getModel(): ITextModel {
return this.model;
}
public setModel(model: ITextModel = null): void {
if (this.model === model) {
// Current model is the new model
return;
}
let detachedModel = this._detachModel();
this._attachModel(model);
let e: editorCommon.IModelChangedEvent = {
oldModelUrl: detachedModel ? detachedModel.uri : null,
newModelUrl: model ? model.uri : null
};
this._removeDecorationTypes();
this._onDidChangeModel.fire(e);
this._postDetachModelCleanup(detachedModel);
}
private _removeDecorationTypes(): void {
this._decorationTypeKeysToIds = {};
if (this._decorationTypeSubtypes) {
for (let decorationType in this._decorationTypeSubtypes) {
let subTypes = this._decorationTypeSubtypes[decorationType];
for (let subType in subTypes) {
this._removeDecorationType(decorationType + '-' + subType);
}
}
this._decorationTypeSubtypes = {};
}
}
public getCenteredRangeInViewport(): Range {
if (!this.hasView) {
return null;
}
return this.viewModel.getCenteredRangeInViewport();
}
public getVisibleRanges(): Range[] {
if (!this.hasView) {
return [];
}
return this.viewModel.getVisibleRanges();
}
public getWhitespaces(): IEditorWhitespace[] {
if (!this.hasView) {
return [];
}
return this.viewModel.viewLayout.getWhitespaces();
}
protected _getVerticalOffsetForPosition(modelLineNumber: number, modelColumn: number): number {
let modelPosition = this.model.validatePosition({
lineNumber: modelLineNumber,
column: modelColumn
});
let viewPosition = this.viewModel.coordinatesConverter.convertModelPositionToViewPosition(modelPosition);
return this.viewModel.viewLayout.getVerticalOffsetForLineNumber(viewPosition.lineNumber);
}
public getTopForLineNumber(lineNumber: number): number {
if (!this.hasView) {
return -1;
}
return this._getVerticalOffsetForPosition(lineNumber, 1);
}
public getTopForPosition(lineNumber: number, column: number): number {
if (!this.hasView) {
return -1;
}
return this._getVerticalOffsetForPosition(lineNumber, column);
}
public setHiddenAreas(ranges: IRange[]): void {
if (this.viewModel) {
this.viewModel.setHiddenAreas(ranges.map(r => Range.lift(r)));
}
}
public getVisibleColumnFromPosition(rawPosition: IPosition): number {
if (!this.model) {
return rawPosition.column;
}
let position = this.model.validatePosition(rawPosition);
let tabSize = this.model.getOptions().tabSize;
return CursorColumns.visibleColumnFromColumn(this.model.getLineContent(position.lineNumber), position.column, tabSize) + 1;
}
public getPosition(): Position {
if (!this.cursor) {
return null;
}
return this.cursor.getPosition().clone();
}
public setPosition(position: IPosition): void {
if (!this.cursor) {
return;
}
if (!Position.isIPosition(position)) {
throw new Error('Invalid arguments');
}
this.cursor.setSelections('api', [{
selectionStartLineNumber: position.lineNumber,
selectionStartColumn: position.column,
positionLineNumber: position.lineNumber,
positionColumn: position.column
}]);
}
private _sendRevealRange(modelRange: Range, verticalType: VerticalRevealType, revealHorizontal: boolean, scrollType: editorCommon.ScrollType): void {
if (!this.model || !this.cursor) {
return;
}
if (!Range.isIRange(modelRange)) {
throw new Error('Invalid arguments');
}
const validatedModelRange = this.model.validateRange(modelRange);
const viewRange = this.viewModel.coordinatesConverter.convertModelRangeToViewRange(validatedModelRange);
this.cursor.emitCursorRevealRange(viewRange, verticalType, revealHorizontal, scrollType);
}
public revealLine(lineNumber: number, scrollType: editorCommon.ScrollType = editorCommon.ScrollType.Smooth): void {
this._revealLine(lineNumber, VerticalRevealType.Simple, scrollType);
}
public revealLineInCenter(lineNumber: number, scrollType: editorCommon.ScrollType = editorCommon.ScrollType.Smooth): void {
this._revealLine(lineNumber, VerticalRevealType.Center, scrollType);
}
public revealLineInCenterIfOutsideViewport(lineNumber: number, scrollType: editorCommon.ScrollType = editorCommon.ScrollType.Smooth): void {
this._revealLine(lineNumber, VerticalRevealType.CenterIfOutsideViewport, scrollType);
}
private _revealLine(lineNumber: number, revealType: VerticalRevealType, scrollType: editorCommon.ScrollType): void {
if (typeof lineNumber !== 'number') {
throw new Error('Invalid arguments');
}
this._sendRevealRange(
new Range(lineNumber, 1, lineNumber, 1),
revealType,
false,
scrollType
);
}
public revealPosition(position: IPosition, scrollType: editorCommon.ScrollType = editorCommon.ScrollType.Smooth): void {
this._revealPosition(
position,
VerticalRevealType.Simple,
true,
scrollType
);
}
public revealPositionInCenter(position: IPosition, scrollType: editorCommon.ScrollType = editorCommon.ScrollType.Smooth): void {
this._revealPosition(
position,
VerticalRevealType.Center,
true,
scrollType
);
}
public revealPositionInCenterIfOutsideViewport(position: IPosition, scrollType: editorCommon.ScrollType = editorCommon.ScrollType.Smooth): void {
this._revealPosition(
position,
VerticalRevealType.CenterIfOutsideViewport,
true,
scrollType
);
}
private _revealPosition(position: IPosition, verticalType: VerticalRevealType, revealHorizontal: boolean, scrollType: editorCommon.ScrollType): void {
if (!Position.isIPosition(position)) {
throw new Error('Invalid arguments');
}
this._sendRevealRange(
new Range(position.lineNumber, position.column, position.lineNumber, position.column),
verticalType,
revealHorizontal,
scrollType
);
}
public getSelection(): Selection {
if (!this.cursor) {
return null;
}
return this.cursor.getSelection().clone();
}
public getSelections(): Selection[] {
if (!this.cursor) {
return null;
}
let selections = this.cursor.getSelections();
let result: Selection[] = [];
for (let i = 0, len = selections.length; i < len; i++) {
result[i] = selections[i].clone();
}
return result;
}
public setSelection(range: IRange): void;
public setSelection(editorRange: Range): void;
public setSelection(selection: ISelection): void;
public setSelection(editorSelection: Selection): void;
public setSelection(something: any): void {
let isSelection = Selection.isISelection(something);
let isRange = Range.isIRange(something);
if (!isSelection && !isRange) {
throw new Error('Invalid arguments');
}
if (isSelection) {
this._setSelectionImpl(<ISelection>something);
} else if (isRange) {
// act as if it was an IRange
let selection: ISelection = {
selectionStartLineNumber: something.startLineNumber,
selectionStartColumn: something.startColumn,
positionLineNumber: something.endLineNumber,
positionColumn: something.endColumn
};
this._setSelectionImpl(selection);
}
}
private _setSelectionImpl(sel: ISelection): void {
if (!this.cursor) {
return;
}
let selection = new Selection(sel.selectionStartLineNumber, sel.selectionStartColumn, sel.positionLineNumber, sel.positionColumn);
this.cursor.setSelections('api', [selection]);
}
public revealLines(startLineNumber: number, endLineNumber: number, scrollType: editorCommon.ScrollType = editorCommon.ScrollType.Smooth): void {
this._revealLines(
startLineNumber,
endLineNumber,
VerticalRevealType.Simple,
scrollType
);
}
public revealLinesInCenter(startLineNumber: number, endLineNumber: number, scrollType: editorCommon.ScrollType = editorCommon.ScrollType.Smooth): void {
this._revealLines(
startLineNumber,
endLineNumber,
VerticalRevealType.Center,
scrollType
);
}
public revealLinesInCenterIfOutsideViewport(startLineNumber: number, endLineNumber: number, scrollType: editorCommon.ScrollType = editorCommon.ScrollType.Smooth): void {
this._revealLines(
startLineNumber,
endLineNumber,
VerticalRevealType.CenterIfOutsideViewport,
scrollType
);
}
private _revealLines(startLineNumber: number, endLineNumber: number, verticalType: VerticalRevealType, scrollType: editorCommon.ScrollType): void {
if (typeof startLineNumber !== 'number' || typeof endLineNumber !== 'number') {
throw new Error('Invalid arguments');
}
this._sendRevealRange(
new Range(startLineNumber, 1, endLineNumber, 1),
verticalType,
false,
scrollType
);
}
public revealRange(range: IRange, scrollType: editorCommon.ScrollType = editorCommon.ScrollType.Smooth, revealVerticalInCenter: boolean = false, revealHorizontal: boolean = true): void {
this._revealRange(
range,
revealVerticalInCenter ? VerticalRevealType.Center : VerticalRevealType.Simple,
revealHorizontal,
scrollType
);
}
public revealRangeInCenter(range: IRange, scrollType: editorCommon.ScrollType = editorCommon.ScrollType.Smooth): void {
this._revealRange(
range,
VerticalRevealType.Center,
true,
scrollType
);
}
public revealRangeInCenterIfOutsideViewport(range: IRange, scrollType: editorCommon.ScrollType = editorCommon.ScrollType.Smooth): void {
this._revealRange(
range,
VerticalRevealType.CenterIfOutsideViewport,
true,
scrollType
);
}
public revealRangeAtTop(range: IRange, scrollType: editorCommon.ScrollType = editorCommon.ScrollType.Smooth): void {
this._revealRange(
range,
VerticalRevealType.Top,
true,
scrollType
);
}
private _revealRange(range: IRange, verticalType: VerticalRevealType, revealHorizontal: boolean, scrollType: editorCommon.ScrollType): void {
if (!Range.isIRange(range)) {
throw new Error('Invalid arguments');
}
this._sendRevealRange(
Range.lift(range),
verticalType,
revealHorizontal,
scrollType
);
}
public setSelections(ranges: ISelection[]): void {
if (!this.cursor) {
return;
}
if (!ranges || ranges.length === 0) {
throw new Error('Invalid arguments');
}
for (let i = 0, len = ranges.length; i < len; i++) {
if (!Selection.isISelection(ranges[i])) {
throw new Error('Invalid arguments');
}
}
this.cursor.setSelections('api', ranges);
}
public getScrollWidth(): number {
if (!this.hasView) {
return -1;
}
return this.viewModel.viewLayout.getScrollWidth();
}
public getScrollLeft(): number {
if (!this.hasView) {
return -1;
}
return this.viewModel.viewLayout.getCurrentScrollLeft();
}
public getScrollHeight(): number {
if (!this.hasView) {
return -1;
}
return this.viewModel.viewLayout.getScrollHeight();
}
public getScrollTop(): number {
if (!this.hasView) {
return -1;
}
return this.viewModel.viewLayout.getCurrentScrollTop();
}
public setScrollLeft(newScrollLeft: number): void {
if (!this.hasView) {
return;
}
if (typeof newScrollLeft !== 'number') {
throw new Error('Invalid arguments');
}
this.viewModel.viewLayout.setScrollPositionNow({
scrollLeft: newScrollLeft
});
}
public setScrollTop(newScrollTop: number): void {
if (!this.hasView) {
return;
}
if (typeof newScrollTop !== 'number') {
throw new Error('Invalid arguments');
}
this.viewModel.viewLayout.setScrollPositionNow({
scrollTop: newScrollTop
});
}
public setScrollPosition(position: editorCommon.INewScrollPosition): void {
if (!this.hasView) {
return;
}
this.viewModel.viewLayout.setScrollPositionNow(position);
}
public saveViewState(): editorCommon.ICodeEditorViewState {
if (!this.cursor || !this.hasView) {
return null;
}
const contributionsState: { [key: string]: any } = {};
const keys = Object.keys(this._contributions);
for (let i = 0, len = keys.length; i < len; i++) {
const id = keys[i];
const contribution = this._contributions[id];
if (typeof contribution.saveViewState === 'function') {
contributionsState[id] = contribution.saveViewState();
}
}
const cursorState = this.cursor.saveState();
const viewState = this.viewModel.saveState();
return {
cursorState: cursorState,
viewState: viewState,
contributionsState: contributionsState
};
}
public restoreViewState(s: editorCommon.ICodeEditorViewState): void {
if (!this.cursor || !this.hasView) {
return;
}
if (s && s.cursorState && s.viewState) {
let codeEditorState = <editorCommon.ICodeEditorViewState>s;
let cursorState = <any>codeEditorState.cursorState;
if (Array.isArray(cursorState)) {
this.cursor.restoreState(<editorCommon.ICursorState[]>cursorState);
} else {
// Backwards compatibility
this.cursor.restoreState([<editorCommon.ICursorState>cursorState]);
}
let contributionsState = s.contributionsState || {};
let keys = Object.keys(this._contributions);
for (let i = 0, len = keys.length; i < len; i++) {
let id = keys[i];
let contribution = this._contributions[id];
if (typeof contribution.restoreViewState === 'function') {
contribution.restoreViewState(contributionsState[id]);
}
}
}
}
public onVisible(): void {
}
public onHide(): void {
}
public abstract layout(dimension?: editorCommon.IDimension): void;
public abstract focus(): void;
public abstract isFocused(): boolean;
public abstract hasWidgetFocus(): boolean;
public getContribution<T extends editorCommon.IEditorContribution>(id: string): T {
return <T>(this._contributions[id] || null);
}
public getActions(): editorCommon.IEditorAction[] {
let result: editorCommon.IEditorAction[] = [];
let keys = Object.keys(this._actions);
for (let i = 0, len = keys.length; i < len; i++) {
let id = keys[i];
result.push(this._actions[id]);
}
return result;
}
public getSupportedActions(): editorCommon.IEditorAction[] {
let result = this.getActions();
result = result.filter(action => action.isSupported());
return result;
}
public getAction(id: string): editorCommon.IEditorAction {
return this._actions[id] || null;
}
public trigger(source: string, handlerId: string, payload: any): void {
payload = payload || {};
// Special case for typing
if (handlerId === editorCommon.Handler.Type) {
if (!this.cursor || typeof payload.text !== 'string' || payload.text.length === 0) {
// nothing to do
return;
}
if (source === 'keyboard') {
this._onWillType.fire(payload.text);
}
this.cursor.trigger(source, handlerId, payload);
if (source === 'keyboard') {
this._onDidType.fire(payload.text);
}
return;
}
// Special case for pasting
if (handlerId === editorCommon.Handler.Paste) {
if (!this.cursor || typeof payload.text !== 'string' || payload.text.length === 0) {
// nothing to do
return;
}
const startPosition = this.cursor.getSelection().getStartPosition();
this.cursor.trigger(source, handlerId, payload);
const endPosition = this.cursor.getSelection().getStartPosition();
if (source === 'keyboard') {
this._onDidPaste.fire(
new Range(startPosition.lineNumber, startPosition.column, endPosition.lineNumber, endPosition.column)
);
}
return;
}
const action = this.getAction(handlerId);
if (action) {
TPromise.as(action.run()).then(null, onUnexpectedError);
return;
}
if (!this.cursor) {
return;
}
if (this._triggerEditorCommand(source, handlerId, payload)) {
return;
}
this.cursor.trigger(source, handlerId, payload);
}
protected abstract _triggerEditorCommand(source: string, handlerId: string, payload: any): boolean;
public _getCursors(): ICursors {
return this.cursor;
}
public _getCursorConfiguration(): CursorConfiguration {
return this.cursor.context.config;
}
public pushUndoStop(): boolean {
if (!this.model) {
return false;
}
if (this._configuration.editor.readOnly) {
// read only editor => sorry!
return false;
}
this.model.pushStackElement();
return true;
}
public executeEdits(source: string, edits: IIdentifiedSingleEditOperation[], endCursorState?: Selection[]): boolean {
if (!this.cursor) {
// no view, no cursor
return false;
}
if (this._configuration.editor.readOnly) {
// read only editor => sorry!
return false;
}
this.model.pushEditOperations(this.cursor.getSelections(), edits, () => {
return endCursorState ? endCursorState : this.cursor.getSelections();
});
if (endCursorState) {
this.cursor.setSelections(source, endCursorState);
}
return true;
}
public executeCommand(source: string, command: editorCommon.ICommand): void {
if (!this.cursor) {
return;
}
this.cursor.trigger(source, editorCommon.Handler.ExecuteCommand, command);
}
public executeCommands(source: string, commands: editorCommon.ICommand[]): void {
if (!this.cursor) {
return;
}
this.cursor.trigger(source, editorCommon.Handler.ExecuteCommands, commands);
}
public changeDecorations(callback: (changeAccessor: IModelDecorationsChangeAccessor) => any): any {
if (!this.model) {
// console.warn('Cannot change decorations on editor that is not attached to a model');
// callback will not be called
return null;
}
return this.model.changeDecorations(callback, this.id);
}
public getLineDecorations(lineNumber: number): IModelDecoration[] {
if (!this.model) {
return null;
}
return this.model.getLineDecorations(lineNumber, this.id, this._configuration.editor.readOnly);
}
public deltaDecorations(oldDecorations: string[], newDecorations: IModelDeltaDecoration[]): string[] {
if (!this.model) {
return [];
}
if (oldDecorations.length === 0 && newDecorations.length === 0) {
return oldDecorations;
}
return this.model.deltaDecorations(oldDecorations, newDecorations, this.id);
}
public setDecorations(decorationTypeKey: string, decorationOptions: editorCommon.IDecorationOptions[]): void {
let newDecorationsSubTypes: { [key: string]: boolean } = {};
let oldDecorationsSubTypes = this._decorationTypeSubtypes[decorationTypeKey] || {};
this._decorationTypeSubtypes[decorationTypeKey] = newDecorationsSubTypes;
let newModelDecorations: IModelDeltaDecoration[] = [];
for (let decorationOption of decorationOptions) {
let typeKey = decorationTypeKey;
if (decorationOption.renderOptions) {
// identify custom reder options by a hash code over all keys and values
// For custom render options register a decoration type if necessary
let subType = hash(decorationOption.renderOptions).toString(16);
// The fact that `decorationTypeKey` appears in the typeKey has no influence
// it is just a mechanism to get predictable and unique keys (repeatable for the same options and unique across clients)
typeKey = decorationTypeKey + '-' + subType;
if (!oldDecorationsSubTypes[subType] && !newDecorationsSubTypes[subType]) {
// decoration type did not exist before, register new one
this._registerDecorationType(typeKey, decorationOption.renderOptions, decorationTypeKey);
}
newDecorationsSubTypes[subType] = true;
}
let opts = this._resolveDecorationOptions(typeKey, !!decorationOption.hoverMessage);
if (decorationOption.hoverMessage) {
opts.hoverMessage = decorationOption.hoverMessage;
}
newModelDecorations.push({ range: decorationOption.range, options: opts });
}
// remove decoration sub types that are no longer used, deregister decoration type if necessary
for (let subType in oldDecorationsSubTypes) {
if (!newDecorationsSubTypes[subType]) {
this._removeDecorationType(decorationTypeKey + '-' + subType);
}
}
// update all decorations
let oldDecorationsIds = this._decorationTypeKeysToIds[decorationTypeKey] || [];
this._decorationTypeKeysToIds[decorationTypeKey] = this.deltaDecorations(oldDecorationsIds, newModelDecorations);
}
public setDecorationsFast(decorationTypeKey: string, ranges: IRange[]): void {
// remove decoration sub types that are no longer used, deregister decoration type if necessary
let oldDecorationsSubTypes = this._decorationTypeSubtypes[decorationTypeKey] || {};
for (let subType in oldDecorationsSubTypes) {
this._removeDecorationType(decorationTypeKey + '-' + subType);
}
this._decorationTypeSubtypes[decorationTypeKey] = {};
const opts = ModelDecorationOptions.createDynamic(this._resolveDecorationOptions(decorationTypeKey, false));
let newModelDecorations: IModelDeltaDecoration[] = new Array<IModelDeltaDecoration>(ranges.length);
for (let i = 0, len = ranges.length; i < len; i++) {
newModelDecorations[i] = { range: ranges[i], options: opts };
}
// update all decorations
let oldDecorationsIds = this._decorationTypeKeysToIds[decorationTypeKey] || [];
this._decorationTypeKeysToIds[decorationTypeKey] = this.deltaDecorations(oldDecorationsIds, newModelDecorations);
}
public removeDecorations(decorationTypeKey: string): void {
// remove decorations for type and sub type
let oldDecorationsIds = this._decorationTypeKeysToIds[decorationTypeKey];
if (oldDecorationsIds) {
this.deltaDecorations(oldDecorationsIds, []);
}
if (this._decorationTypeKeysToIds.hasOwnProperty(decorationTypeKey)) {
delete this._decorationTypeKeysToIds[decorationTypeKey];
}
if (this._decorationTypeSubtypes.hasOwnProperty(decorationTypeKey)) {
delete this._decorationTypeSubtypes[decorationTypeKey];
}
}
public getLayoutInfo(): editorOptions.EditorLayoutInfo {
return this._configuration.editor.layoutInfo;
}
protected _attachModel(model: ITextModel): void {
this.model = model ? model : null;
this.listenersToRemove = [];
this.viewModel = null;
this.cursor = null;
if (this.model) {
this.domElement.setAttribute('data-mode-id', this.model.getLanguageIdentifier().language);
this._configuration.setIsDominatedByLongLines(this.model.isDominatedByLongLines());
this._configuration.setMaxLineNumber(this.model.getLineCount());
this.model.onBeforeAttached();
this.viewModel = new ViewModel(this.id, this._configuration, this.model, (callback) => this._scheduleAtNextAnimationFrame(callback));
this.listenersToRemove.push(this.model.onDidChangeDecorations((e) => this._onDidChangeModelDecorations.fire(e)));
this.listenersToRemove.push(this.model.onDidChangeLanguage((e) => {
if (!this.model) {
return;
}
this.domElement.setAttribute('data-mode-id', this.model.getLanguageIdentifier().language);
this._onDidChangeModelLanguage.fire(e);
}));
this.listenersToRemove.push(this.model.onDidChangeLanguageConfiguration((e) => this._onDidChangeModelLanguageConfiguration.fire(e)));
this.listenersToRemove.push(this.model.onDidChangeContent((e) => this._onDidChangeModelContent.fire(e)));
this.listenersToRemove.push(this.model.onDidChangeOptions((e) => this._onDidChangeModelOptions.fire(e)));
// Someone might destroy the model from under the editor, so prevent any exceptions by setting a null model
this.listenersToRemove.push(this.model.onWillDispose(() => this.setModel(null)));
this.cursor = new Cursor(
this._configuration,
this.model,
this.viewModel
);
this._createView();
this.listenersToRemove.push(this.cursor.onDidChange((e: CursorStateChangedEvent) => {
let positions: Position[] = [];
for (let i = 0, len = e.selections.length; i < len; i++) {
positions[i] = e.selections[i].getPosition();
}
const e1: ICursorPositionChangedEvent = {
position: positions[0],
secondaryPositions: positions.slice(1),
reason: e.reason,
source: e.source
};
this._onDidChangeCursorPosition.fire(e1);
const e2: ICursorSelectionChangedEvent = {
selection: e.selections[0],
secondarySelections: e.selections.slice(1),
source: e.source,
reason: e.reason
};
this._onDidChangeCursorSelection.fire(e2);
}));
} else {
this.hasView = false;
}
}