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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import 'vs/editor/browser/services/markerDecorations';
import 'vs/css!./media/editor';
import * as nls from 'vs/nls';
import * as dom from 'vs/base/browser/dom';
import { IKeyboardEvent } from 'vs/base/browser/keyboardEvent';
import { IMouseWheelEvent } from 'vs/base/browser/mouseEvent';
import { Color } from 'vs/base/common/color';
import { onUnexpectedError } from 'vs/base/common/errors';
import { Emitter, EmitterOptions, Event, EventDeliveryQueue } from 'vs/base/common/event';
import { hash } from 'vs/base/common/hash';
import { Disposable, IDisposable, dispose, DisposableStore } from 'vs/base/common/lifecycle';
import { Schemas } from 'vs/base/common/network';
import { EditorConfiguration, IEditorConstructionOptions } from 'vs/editor/browser/config/editorConfiguration';
import * as editorBrowser from 'vs/editor/browser/editorBrowser';
import { EditorExtensionsRegistry, IEditorContributionDescription } from 'vs/editor/browser/editorExtensions';
import { ICodeEditorService } from 'vs/editor/browser/services/codeEditorService';
import { ICommandDelegate } from 'vs/editor/browser/view/viewController';
import { IContentWidgetData, IOverlayWidgetData, View } from 'vs/editor/browser/view';
import { ViewUserInputEvents } from 'vs/editor/browser/view/viewUserInputEvents';
import { ConfigurationChangedEvent, EditorLayoutInfo, IEditorOptions, EditorOption, IComputedEditorOptions, FindComputedEditorOptionValueById, filterValidationDecorations } from 'vs/editor/common/config/editorOptions';
import { CursorsController } from 'vs/editor/common/cursor/cursor';
import { CursorColumns } from 'vs/editor/common/core/cursorColumns';
import { CursorChangeReason, ICursorPositionChangedEvent, ICursorSelectionChangedEvent } from 'vs/editor/common/cursorEvents';
import { IPosition, Position } from 'vs/editor/common/core/position';
import { IRange, Range } from 'vs/editor/common/core/range';
import { ISelection, Selection } from 'vs/editor/common/core/selection';
import { InternalEditorAction } from 'vs/editor/common/editorAction';
import * as editorCommon from 'vs/editor/common/editorCommon';
import { EditorContextKeys } from 'vs/editor/common/editorContextKeys';
import { EndOfLinePreference, IIdentifiedSingleEditOperation, IModelDecoration, IModelDecorationOptions, IModelDecorationsChangeAccessor, IModelDeltaDecoration, ITextModel, ICursorStateComputer } from 'vs/editor/common/model';
import { IWordAtPosition } from 'vs/editor/common/core/wordHelper';
import { ClassName } from 'vs/editor/common/model/intervalTree';
import { ModelDecorationOptions } from 'vs/editor/common/model/textModel';
import { IModelContentChangedEvent, IModelDecorationsChangedEvent, IModelLanguageChangedEvent, IModelLanguageConfigurationChangedEvent, IModelOptionsChangedEvent, IModelTokensChangedEvent } from 'vs/editor/common/textModelEvents';
import { editorUnnecessaryCodeBorder, editorUnnecessaryCodeOpacity } from 'vs/editor/common/core/editorColorRegistry';
import { editorErrorBorder, editorErrorForeground, editorHintBorder, editorHintForeground, editorInfoBorder, editorInfoForeground, editorWarningBorder, editorWarningForeground, editorForeground, editorErrorBackground, editorInfoBackground, editorWarningBackground } from 'vs/platform/theme/common/colorRegistry';
import { VerticalRevealType } from 'vs/editor/common/viewEvents';
import { ViewModel } from 'vs/editor/common/viewModel/viewModelImpl';
import { ICommandService } from 'vs/platform/commands/common/commands';
import { IContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { IInstantiationService, ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';
import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection';
import { INotificationService } from 'vs/platform/notification/common/notification';
import { IThemeService, registerThemingParticipant } from 'vs/platform/theme/common/themeService';
import { IAccessibilityService } from 'vs/platform/accessibility/common/accessibility';
import { withNullAsUndefined } from 'vs/base/common/types';
import { MonospaceLineBreaksComputerFactory } from 'vs/editor/common/viewModel/monospaceLineBreaksComputer';
import { DOMLineBreaksComputerFactory } from 'vs/editor/browser/view/domLineBreaksComputer';
import { WordOperations } from 'vs/editor/common/cursor/cursorWordOperations';
import { IEditorWhitespace, IViewModel } from 'vs/editor/common/viewModel';
import { OutgoingViewModelEventKind } from 'vs/editor/common/viewModelEventDispatcher';
import { ILanguageConfigurationService } from 'vs/editor/common/languages/languageConfigurationRegistry';
import { applyFontInfo } from 'vs/editor/browser/config/domFontInfo';
import { IEditorConfiguration } from 'vs/editor/common/config/editorConfiguration';
import { IDimension } from 'vs/editor/common/core/dimension';
import { ILanguageFeaturesService } from 'vs/editor/common/services/languageFeatures';
let EDITOR_ID = 0;
export interface ICodeEditorWidgetOptions {
/**
* Is this a simple widget (not a real code editor)?
* Defaults to false.
*/
isSimpleWidget?: boolean;
/**
* Contributions to instantiate.
* Defaults to EditorExtensionsRegistry.getEditorContributions().
*/
contributions?: IEditorContributionDescription[];
/**
* Telemetry data associated with this CodeEditorWidget.
* Defaults to null.
*/
telemetryData?: object;
}
class ModelData {
public readonly model: ITextModel;
public readonly viewModel: ViewModel;
public readonly view: View;
public readonly hasRealView: boolean;
public readonly listenersToRemove: IDisposable[];
constructor(model: ITextModel, viewModel: ViewModel, view: View, hasRealView: boolean, listenersToRemove: IDisposable[]) {
this.model = model;
this.viewModel = viewModel;
this.view = view;
this.hasRealView = hasRealView;
this.listenersToRemove = listenersToRemove;
}
public dispose(): void {
dispose(this.listenersToRemove);
this.model.onBeforeDetached();
if (this.hasRealView) {
this.view.dispose();
}
this.viewModel.dispose();
}
}
export class CodeEditorWidget extends Disposable implements editorBrowser.ICodeEditor {
private static readonly dropIntoEditorDecorationOptions = ModelDecorationOptions.register({
description: 'workbench-dnd-target',
className: 'dnd-target'
});
//#region Eventing
private readonly _deliveryQueue = new EventDeliveryQueue();
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>({ deliveryQueue: this._deliveryQueue }));
public readonly onDidChangeModelContent: Event<IModelContentChangedEvent> = this._onDidChangeModelContent.event;
private readonly _onDidChangeModelLanguage: Emitter<IModelLanguageChangedEvent> = this._register(new Emitter<IModelLanguageChangedEvent>({ deliveryQueue: this._deliveryQueue }));
public readonly onDidChangeModelLanguage: Event<IModelLanguageChangedEvent> = this._onDidChangeModelLanguage.event;
private readonly _onDidChangeModelLanguageConfiguration: Emitter<IModelLanguageConfigurationChangedEvent> = this._register(new Emitter<IModelLanguageConfigurationChangedEvent>({ deliveryQueue: this._deliveryQueue }));
public readonly onDidChangeModelLanguageConfiguration: Event<IModelLanguageConfigurationChangedEvent> = this._onDidChangeModelLanguageConfiguration.event;
private readonly _onDidChangeModelOptions: Emitter<IModelOptionsChangedEvent> = this._register(new Emitter<IModelOptionsChangedEvent>({ deliveryQueue: this._deliveryQueue }));
public readonly onDidChangeModelOptions: Event<IModelOptionsChangedEvent> = this._onDidChangeModelOptions.event;
private readonly _onDidChangeModelDecorations: Emitter<IModelDecorationsChangedEvent> = this._register(new Emitter<IModelDecorationsChangedEvent>({ deliveryQueue: this._deliveryQueue }));
public readonly onDidChangeModelDecorations: Event<IModelDecorationsChangedEvent> = this._onDidChangeModelDecorations.event;
private readonly _onDidChangeModelTokens: Emitter<IModelTokensChangedEvent> = this._register(new Emitter<IModelTokensChangedEvent>({ deliveryQueue: this._deliveryQueue }));
public readonly onDidChangeModelTokens: Event<IModelTokensChangedEvent> = this._onDidChangeModelTokens.event;
private readonly _onDidChangeConfiguration: Emitter<ConfigurationChangedEvent> = this._register(new Emitter<ConfigurationChangedEvent>({ deliveryQueue: this._deliveryQueue }));
public readonly onDidChangeConfiguration: Event<ConfigurationChangedEvent> = this._onDidChangeConfiguration.event;
protected readonly _onDidChangeModel: Emitter<editorCommon.IModelChangedEvent> = this._register(new Emitter<editorCommon.IModelChangedEvent>({ deliveryQueue: this._deliveryQueue }));
public readonly onDidChangeModel: Event<editorCommon.IModelChangedEvent> = this._onDidChangeModel.event;
private readonly _onDidChangeCursorPosition: Emitter<ICursorPositionChangedEvent> = this._register(new Emitter<ICursorPositionChangedEvent>({ deliveryQueue: this._deliveryQueue }));
public readonly onDidChangeCursorPosition: Event<ICursorPositionChangedEvent> = this._onDidChangeCursorPosition.event;
private readonly _onDidChangeCursorSelection: Emitter<ICursorSelectionChangedEvent> = this._register(new Emitter<ICursorSelectionChangedEvent>({ deliveryQueue: this._deliveryQueue }));
public readonly onDidChangeCursorSelection: Event<ICursorSelectionChangedEvent> = this._onDidChangeCursorSelection.event;
private readonly _onDidAttemptReadOnlyEdit: Emitter<void> = this._register(new Emitter<void>({ deliveryQueue: this._deliveryQueue }));
public readonly onDidAttemptReadOnlyEdit: Event<void> = this._onDidAttemptReadOnlyEdit.event;
private readonly _onDidLayoutChange: Emitter<EditorLayoutInfo> = this._register(new Emitter<EditorLayoutInfo>({ deliveryQueue: this._deliveryQueue }));
public readonly onDidLayoutChange: Event<EditorLayoutInfo> = this._onDidLayoutChange.event;
private readonly _editorTextFocus: BooleanEventEmitter = this._register(new BooleanEventEmitter({ deliveryQueue: this._deliveryQueue }));
public readonly onDidFocusEditorText: Event<void> = this._editorTextFocus.onDidChangeToTrue;
public readonly onDidBlurEditorText: Event<void> = this._editorTextFocus.onDidChangeToFalse;
private readonly _editorWidgetFocus: BooleanEventEmitter = this._register(new BooleanEventEmitter({ deliveryQueue: this._deliveryQueue }));
public readonly onDidFocusEditorWidget: Event<void> = this._editorWidgetFocus.onDidChangeToTrue;
public readonly onDidBlurEditorWidget: Event<void> = this._editorWidgetFocus.onDidChangeToFalse;
private readonly _onWillType: Emitter<string> = this._register(new Emitter<string>({ deliveryQueue: this._deliveryQueue }));
public readonly onWillType = this._onWillType.event;
private readonly _onDidType: Emitter<string> = this._register(new Emitter<string>({ deliveryQueue: this._deliveryQueue }));
public readonly onDidType = this._onDidType.event;
private readonly _onDidCompositionStart: Emitter<void> = this._register(new Emitter<void>({ deliveryQueue: this._deliveryQueue }));
public readonly onDidCompositionStart = this._onDidCompositionStart.event;
private readonly _onDidCompositionEnd: Emitter<void> = this._register(new Emitter<void>({ deliveryQueue: this._deliveryQueue }));
public readonly onDidCompositionEnd = this._onDidCompositionEnd.event;
private readonly _onDidPaste: Emitter<editorBrowser.IPasteEvent> = this._register(new Emitter<editorBrowser.IPasteEvent>({ deliveryQueue: this._deliveryQueue }));
public readonly onDidPaste = this._onDidPaste.event;
private readonly _onMouseUp: Emitter<editorBrowser.IEditorMouseEvent> = this._register(new Emitter<editorBrowser.IEditorMouseEvent>({ deliveryQueue: this._deliveryQueue }));
public readonly onMouseUp: Event<editorBrowser.IEditorMouseEvent> = this._onMouseUp.event;
private readonly _onMouseDown: Emitter<editorBrowser.IEditorMouseEvent> = this._register(new Emitter<editorBrowser.IEditorMouseEvent>({ deliveryQueue: this._deliveryQueue }));
public readonly onMouseDown: Event<editorBrowser.IEditorMouseEvent> = this._onMouseDown.event;
private readonly _onMouseDrag: Emitter<editorBrowser.IEditorMouseEvent> = this._register(new Emitter<editorBrowser.IEditorMouseEvent>({ deliveryQueue: this._deliveryQueue }));
public readonly onMouseDrag: Event<editorBrowser.IEditorMouseEvent> = this._onMouseDrag.event;
private readonly _onMouseDrop: Emitter<editorBrowser.IPartialEditorMouseEvent> = this._register(new Emitter<editorBrowser.IPartialEditorMouseEvent>({ deliveryQueue: this._deliveryQueue }));
public readonly onMouseDrop: Event<editorBrowser.IPartialEditorMouseEvent> = this._onMouseDrop.event;
private readonly _onMouseDropCanceled: Emitter<void> = this._register(new Emitter<void>({ deliveryQueue: this._deliveryQueue }));
public readonly onMouseDropCanceled: Event<void> = this._onMouseDropCanceled.event;
private readonly _onDropIntoEditor = this._register(new Emitter<{ readonly position: IPosition; readonly event: DragEvent }>({ deliveryQueue: this._deliveryQueue }));
public readonly onDropIntoEditor = this._onDropIntoEditor.event;
private readonly _onContextMenu: Emitter<editorBrowser.IEditorMouseEvent> = this._register(new Emitter<editorBrowser.IEditorMouseEvent>({ deliveryQueue: this._deliveryQueue }));
public readonly onContextMenu: Event<editorBrowser.IEditorMouseEvent> = this._onContextMenu.event;
private readonly _onMouseMove: Emitter<editorBrowser.IEditorMouseEvent> = this._register(new Emitter<editorBrowser.IEditorMouseEvent>({ deliveryQueue: this._deliveryQueue }));
public readonly onMouseMove: Event<editorBrowser.IEditorMouseEvent> = this._onMouseMove.event;
private readonly _onMouseLeave: Emitter<editorBrowser.IPartialEditorMouseEvent> = this._register(new Emitter<editorBrowser.IPartialEditorMouseEvent>({ deliveryQueue: this._deliveryQueue }));
public readonly onMouseLeave: Event<editorBrowser.IPartialEditorMouseEvent> = this._onMouseLeave.event;
private readonly _onMouseWheel: Emitter<IMouseWheelEvent> = this._register(new Emitter<IMouseWheelEvent>({ deliveryQueue: this._deliveryQueue }));
public readonly onMouseWheel: Event<IMouseWheelEvent> = this._onMouseWheel.event;
private readonly _onKeyUp: Emitter<IKeyboardEvent> = this._register(new Emitter<IKeyboardEvent>({ deliveryQueue: this._deliveryQueue }));
public readonly onKeyUp: Event<IKeyboardEvent> = this._onKeyUp.event;
private readonly _onKeyDown: Emitter<IKeyboardEvent> = this._register(new Emitter<IKeyboardEvent>({ deliveryQueue: this._deliveryQueue }));
public readonly onKeyDown: Event<IKeyboardEvent> = this._onKeyDown.event;
private readonly _onDidContentSizeChange: Emitter<editorCommon.IContentSizeChangedEvent> = this._register(new Emitter<editorCommon.IContentSizeChangedEvent>({ deliveryQueue: this._deliveryQueue }));
public readonly onDidContentSizeChange: Event<editorCommon.IContentSizeChangedEvent> = this._onDidContentSizeChange.event;
private readonly _onDidScrollChange: Emitter<editorCommon.IScrollEvent> = this._register(new Emitter<editorCommon.IScrollEvent>({ deliveryQueue: this._deliveryQueue }));
public readonly onDidScrollChange: Event<editorCommon.IScrollEvent> = this._onDidScrollChange.event;
private readonly _onDidChangeViewZones: Emitter<void> = this._register(new Emitter<void>({ deliveryQueue: this._deliveryQueue }));
public readonly onDidChangeViewZones: Event<void> = this._onDidChangeViewZones.event;
private readonly _onDidChangeHiddenAreas: Emitter<void> = this._register(new Emitter<void>({ deliveryQueue: this._deliveryQueue }));
public readonly onDidChangeHiddenAreas: Event<void> = this._onDidChangeHiddenAreas.event;
//#endregion
public get isSimpleWidget(): boolean {
return this._configuration.isSimpleWidget;
}
private readonly _telemetryData?: object;
private readonly _domElement: HTMLElement;
private readonly _overflowWidgetsDomNode: HTMLElement | undefined;
private readonly _id: number;
private readonly _configuration: IEditorConfiguration;
protected _contributions: { [key: string]: editorCommon.IEditorContribution };
protected _actions: { [key: string]: editorCommon.IEditorAction };
// --- Members logically associated to a model
protected _modelData: ModelData | null;
protected readonly _instantiationService: IInstantiationService;
protected readonly _contextKeyService: IContextKeyService;
private readonly _notificationService: INotificationService;
protected readonly _codeEditorService: ICodeEditorService;
private readonly _commandService: ICommandService;
private readonly _themeService: IThemeService;
private readonly _focusTracker: CodeEditorWidgetFocusTracker;
private _contentWidgets: { [key: string]: IContentWidgetData };
private _overlayWidgets: { [key: string]: IOverlayWidgetData };
/**
* map from "parent" decoration type to live decoration ids.
*/
private _decorationTypeKeysToIds: { [decorationTypeKey: string]: string[] };
private _decorationTypeSubtypes: { [decorationTypeKey: string]: { [subtype: string]: boolean } };
private _bannerDomNode: HTMLElement | null = null;
private _dropIntoEditorDecorations: EditorDecorationsCollection = this.createDecorationsCollection();
constructor(
domElement: HTMLElement,
_options: Readonly<IEditorConstructionOptions>,
codeEditorWidgetOptions: ICodeEditorWidgetOptions,
@IInstantiationService instantiationService: IInstantiationService,
@ICodeEditorService codeEditorService: ICodeEditorService,
@ICommandService commandService: ICommandService,
@IContextKeyService contextKeyService: IContextKeyService,
@IThemeService themeService: IThemeService,
@INotificationService notificationService: INotificationService,
@IAccessibilityService accessibilityService: IAccessibilityService,
@ILanguageConfigurationService private readonly languageConfigurationService: ILanguageConfigurationService,
@ILanguageFeaturesService languageFeaturesService: ILanguageFeaturesService,
) {
super();
const options = { ..._options };
this._domElement = domElement;
this._overflowWidgetsDomNode = options.overflowWidgetsDomNode;
delete options.overflowWidgetsDomNode;
this._id = (++EDITOR_ID);
this._decorationTypeKeysToIds = {};
this._decorationTypeSubtypes = {};
this._telemetryData = codeEditorWidgetOptions.telemetryData;
this._configuration = this._register(this._createConfiguration(codeEditorWidgetOptions.isSimpleWidget || false, options, accessibilityService));
this._register(this._configuration.onDidChange((e) => {
this._onDidChangeConfiguration.fire(e);
const options = this._configuration.options;
if (e.hasChanged(EditorOption.layoutInfo)) {
const layoutInfo = options.get(EditorOption.layoutInfo);
this._onDidLayoutChange.fire(layoutInfo);
}
}));
this._contextKeyService = this._register(contextKeyService.createScoped(this._domElement));
this._notificationService = notificationService;
this._codeEditorService = codeEditorService;
this._commandService = commandService;
this._themeService = themeService;
this._register(new EditorContextKeysManager(this, this._contextKeyService));
this._register(new EditorModeContext(this, this._contextKeyService, languageFeaturesService));
this._instantiationService = instantiationService.createChild(new ServiceCollection([IContextKeyService, this._contextKeyService]));
this._modelData = null;
this._contributions = {};
this._actions = {};
this._focusTracker = new CodeEditorWidgetFocusTracker(domElement);
this._register(this._focusTracker.onChange(() => {
this._editorWidgetFocus.setValue(this._focusTracker.hasFocus());
}));
this._contentWidgets = {};
this._overlayWidgets = {};
let contributions: IEditorContributionDescription[];
if (Array.isArray(codeEditorWidgetOptions.contributions)) {
contributions = codeEditorWidgetOptions.contributions;
} else {
contributions = EditorExtensionsRegistry.getEditorContributions();
}
for (const desc of contributions) {
if (this._contributions[desc.id]) {
onUnexpectedError(new Error(`Cannot have two contributions with the same id ${desc.id}`));
continue;
}
try {
const contribution = this._instantiationService.createInstance(desc.ctor, this);
this._contributions[desc.id] = contribution;
} catch (err) {
onUnexpectedError(err);
}
}
EditorExtensionsRegistry.getEditorActions().forEach((action) => {
if (this._actions[action.id]) {
onUnexpectedError(new Error(`Cannot have two actions with the same id ${action.id}`));
return;
}
const internalAction = new InternalEditorAction(
action.id,
action.label,
action.alias,
withNullAsUndefined(action.precondition),
(): Promise<void> => {
return this._instantiationService.invokeFunction((accessor) => {
return Promise.resolve(action.runEditorCommand(accessor, this, null));
});
},
this._contextKeyService
);
this._actions[internalAction.id] = internalAction;
});
this._register(new dom.DragAndDropObserver(this._domElement, {
onDragEnter: () => undefined,
onDragOver: e => {
if (!this._configuration.options.get(EditorOption.dropIntoEditor).enabled) {
return;
}
const target = this.getTargetAtClientPoint(e.clientX, e.clientY);
if (target?.position) {
this.showDropIndicatorAt(target.position);
}
},
onDrop: async e => {
if (!this._configuration.options.get(EditorOption.dropIntoEditor).enabled) {
return;
}
this.removeDropIndicator();
if (!e.dataTransfer) {
return;
}
const target = this.getTargetAtClientPoint(e.clientX, e.clientY);
if (target?.position) {
this._onDropIntoEditor.fire({ position: target.position, event: e });
}
},
onDragLeave: () => {
this.removeDropIndicator();
},
onDragEnd: () => {
this.removeDropIndicator();
},
}));
this._codeEditorService.addCodeEditor(this);
}
protected _createConfiguration(isSimpleWidget: boolean, options: Readonly<IEditorConstructionOptions>, accessibilityService: IAccessibilityService): EditorConfiguration {
return new EditorConfiguration(isSimpleWidget, options, this._domElement, accessibilityService);
}
public getId(): string {
return this.getEditorType() + ':' + this._id;
}
public getEditorType(): string {
return editorCommon.EditorType.ICodeEditor;
}
public override dispose(): void {
this._codeEditorService.removeCodeEditor(this);
this._focusTracker.dispose();
const keys = Object.keys(this._contributions);
for (let i = 0, len = keys.length; i < len; i++) {
const contributionId = keys[i];
this._contributions[contributionId].dispose();
}
this._contributions = {};
this._actions = {};
this._contentWidgets = {};
this._overlayWidgets = {};
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: Readonly<IEditorOptions> | undefined): void {
this._configuration.updateOptions(newOptions || {});
}
public getOptions(): IComputedEditorOptions {
return this._configuration.options;
}
public getOption<T extends EditorOption>(id: T): FindComputedEditorOptionValueById<T> {
return this._configuration.options.get(id);
}
public getRawOptions(): IEditorOptions {
return this._configuration.getRawOptions();
}
public getOverflowWidgetsDomNode(): HTMLElement | undefined {
return this._overflowWidgetsDomNode;
}
public getConfiguredWordAtPosition(position: Position): IWordAtPosition | null {
if (!this._modelData) {
return null;
}
return WordOperations.getWordAtPosition(this._modelData.model, this._configuration.options.get(EditorOption.wordSeparators), position);
}
public getValue(options: { preserveBOM: boolean; lineEnding: string } | null = null): string {
if (!this._modelData) {
return '';
}
const 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._modelData.model.getValue(eolPreference, preserveBOM);
}
public setValue(newValue: string): void {
if (!this._modelData) {
return;
}
this._modelData.model.setValue(newValue);
}
public getModel(): ITextModel | null {
if (!this._modelData) {
return null;
}
return this._modelData.model;
}
public setModel(_model: ITextModel | editorCommon.IDiffEditorModel | null = null): void {
const model = <ITextModel | null>_model;
if (this._modelData === null && model === null) {
// Current model is the new model
return;
}
if (this._modelData && this._modelData.model === model) {
// Current model is the new model
return;
}
const hasTextFocus = this.hasTextFocus();
const detachedModel = this._detachModel();
this._attachModel(model);
if (hasTextFocus && this.hasModel()) {
this.focus();
}
const 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 (const decorationType in this._decorationTypeSubtypes) {
const subTypes = this._decorationTypeSubtypes[decorationType];
for (const subType in subTypes) {
this._removeDecorationType(decorationType + '-' + subType);
}
}
this._decorationTypeSubtypes = {};
}
}
public getVisibleRanges(): Range[] {
if (!this._modelData) {
return [];
}
return this._modelData.viewModel.getVisibleRanges();
}
public getVisibleRangesPlusViewportAboveBelow(): Range[] {
if (!this._modelData) {
return [];
}
return this._modelData.viewModel.getVisibleRangesPlusViewportAboveBelow();
}
public getWhitespaces(): IEditorWhitespace[] {
if (!this._modelData) {
return [];
}
return this._modelData.viewModel.viewLayout.getWhitespaces();
}
private static _getVerticalOffsetAfterPosition(modelData: ModelData, modelLineNumber: number, modelColumn: number, includeViewZones: boolean): number {
const modelPosition = modelData.model.validatePosition({
lineNumber: modelLineNumber,
column: modelColumn
});
const viewPosition = modelData.viewModel.coordinatesConverter.convertModelPositionToViewPosition(modelPosition);
return modelData.viewModel.viewLayout.getVerticalOffsetAfterLineNumber(viewPosition.lineNumber, includeViewZones);
}
public getTopForLineNumber(lineNumber: number, includeViewZones: boolean = false): number {
if (!this._modelData) {
return -1;
}
return CodeEditorWidget._getVerticalOffsetForPosition(this._modelData, lineNumber, 1, includeViewZones);
}
public getTopForPosition(lineNumber: number, column: number): number {
if (!this._modelData) {
return -1;
}
return CodeEditorWidget._getVerticalOffsetForPosition(this._modelData, lineNumber, column, false);
}
private static _getVerticalOffsetForPosition(modelData: ModelData, modelLineNumber: number, modelColumn: number, includeViewZones: boolean = false): number {
const modelPosition = modelData.model.validatePosition({
lineNumber: modelLineNumber,
column: modelColumn
});
const viewPosition = modelData.viewModel.coordinatesConverter.convertModelPositionToViewPosition(modelPosition);
return modelData.viewModel.viewLayout.getVerticalOffsetForLineNumber(viewPosition.lineNumber, includeViewZones);
}
public getBottomForLineNumber(lineNumber: number, includeViewZones: boolean = false): number {
if (!this._modelData) {
return -1;
}
return CodeEditorWidget._getVerticalOffsetAfterPosition(this._modelData, lineNumber, 1, includeViewZones);
}
public setHiddenAreas(ranges: IRange[]): void {
this._modelData?.viewModel.setHiddenAreas(ranges.map(r => Range.lift(r)));
}
public getVisibleColumnFromPosition(rawPosition: IPosition): number {
if (!this._modelData) {
return rawPosition.column;
}
const position = this._modelData.model.validatePosition(rawPosition);
const tabSize = this._modelData.model.getOptions().tabSize;
return CursorColumns.visibleColumnFromColumn(this._modelData.model.getLineContent(position.lineNumber), position.column, tabSize) + 1;
}
public getStatusbarColumn(rawPosition: IPosition): number {
if (!this._modelData) {
return rawPosition.column;
}
const position = this._modelData.model.validatePosition(rawPosition);
const tabSize = this._modelData.model.getOptions().tabSize;
return CursorColumns.toStatusbarColumn(this._modelData.model.getLineContent(position.lineNumber), position.column, tabSize);
}
public getPosition(): Position | null {
if (!this._modelData) {
return null;
}
return this._modelData.viewModel.getPosition();
}
public setPosition(position: IPosition, source: string = 'api'): void {
if (!this._modelData) {
return;
}
if (!Position.isIPosition(position)) {
throw new Error('Invalid arguments');
}
this._modelData.viewModel.setSelections(source, [{
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._modelData) {
return;
}
if (!Range.isIRange(modelRange)) {
throw new Error('Invalid arguments');
}
const validatedModelRange = this._modelData.model.validateRange(modelRange);
const viewRange = this._modelData.viewModel.coordinatesConverter.convertModelRangeToViewRange(validatedModelRange);
this._modelData.viewModel.revealRange('api', revealHorizontal, viewRange, verticalType, 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);
}
public revealLineNearTop(lineNumber: number, scrollType: editorCommon.ScrollType = editorCommon.ScrollType.Smooth): void {
this._revealLine(lineNumber, VerticalRevealType.NearTop, 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
);
}
public revealPositionNearTop(position: IPosition, scrollType: editorCommon.ScrollType = editorCommon.ScrollType.Smooth): void {
this._revealPosition(
position,
VerticalRevealType.NearTop,
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 | null {
if (!this._modelData) {
return null;
}
return this._modelData.viewModel.getSelection();
}
public getSelections(): Selection[] | null {
if (!this._modelData) {
return null;
}
return this._modelData.viewModel.getSelections();
}
public setSelection(range: IRange, source?: string): void;
public setSelection(editorRange: Range, source?: string): void;
public setSelection(selection: ISelection, source?: string): void;
public setSelection(editorSelection: Selection, source?: string): void;
public setSelection(something: any, source: string = 'api'): void {
const isSelection = Selection.isISelection(something);
const isRange = Range.isIRange(something);
if (!isSelection && !isRange) {
throw new Error('Invalid arguments');
}
if (isSelection) {
this._setSelectionImpl(<ISelection>something, source);
} else if (isRange) {
// act as if it was an IRange
const selection: ISelection = {
selectionStartLineNumber: something.startLineNumber,
selectionStartColumn: something.startColumn,
positionLineNumber: something.endLineNumber,
positionColumn: something.endColumn
};
this._setSelectionImpl(selection, source);
}
}
private _setSelectionImpl(sel: ISelection, source: string): void {
if (!this._modelData) {
return;
}
const selection = new Selection(sel.selectionStartLineNumber, sel.selectionStartColumn, sel.positionLineNumber, sel.positionColumn);
this._modelData.viewModel.setSelections(source, [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
);
}
public revealLinesNearTop(startLineNumber: number, endLineNumber: number, scrollType: editorCommon.ScrollType = editorCommon.ScrollType.Smooth): void {
this._revealLines(
startLineNumber,
endLineNumber,
VerticalRevealType.NearTop,
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 revealRangeNearTop(range: IRange, scrollType: editorCommon.ScrollType = editorCommon.ScrollType.Smooth): void {
this._revealRange(
range,
VerticalRevealType.NearTop,
true,
scrollType
);
}
public revealRangeNearTopIfOutsideViewport(range: IRange, scrollType: editorCommon.ScrollType = editorCommon.ScrollType.Smooth): void {
this._revealRange(
range,
VerticalRevealType.NearTopIfOutsideViewport,
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: readonly ISelection[], source: string = 'api', reason = CursorChangeReason.NotSet): void {
if (!this._modelData) {
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._modelData.viewModel.setSelections(source, ranges, reason);
}
public getContentWidth(): number {
if (!this._modelData) {
return -1;
}
return this._modelData.viewModel.viewLayout.getContentWidth();
}
public getScrollWidth(): number {
if (!this._modelData) {
return -1;
}
return this._modelData.viewModel.viewLayout.getScrollWidth();
}
public getScrollLeft(): number {
if (!this._modelData) {
return -1;
}
return this._modelData.viewModel.viewLayout.getCurrentScrollLeft();
}
public getContentHeight(): number {
if (!this._modelData) {
return -1;
}
return this._modelData.viewModel.viewLayout.getContentHeight();
}
public getScrollHeight(): number {
if (!this._modelData) {
return -1;
}
return this._modelData.viewModel.viewLayout.getScrollHeight();
}
public getScrollTop(): number {
if (!this._modelData) {
return -1;
}
return this._modelData.viewModel.viewLayout.getCurrentScrollTop();
}
public setScrollLeft(newScrollLeft: number, scrollType: editorCommon.ScrollType = editorCommon.ScrollType.Immediate): void {
if (!this._modelData) {
return;
}
if (typeof newScrollLeft !== 'number') {
throw new Error('Invalid arguments');
}
this._modelData.viewModel.viewLayout.setScrollPosition({
scrollLeft: newScrollLeft
}, scrollType);
}
public setScrollTop(newScrollTop: number, scrollType: editorCommon.ScrollType = editorCommon.ScrollType.Immediate): void {
if (!this._modelData) {
return;
}
if (typeof newScrollTop !== 'number') {
throw new Error('Invalid arguments');
}
this._modelData.viewModel.viewLayout.setScrollPosition({
scrollTop: newScrollTop
}, scrollType);
}
public setScrollPosition(position: editorCommon.INewScrollPosition, scrollType: editorCommon.ScrollType = editorCommon.ScrollType.Immediate): void {
if (!this._modelData) {
return;
}
this._modelData.viewModel.viewLayout.setScrollPosition(position, scrollType);
}
public saveViewState(): editorCommon.ICodeEditorViewState | null {
if (!this._modelData) {
return null;
}
const contributionsState: { [key: string]: any } = {};
const keys = Object.keys(this._contributions);
for (const id of keys) {
const contribution = this._contributions[id];
if (typeof contribution.saveViewState === 'function') {
contributionsState[id] = contribution.saveViewState();
}
}
const cursorState = this._modelData.viewModel.saveCursorState();
const viewState = this._modelData.viewModel.saveState();
return {
cursorState: cursorState,
viewState: viewState,
contributionsState: contributionsState
};
}
public restoreViewState(s: editorCommon.IEditorViewState | null): void {
if (!this._modelData || !this._modelData.hasRealView) {
return;
}
const codeEditorState = s as editorCommon.ICodeEditorViewState | null;
if (codeEditorState && codeEditorState.cursorState && codeEditorState.viewState) {
const cursorState = <any>codeEditorState.cursorState;
if (Array.isArray(cursorState)) {
if (cursorState.length > 0) {
this._modelData.viewModel.restoreCursorState(<editorCommon.ICursorState[]>cursorState);
}
} else {
// Backwards compatibility
this._modelData.viewModel.restoreCursorState([<editorCommon.ICursorState>cursorState]);
}
const contributionsState = codeEditorState.contributionsState || {};
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.restoreViewState === 'function') {
contribution.restoreViewState(contributionsState[id]);
}
}
const reducedState = this._modelData.viewModel.reduceRestoreState(codeEditorState.viewState);
this._modelData.view.restoreState(reducedState);
}
}
public onVisible(): void {
this._modelData?.view.refreshFocusState();
}
public onHide(): void {
this._modelData?.view.refreshFocusState();
this._focusTracker.refreshState();
}
public getContribution<T extends editorCommon.IEditorContribution>(id: string): T | null {
return <T>(this._contributions[id] || null);
}
public getActions(): editorCommon.IEditorAction[] {
const result: editorCommon.IEditorAction[] = [];
const keys = Object.keys(this._actions);
for (let i = 0, len = keys.length; i < len; i++) {
const 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 | null | undefined, handlerId: string, payload: any): void {
payload = payload || {};
switch (handlerId) {
case editorCommon.Handler.CompositionStart:
this._startComposition();
return;
case editorCommon.Handler.CompositionEnd:
this._endComposition(source);
return;
case editorCommon.Handler.Type: {
const args = <Partial<editorCommon.TypePayload>>payload;
this._type(source, args.text || '');
return;
}
case editorCommon.Handler.ReplacePreviousChar: {
const args = <Partial<editorCommon.ReplacePreviousCharPayload>>payload;
this._compositionType(source, args.text || '', args.replaceCharCnt || 0, 0, 0);
return;
}
case editorCommon.Handler.CompositionType: {
const args = <Partial<editorCommon.CompositionTypePayload>>payload;
this._compositionType(source, args.text || '', args.replacePrevCharCnt || 0, args.replaceNextCharCnt || 0, args.positionDelta || 0);
return;
}
case editorCommon.Handler.Paste: {
const args = <Partial<editorCommon.PastePayload>>payload;
this._paste(source, args.text || '', args.pasteOnNewLine || false, args.multicursorText || null, args.mode || null);
return;
}
case editorCommon.Handler.Cut:
this._cut(source);
return;
}
const action = this.getAction(handlerId);
if (action) {
Promise.resolve(action.run()).then(undefined, onUnexpectedError);
return;
}
if (!this._modelData) {
return;
}
if (this._triggerEditorCommand(source, handlerId, payload)) {
return;
}
this._triggerCommand(handlerId, payload);
}
protected _triggerCommand(handlerId: string, payload: any): void {
this._commandService.executeCommand(handlerId, payload);
}
private _startComposition(): void {
if (!this._modelData) {
return;
}
this._modelData.viewModel.startComposition();
this._onDidCompositionStart.fire();
}
private _endComposition(source: string | null | undefined): void {
if (!this._modelData) {
return;
}
this._modelData.viewModel.endComposition(source);
this._onDidCompositionEnd.fire();
}
private _type(source: string | null | undefined, text: string): void {
if (!this._modelData || text.length === 0) {
return;
}
if (source === 'keyboard') {
this._onWillType.fire(text);
}
this._modelData.viewModel.type(text, source);
if (source === 'keyboard') {
this._onDidType.fire(text);
}
}
private _compositionType(source: string | null | undefined, text: string, replacePrevCharCnt: number, replaceNextCharCnt: number, positionDelta: number): void {
if (!this._modelData) {
return;
}
this._modelData.viewModel.compositionType(text, replacePrevCharCnt, replaceNextCharCnt, positionDelta, source);
}
private _paste(source: string | null | undefined, text: string, pasteOnNewLine: boolean, multicursorText: string[] | null, mode: string | null): void {
if (!this._modelData || text.length === 0) {
return;
}
const viewModel = this._modelData.viewModel;
const startPosition = viewModel.getSelection().getStartPosition();
viewModel.paste(text, pasteOnNewLine, multicursorText, source);
const endPosition = viewModel.getSelection().getStartPosition();
if (source === 'keyboard') {
this._onDidPaste.fire({
range: new Range(startPosition.lineNumber, startPosition.column, endPosition.lineNumber, endPosition.column),
languageId: mode
});
}
}
private _cut(source: string | null | undefined): void {
if (!this._modelData) {
return;
}
this._modelData.viewModel.cut(source);
}
private _triggerEditorCommand(source: string | null | undefined, handlerId: string, payload: any): boolean {
const command = EditorExtensionsRegistry.getEditorCommand(handlerId);
if (command) {
payload = payload || {};
payload.source = source;
this._instantiationService.invokeFunction((accessor) => {
Promise.resolve(command.runEditorCommand(accessor, this, payload)).then(undefined, onUnexpectedError);
});
return true;
}
return false;
}
public _getViewModel(): IViewModel | null {
if (!this._modelData) {
return null;
}
return this._modelData.viewModel;
}
public pushUndoStop(): boolean {
if (!this._modelData) {
return false;
}
if (this._configuration.options.get(EditorOption.readOnly)) {
// read only editor => sorry!
return false;
}
this._modelData.model.pushStackElement();
return true;
}
public popUndoStop(): boolean {
if (!this._modelData) {
return false;
}
if (this._configuration.options.get(EditorOption.readOnly)) {
// read only editor => sorry!
return false;
}
this._modelData.model.popStackElement();
return true;
}
public executeEdits(source: string | null | undefined, edits: IIdentifiedSingleEditOperation[], endCursorState?: ICursorStateComputer | Selection[]): boolean {
if (!this._modelData) {
return false;
}
if (this._configuration.options.get(EditorOption.readOnly)) {
// read only editor => sorry!
return false;
}
let cursorStateComputer: ICursorStateComputer;
if (!endCursorState) {
cursorStateComputer = () => null;
} else if (Array.isArray(endCursorState)) {
cursorStateComputer = () => endCursorState;
} else {
cursorStateComputer = endCursorState;
}
this._modelData.viewModel.executeEdits(source, edits, cursorStateComputer);
return true;
}
public executeCommand(source: string | null | undefined, command: editorCommon.ICommand): void {
if (!this._modelData) {
return;
}
this._modelData.viewModel.executeCommand(command, source);
}
public executeCommands(source: string | null | undefined, commands: editorCommon.ICommand[]): void {
if (!this._modelData) {
return;
}
this._modelData.viewModel.executeCommands(commands, source);
}
public createDecorationsCollection(decorations?: IModelDeltaDecoration[]): EditorDecorationsCollection {
return new EditorDecorationsCollection(this, decorations);
}
public changeDecorations(callback: (changeAccessor: IModelDecorationsChangeAccessor) => any): any {
if (!this._modelData) {
// callback will not be called
return null;
}
return this._modelData.model.changeDecorations(callback, this._id);
}
public getLineDecorations(lineNumber: number): IModelDecoration[] | null {
if (!this._modelData) {
return null;
}
return this._modelData.model.getLineDecorations(lineNumber, this._id, filterValidationDecorations(this._configuration.options));
}
public getDecorationsInRange(range: Range): IModelDecoration[] | null {
if (!this._modelData) {
return null;
}
return this._modelData.model.getDecorationsInRange(range, this._id, filterValidationDecorations(this._configuration.options));
}
/**
* @deprecated
*/
public deltaDecorations(oldDecorations: string[], newDecorations: IModelDeltaDecoration[]): string[] {
if (!this._modelData) {
return [];
}
if (oldDecorations.length === 0 && newDecorations.length === 0) {
return oldDecorations;
}
return this._modelData.model.deltaDecorations(oldDecorations, newDecorations, this._id);
}
public removeDecorations(decorationIds: string[]): void {
if (!this._modelData || decorationIds.length === 0) {
return;
}
this._modelData.model.changeDecorations((changeAccessor) => {
changeAccessor.deltaDecorations(decorationIds, []);
});
}
public setDecorationsByType(description: string, decorationTypeKey: string, decorationOptions: editorCommon.IDecorationOptions[]): void {
const newDecorationsSubTypes: { [key: string]: boolean } = {};
const oldDecorationsSubTypes = this._decorationTypeSubtypes[decorationTypeKey] || {};
this._decorationTypeSubtypes[decorationTypeKey] = newDecorationsSubTypes;
const newModelDecorations: IModelDeltaDecoration[] = [];
for (const 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
const 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(description, typeKey, decorationOption.renderOptions, decorationTypeKey);
}
newDecorationsSubTypes[subType] = true;
}
const 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 (const subType in oldDecorationsSubTypes) {
if (!newDecorationsSubTypes[subType]) {
this._removeDecorationType(decorationTypeKey + '-' + subType);
}
}
// update all decorations
const oldDecorationsIds = this._decorationTypeKeysToIds[decorationTypeKey] || [];
this._decorationTypeKeysToIds[decorationTypeKey] = this.deltaDecorations(oldDecorationsIds, newModelDecorations);
}
public setDecorationsByTypeFast(decorationTypeKey: string, ranges: IRange[]): void {
// remove decoration sub types that are no longer used, deregister decoration type if necessary
const oldDecorationsSubTypes = this._decorationTypeSubtypes[decorationTypeKey] || {};
for (const subType in oldDecorationsSubTypes) {
this._removeDecorationType(decorationTypeKey + '-' + subType);
}
this._decorationTypeSubtypes[decorationTypeKey] = {};
const opts = ModelDecorationOptions.createDynamic(this._resolveDecorationOptions(decorationTypeKey, false));
const 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
const oldDecorationsIds = this._decorationTypeKeysToIds[decorationTypeKey] || [];
this._decorationTypeKeysToIds[decorationTypeKey] = this.deltaDecorations(oldDecorationsIds, newModelDecorations);
}
public removeDecorationsByType(decorationTypeKey: string): void {
// remove decorations for type and sub type
const 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(): EditorLayoutInfo {
const options = this._configuration.options;
const layoutInfo = options.get(EditorOption.layoutInfo);
return layoutInfo;
}
public createOverviewRuler(cssClassName: string): editorBrowser.IOverviewRuler | null {
if (!this._modelData || !this._modelData.hasRealView) {
return null;
}
return this._modelData.view.createOverviewRuler(cssClassName);
}
public getContainerDomNode(): HTMLElement {
return this._domElement;
}
public getDomNode(): HTMLElement | null {
if (!this._modelData || !this._modelData.hasRealView) {
return null;
}
return this._modelData.view.domNode.domNode;
}
public delegateVerticalScrollbarPointerDown(browserEvent: PointerEvent): void {
if (!this._modelData || !this._modelData.hasRealView) {
return;
}
this._modelData.view.delegateVerticalScrollbarPointerDown(browserEvent);
}
public layout(dimension?: IDimension): void {
this._configuration.observeContainer(dimension);
this.render();
}
public focus(): void {
if (!this._modelData || !this._modelData.hasRealView) {
return;
}
this._modelData.view.focus();
}
public hasTextFocus(): boolean {
if (!this._modelData || !this._modelData.hasRealView) {
return false;
}
return this._modelData.view.isFocused();
}
public hasWidgetFocus(): boolean {
return this._focusTracker && this._focusTracker.hasFocus();
}
public addContentWidget(widget: editorBrowser.IContentWidget): void {
const widgetData: IContentWidgetData = {
widget: widget,
position: widget.getPosition()
};
if (this._contentWidgets.hasOwnProperty(widget.getId())) {
console.warn('Overwriting a content widget with the same id.');
}
this._contentWidgets[widget.getId()] = widgetData;
if (this._modelData && this._modelData.hasRealView) {
this._modelData.view.addContentWidget(widgetData);
}
}
public layoutContentWidget(widget: editorBrowser.IContentWidget): void {
const widgetId = widget.getId();
if (this._contentWidgets.hasOwnProperty(widgetId)) {
const widgetData = this._contentWidgets[widgetId];
widgetData.position = widget.getPosition();
if (this._modelData && this._modelData.hasRealView) {
this._modelData.view.layoutContentWidget(widgetData);
}
}
}
public removeContentWidget(widget: editorBrowser.IContentWidget): void {
const widgetId = widget.getId();
if (this._contentWidgets.hasOwnProperty(widgetId)) {
const widgetData = this._contentWidgets[widgetId];
delete this._contentWidgets[widgetId];
if (this._modelData && this._modelData.hasRealView) {
this._modelData.view.removeContentWidget(widgetData);
}
}
}
public addOverlayWidget(widget: editorBrowser.IOverlayWidget): void {
const widgetData: IOverlayWidgetData = {
widget: widget,
position: widget.getPosition()
};
if (this._overlayWidgets.hasOwnProperty(widget.getId())) {
console.warn('Overwriting an overlay widget with the same id.');
}
this._overlayWidgets[widget.getId()] = widgetData;
if (this._modelData && this._modelData.hasRealView) {
this._modelData.view.addOverlayWidget(widgetData);
}
}
public layoutOverlayWidget(widget: editorBrowser.IOverlayWidget): void {
const widgetId = widget.getId();
if (this._overlayWidgets.hasOwnProperty(widgetId)) {
const widgetData = this._overlayWidgets[widgetId];
widgetData.position = widget.getPosition();
if (this._modelData && this._modelData.hasRealView) {
this._modelData.view.layoutOverlayWidget(widgetData);
}
}
}
public removeOverlayWidget(widget: editorBrowser.IOverlayWidget): void {
const widgetId = widget.getId();
if (this._overlayWidgets.hasOwnProperty(widgetId)) {
const widgetData = this._overlayWidgets[widgetId];
delete this._overlayWidgets[widgetId];
if (this._modelData && this._modelData.hasRealView) {
this._modelData.view.removeOverlayWidget(widgetData);
}
}
}
public changeViewZones(callback: (accessor: editorBrowser.IViewZoneChangeAccessor) => void): void {
if (!this._modelData || !this._modelData.hasRealView) {
return;
}
this._modelData.view.change(callback);
}
public getTargetAtClientPoint(clientX: number, clientY: number): editorBrowser.IMouseTarget | null {
if (!this._modelData || !this._modelData.hasRealView) {
return null;
}
return this._modelData.view.getTargetAtClientPoint(clientX, clientY);
}
public getScrolledVisiblePosition(rawPosition: IPosition): { top: number; left: number; height: number } | null {
if (!this._modelData || !this._modelData.hasRealView) {
return null;
}
const position = this._modelData.model.validatePosition(rawPosition);
const options = this._configuration.options;
const layoutInfo = options.get(EditorOption.layoutInfo);
const top = CodeEditorWidget._getVerticalOffsetForPosition(this._modelData, position.lineNumber, position.column) - this.getScrollTop();
const left = this._modelData.view.getOffsetForColumn(position.lineNumber, position.column) + layoutInfo.glyphMarginWidth + layoutInfo.lineNumbersWidth + layoutInfo.decorationsWidth - this.getScrollLeft();
return {
top: top,
left: left,
height: options.get(EditorOption.lineHeight)
};
}
public getOffsetForColumn(lineNumber: number, column: number): number {
if (!this._modelData || !this._modelData.hasRealView) {
return -1;
}
return this._modelData.view.getOffsetForColumn(lineNumber, column);
}
public render(forceRedraw: boolean = false): void {
if (!this._modelData || !this._modelData.hasRealView) {
return;
}
this._modelData.view.render(true, forceRedraw);
}
public setAriaOptions(options: editorBrowser.IEditorAriaOptions): void {
if (!this._modelData || !this._modelData.hasRealView) {
return;
}
this._modelData.view.setAriaOptions(options);
}
public applyFontInfo(target: HTMLElement): void {
applyFontInfo(target, this._configuration.options.get(EditorOption.fontInfo));
}
public setBanner(domNode: HTMLElement | null, domNodeHeight: number): void {
if (this._bannerDomNode && this._domElement.contains(this._bannerDomNode)) {
this._domElement.removeChild(this._bannerDomNode);
}
this._bannerDomNode = domNode;
this._configuration.setReservedHeight(domNode ? domNodeHeight : 0);
if (this._bannerDomNode) {
this._domElement.prepend(this._bannerDomNode);
}
}
protected _attachModel(model: ITextModel | null): void {
if (!model) {
this._modelData = null;
return;
}
const listenersToRemove: IDisposable[] = [];
this._domElement.setAttribute('data-mode-id', model.getLanguageId());
this._configuration.setIsDominatedByLongLines(model.isDominatedByLongLines());
this._configuration.setModelLineCount(model.getLineCount());
model.onBeforeAttached();
const viewModel = new ViewModel(
this._id,
this._configuration,
model,
DOMLineBreaksComputerFactory.create(),
MonospaceLineBreaksComputerFactory.create(this._configuration.options),
(callback) => dom.scheduleAtNextAnimationFrame(callback),
this.languageConfigurationService,
this._themeService
);
// Someone might destroy the model from under the editor, so prevent any exceptions by setting a null model
listenersToRemove.push(model.onWillDispose(() => this.setModel(null)));
listenersToRemove.push(viewModel.onEvent((e) => {
switch (e.kind) {
case OutgoingViewModelEventKind.ContentSizeChanged:
this._onDidContentSizeChange.fire(e);
break;
case OutgoingViewModelEventKind.FocusChanged:
this._editorTextFocus.setValue(e.hasFocus);
break;
case OutgoingViewModelEventKind.ScrollChanged:
this._onDidScrollChange.fire(e);
break;
case OutgoingViewModelEventKind.ViewZonesChanged:
this._onDidChangeViewZones.fire();
break;
case OutgoingViewModelEventKind.HiddenAreasChanged:
this._onDidChangeHiddenAreas.fire();
break;
case OutgoingViewModelEventKind.ReadOnlyEditAttempt:
this._onDidAttemptReadOnlyEdit.fire();
break;
case OutgoingViewModelEventKind.CursorStateChanged: {
if (e.reachedMaxCursorCount) {
this._notificationService.warn(nls.localize('cursors.maximum', "The number of cursors has been limited to {0}.", CursorsController.MAX_CURSOR_COUNT));
}
const 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),
modelVersionId: e.modelVersionId,
oldSelections: e.oldSelections,
oldModelVersionId: e.oldModelVersionId,
source: e.source,
reason: e.reason
};
this._onDidChangeCursorSelection.fire(e2);
break;
}
case OutgoingViewModelEventKind.ModelDecorationsChanged:
this._onDidChangeModelDecorations.fire(e.event);
break;
case OutgoingViewModelEventKind.ModelLanguageChanged:
this._domElement.setAttribute('data-mode-id', model.getLanguageId());
this._onDidChangeModelLanguage.fire(e.event);
break;
case OutgoingViewModelEventKind.ModelLanguageConfigurationChanged:
this._onDidChangeModelLanguageConfiguration.fire(e.event);
break;
case OutgoingViewModelEventKind.ModelContentChanged:
this._onDidChangeModelContent.fire(e.event);
break;
case OutgoingViewModelEventKind.ModelOptionsChanged:
this._onDidChangeModelOptions.fire(e.event);
break;
case OutgoingViewModelEventKind.ModelTokensChanged:
this._onDidChangeModelTokens.fire(e.event);
break;
}
}));
const [view, hasRealView] = this._createView(viewModel);
if (hasRealView) {
this._domElement.appendChild(view.domNode.domNode);
let keys = Object.keys(this._contentWidgets);
for (let i = 0, len = keys.length; i < len; i++) {
const widgetId = keys[i];
view.addContentWidget(this._contentWidgets[widgetId]);
}
keys = Object.keys(this._overlayWidgets);
for (let i = 0, len = keys.length; i < len; i++) {
const widgetId = keys[i];
view.addOverlayWidget(this._overlayWidgets[widgetId]);
}
view.render(false, true);
view.domNode.domNode.setAttribute('data-uri', model.uri.toString());
}
this._modelData = new ModelData(model, viewModel, view, hasRealView, listenersToRemove);
}
protected _createView(viewModel: ViewModel): [View, boolean] {
let commandDelegate: ICommandDelegate;
if (this.isSimpleWidget) {
commandDelegate = {
paste: (text: string, pasteOnNewLine: boolean, multicursorText: string[] | null, mode: string | null) => {
this._paste('keyboard', text, pasteOnNewLine, multicursorText, mode);
},
type: (text: string) => {
this._type('keyboard', text);
},
compositionType: (text: string, replacePrevCharCnt: number, replaceNextCharCnt: number, positionDelta: number) => {
this._compositionType('keyboard', text, replacePrevCharCnt, replaceNextCharCnt, positionDelta);
},
startComposition: () => {
this._startComposition();
},
endComposition: () => {
this._endComposition('keyboard');
},
cut: () => {
this._cut('keyboard');
}
};
} else {
commandDelegate = {
paste: (text: string, pasteOnNewLine: boolean, multicursorText: string[] | null, mode: string | null) => {
const payload: editorCommon.PastePayload = { text, pasteOnNewLine, multicursorText, mode };
this._commandService.executeCommand(editorCommon.Handler.Paste, payload);
},
type: (text: string) => {
const payload: editorCommon.TypePayload = { text };
this._commandService.executeCommand(editorCommon.Handler.Type, payload);
},
compositionType: (text: string, replacePrevCharCnt: number, replaceNextCharCnt: number, positionDelta: number) => {
// Try if possible to go through the existing `replacePreviousChar` command
if (replaceNextCharCnt || positionDelta) {
// must be handled through the new command
const payload: editorCommon.CompositionTypePayload = { text, replacePrevCharCnt, replaceNextCharCnt, positionDelta };
this._commandService.executeCommand(editorCommon.Handler.CompositionType, payload);
} else {
const payload: editorCommon.ReplacePreviousCharPayload = { text, replaceCharCnt: replacePrevCharCnt };
this._commandService.executeCommand(editorCommon.Handler.ReplacePreviousChar, payload);
}
},
startComposition: () => {
this._commandService.executeCommand(editorCommon.Handler.CompositionStart, {});
},
endComposition: () => {
this._commandService.executeCommand(editorCommon.Handler.CompositionEnd, {});
},
cut: () => {
this._commandService.executeCommand(editorCommon.Handler.Cut, {});
}
};
}
const viewUserInputEvents = new ViewUserInputEvents(viewModel.coordinatesConverter);
viewUserInputEvents.onKeyDown = (e) => this._onKeyDown.fire(e);
viewUserInputEvents.onKeyUp = (e) => this._onKeyUp.fire(e);
viewUserInputEvents.onContextMenu = (e) => this._onContextMenu.fire(e);
viewUserInputEvents.onMouseMove = (e) => this._onMouseMove.fire(e);
viewUserInputEvents.onMouseLeave = (e) => this._onMouseLeave.fire(e);
viewUserInputEvents.onMouseDown = (e) => this._onMouseDown.fire(e);
viewUserInputEvents.onMouseUp = (e) => this._onMouseUp.fire(e);
viewUserInputEvents.onMouseDrag = (e) => this._onMouseDrag.fire(e);
viewUserInputEvents.onMouseDrop = (e) => this._onMouseDrop.fire(e);
viewUserInputEvents.onMouseDropCanceled = (e) => this._onMouseDropCanceled.fire(e);
viewUserInputEvents.onMouseWheel = (e) => this._onMouseWheel.fire(e);
const view = new View(
commandDelegate,
this._configuration,
this._themeService.getColorTheme(),
viewModel,
viewUserInputEvents,
this._overflowWidgetsDomNode
);
return [view, true];
}
protected _postDetachModelCleanup(detachedModel: ITextModel | null): void {
detachedModel?.removeAllDecorationsWithOwnerId(this._id);
}
private _detachModel(): ITextModel | null {
if (!this._modelData) {
return null;
}
const model = this._modelData.model;
const removeDomNode = this._modelData.hasRealView ? this._modelData.view.domNode.domNode : null;
this._modelData.dispose();
this._modelData = null;
this._domElement.removeAttribute('data-mode-id');
if (removeDomNode && this._domElement.contains(removeDomNode)) {
this._domElement.removeChild(removeDomNode);
}
if (this._bannerDomNode && this._domElement.contains(this._bannerDomNode)) {
this._domElement.removeChild(this._bannerDomNode);
}
return model;
}
private _registerDecorationType(description: string, key: string, options: editorCommon.IDecorationRenderOptions, parentTypeKey?: string): void {
this._codeEditorService.registerDecorationType(description, key, options, parentTypeKey, this);
}
private _removeDecorationType(key: string): void {
this._codeEditorService.removeDecorationType(key);
}
private _resolveDecorationOptions(typeKey: string, writable: boolean): IModelDecorationOptions {
return this._codeEditorService.resolveDecorationOptions(typeKey, writable);
}
public getTelemetryData(): { [key: string]: any } | undefined {
return this._telemetryData;
}
public hasModel(): this is editorBrowser.IActiveCodeEditor {
return (this._modelData !== null);
}
private showDropIndicatorAt(position: Position): void {
const newDecorations: IModelDeltaDecoration[] = [{
range: new Range(position.lineNumber, position.column, position.lineNumber, position.column),
options: CodeEditorWidget.dropIntoEditorDecorationOptions
}];
this._dropIntoEditorDecorations.set(newDecorations);
this.revealPosition(position, editorCommon.ScrollType.Immediate);
}
private removeDropIndicator(): void {
this._dropIntoEditorDecorations.clear();
}
}
const enum BooleanEventValue {
NotSet,
False,
True
}
export class BooleanEventEmitter extends Disposable {
private readonly _onDidChangeToTrue: Emitter<void> = this._register(new Emitter<void>(this._emitterOptions));
public readonly onDidChangeToTrue: Event<void> = this._onDidChangeToTrue.event;
private readonly _onDidChangeToFalse: Emitter<void> = this._register(new Emitter<void>(this._emitterOptions));
public readonly onDidChangeToFalse: Event<void> = this._onDidChangeToFalse.event;
private _value: BooleanEventValue;
constructor(
private readonly _emitterOptions: EmitterOptions
) {
super();
this._value = BooleanEventValue.NotSet;
}
public setValue(_value: boolean) {
const value = (_value ? BooleanEventValue.True : BooleanEventValue.False);
if (this._value === value) {
return;
}
this._value = value;
if (this._value === BooleanEventValue.True) {
this._onDidChangeToTrue.fire();
} else if (this._value === BooleanEventValue.False) {
this._onDidChangeToFalse.fire();
}
}
}
class EditorContextKeysManager extends Disposable {
private readonly _editor: CodeEditorWidget;
private readonly _editorSimpleInput: IContextKey<boolean>;
private readonly _editorFocus: IContextKey<boolean>;
private readonly _textInputFocus: IContextKey<boolean>;
private readonly _editorTextFocus: IContextKey<boolean>;
private readonly _editorTabMovesFocus: IContextKey<boolean>;
private readonly _editorReadonly: IContextKey<boolean>;
private readonly _inDiffEditor: IContextKey<boolean>;
private readonly _editorColumnSelection: IContextKey<boolean>;
private readonly _hasMultipleSelections: IContextKey<boolean>;
private readonly _hasNonEmptySelection: IContextKey<boolean>;
private readonly _canUndo: IContextKey<boolean>;
private readonly _canRedo: IContextKey<boolean>;
constructor(
editor: CodeEditorWidget,
contextKeyService: IContextKeyService
) {
super();
this._editor = editor;
contextKeyService.createKey('editorId', editor.getId());
this._editorSimpleInput = EditorContextKeys.editorSimpleInput.bindTo(contextKeyService);
this._editorFocus = EditorContextKeys.focus.bindTo(contextKeyService);
this._textInputFocus = EditorContextKeys.textInputFocus.bindTo(contextKeyService);
this._editorTextFocus = EditorContextKeys.editorTextFocus.bindTo(contextKeyService);
this._editorTabMovesFocus = EditorContextKeys.tabMovesFocus.bindTo(contextKeyService);
this._editorReadonly = EditorContextKeys.readOnly.bindTo(contextKeyService);
this._inDiffEditor = EditorContextKeys.inDiffEditor.bindTo(contextKeyService);
this._editorColumnSelection = EditorContextKeys.columnSelection.bindTo(contextKeyService);
this._hasMultipleSelections = EditorContextKeys.hasMultipleSelections.bindTo(contextKeyService);
this._hasNonEmptySelection = EditorContextKeys.hasNonEmptySelection.bindTo(contextKeyService);
this._canUndo = EditorContextKeys.canUndo.bindTo(contextKeyService);
this._canRedo = EditorContextKeys.canRedo.bindTo(contextKeyService);
this._register(this._editor.onDidChangeConfiguration(() => this._updateFromConfig()));
this._register(this._editor.onDidChangeCursorSelection(() => this._updateFromSelection()));
this._register(this._editor.onDidFocusEditorWidget(() => this._updateFromFocus()));
this._register(this._editor.onDidBlurEditorWidget(() => this._updateFromFocus()));
this._register(this._editor.onDidFocusEditorText(() => this._updateFromFocus()));
this._register(this._editor.onDidBlurEditorText(() => this._updateFromFocus()));
this._register(this._editor.onDidChangeModel(() => this._updateFromModel()));
this._register(this._editor.onDidChangeConfiguration(() => this._updateFromModel()));
this._updateFromConfig();
this._updateFromSelection();
this._updateFromFocus();
this._updateFromModel();
this._editorSimpleInput.set(this._editor.isSimpleWidget);
}
private _updateFromConfig(): void {
const options = this._editor.getOptions();
this._editorTabMovesFocus.set(options.get(EditorOption.tabFocusMode));
this._editorReadonly.set(options.get(EditorOption.readOnly));
this._inDiffEditor.set(options.get(EditorOption.inDiffEditor));
this._editorColumnSelection.set(options.get(EditorOption.columnSelection));
}
private _updateFromSelection(): void {
const selections = this._editor.getSelections();
if (!selections) {
this._hasMultipleSelections.reset();
this._hasNonEmptySelection.reset();
} else {
this._hasMultipleSelections.set(selections.length > 1);
this._hasNonEmptySelection.set(selections.some(s => !s.isEmpty()));
}
}
private _updateFromFocus(): void {
this._editorFocus.set(this._editor.hasWidgetFocus() && !this._editor.isSimpleWidget);
this._editorTextFocus.set(this._editor.hasTextFocus() && !this._editor.isSimpleWidget);
this._textInputFocus.set(this._editor.hasTextFocus());
}
private _updateFromModel(): void {
const model = this._editor.getModel();
this._canUndo.set(Boolean(model && model.canUndo()));
this._canRedo.set(Boolean(model && model.canRedo()));
}
}
export class EditorModeContext extends Disposable {
private readonly _langId: IContextKey<string>;
private readonly _hasCompletionItemProvider: IContextKey<boolean>;
private readonly _hasCodeActionsProvider: IContextKey<boolean>;
private readonly _hasCodeLensProvider: IContextKey<boolean>;
private readonly _hasDefinitionProvider: IContextKey<boolean>;
private readonly _hasDeclarationProvider: IContextKey<boolean>;
private readonly _hasImplementationProvider: IContextKey<boolean>;
private readonly _hasTypeDefinitionProvider: IContextKey<boolean>;
private readonly _hasHoverProvider: IContextKey<boolean>;
private readonly _hasDocumentHighlightProvider: IContextKey<boolean>;
private readonly _hasDocumentSymbolProvider: IContextKey<boolean>;
private readonly _hasReferenceProvider: IContextKey<boolean>;
private readonly _hasRenameProvider: IContextKey<boolean>;
private readonly _hasDocumentFormattingProvider: IContextKey<boolean>;
private readonly _hasDocumentSelectionFormattingProvider: IContextKey<boolean>;
private readonly _hasMultipleDocumentFormattingProvider: IContextKey<boolean>;
private readonly _hasMultipleDocumentSelectionFormattingProvider: IContextKey<boolean>;
private readonly _hasSignatureHelpProvider: IContextKey<boolean>;
private readonly _hasInlayHintsProvider: IContextKey<boolean>;
private readonly _isInWalkThrough: IContextKey<boolean>;
constructor(
private readonly _editor: CodeEditorWidget,
private readonly _contextKeyService: IContextKeyService,
private readonly _languageFeaturesService: ILanguageFeaturesService,
) {
super();
this._langId = EditorContextKeys.languageId.bindTo(_contextKeyService);
this._hasCompletionItemProvider = EditorContextKeys.hasCompletionItemProvider.bindTo(_contextKeyService);
this._hasCodeActionsProvider = EditorContextKeys.hasCodeActionsProvider.bindTo(_contextKeyService);
this._hasCodeLensProvider = EditorContextKeys.hasCodeLensProvider.bindTo(_contextKeyService);
this._hasDefinitionProvider = EditorContextKeys.hasDefinitionProvider.bindTo(_contextKeyService);
this._hasDeclarationProvider = EditorContextKeys.hasDeclarationProvider.bindTo(_contextKeyService);
this._hasImplementationProvider = EditorContextKeys.hasImplementationProvider.bindTo(_contextKeyService);
this._hasTypeDefinitionProvider = EditorContextKeys.hasTypeDefinitionProvider.bindTo(_contextKeyService);
this._hasHoverProvider = EditorContextKeys.hasHoverProvider.bindTo(_contextKeyService);
this._hasDocumentHighlightProvider = EditorContextKeys.hasDocumentHighlightProvider.bindTo(_contextKeyService);
this._hasDocumentSymbolProvider = EditorContextKeys.hasDocumentSymbolProvider.bindTo(_contextKeyService);
this._hasReferenceProvider = EditorContextKeys.hasReferenceProvider.bindTo(_contextKeyService);
this._hasRenameProvider = EditorContextKeys.hasRenameProvider.bindTo(_contextKeyService);
this._hasSignatureHelpProvider = EditorContextKeys.hasSignatureHelpProvider.bindTo(_contextKeyService);
this._hasInlayHintsProvider = EditorContextKeys.hasInlayHintsProvider.bindTo(_contextKeyService);
this._hasDocumentFormattingProvider = EditorContextKeys.hasDocumentFormattingProvider.bindTo(_contextKeyService);
this._hasDocumentSelectionFormattingProvider = EditorContextKeys.hasDocumentSelectionFormattingProvider.bindTo(_contextKeyService);
this._hasMultipleDocumentFormattingProvider = EditorContextKeys.hasMultipleDocumentFormattingProvider.bindTo(_contextKeyService);
this._hasMultipleDocumentSelectionFormattingProvider = EditorContextKeys.hasMultipleDocumentSelectionFormattingProvider.bindTo(_contextKeyService);
this._isInWalkThrough = EditorContextKeys.isInWalkThroughSnippet.bindTo(_contextKeyService);
const update = () => this._update();
// update when model/mode changes
this._register(_editor.onDidChangeModel(update));
this._register(_editor.onDidChangeModelLanguage(update));
// update when registries change
this._register(_languageFeaturesService.completionProvider.onDidChange(update));
this._register(_languageFeaturesService.codeActionProvider.onDidChange(update));
this._register(_languageFeaturesService.codeLensProvider.onDidChange(update));
this._register(_languageFeaturesService.definitionProvider.onDidChange(update));
this._register(_languageFeaturesService.declarationProvider.onDidChange(update));
this._register(_languageFeaturesService.implementationProvider.onDidChange(update));
this._register(_languageFeaturesService.typeDefinitionProvider.onDidChange(update));
this._register(_languageFeaturesService.hoverProvider.onDidChange(update));
this._register(_languageFeaturesService.documentHighlightProvider.onDidChange(update));
this._register(_languageFeaturesService.documentSymbolProvider.onDidChange(update));
this._register(_languageFeaturesService.referenceProvider.onDidChange(update));
this._register(_languageFeaturesService.renameProvider.onDidChange(update));
this._register(_languageFeaturesService.documentFormattingEditProvider.onDidChange(update));
this._register(_languageFeaturesService.documentRangeFormattingEditProvider.onDidChange(update));
this._register(_languageFeaturesService.signatureHelpProvider.onDidChange(update));
this._register(_languageFeaturesService.inlayHintsProvider.onDidChange(update));
update();
}
override dispose() {
super.dispose();
}
reset() {
this._contextKeyService.bufferChangeEvents(() => {
this._langId.reset();
this._hasCompletionItemProvider.reset();
this._hasCodeActionsProvider.reset();
this._hasCodeLensProvider.reset();
this._hasDefinitionProvider.reset();
this._hasDeclarationProvider.reset();
this._hasImplementationProvider.reset();
this._hasTypeDefinitionProvider.reset();
this._hasHoverProvider.reset();
this._hasDocumentHighlightProvider.reset();
this._hasDocumentSymbolProvider.reset();
this._hasReferenceProvider.reset();
this._hasRenameProvider.reset();
this._hasDocumentFormattingProvider.reset();
this._hasDocumentSelectionFormattingProvider.reset();
this._hasSignatureHelpProvider.reset();
this._isInWalkThrough.reset();
});
}
private _update() {
const model = this._editor.getModel();
if (!model) {
this.reset();
return;
}
this._contextKeyService.bufferChangeEvents(() => {
this._langId.set(model.getLanguageId());
this._hasCompletionItemProvider.set(this._languageFeaturesService.completionProvider.has(model));
this._hasCodeActionsProvider.set(this._languageFeaturesService.codeActionProvider.has(model));
this._hasCodeLensProvider.set(this._languageFeaturesService.codeLensProvider.has(model));
this._hasDefinitionProvider.set(this._languageFeaturesService.definitionProvider.has(model));
this._hasDeclarationProvider.set(this._languageFeaturesService.declarationProvider.has(model));
this._hasImplementationProvider.set(this._languageFeaturesService.implementationProvider.has(model));
this._hasTypeDefinitionProvider.set(this._languageFeaturesService.typeDefinitionProvider.has(model));
this._hasHoverProvider.set(this._languageFeaturesService.hoverProvider.has(model));
this._hasDocumentHighlightProvider.set(this._languageFeaturesService.documentHighlightProvider.has(model));
this._hasDocumentSymbolProvider.set(this._languageFeaturesService.documentSymbolProvider.has(model));
this._hasReferenceProvider.set(this._languageFeaturesService.referenceProvider.has(model));
this._hasRenameProvider.set(this._languageFeaturesService.renameProvider.has(model));
this._hasSignatureHelpProvider.set(this._languageFeaturesService.signatureHelpProvider.has(model));
this._hasInlayHintsProvider.set(this._languageFeaturesService.inlayHintsProvider.has(model));
this._hasDocumentFormattingProvider.set(this._languageFeaturesService.documentFormattingEditProvider.has(model) || this._languageFeaturesService.documentRangeFormattingEditProvider.has(model));
this._hasDocumentSelectionFormattingProvider.set(this._languageFeaturesService.documentRangeFormattingEditProvider.has(model));
this._hasMultipleDocumentFormattingProvider.set(this._languageFeaturesService.documentFormattingEditProvider.all(model).length + this._languageFeaturesService.documentRangeFormattingEditProvider.all(model).length > 1);
this._hasMultipleDocumentSelectionFormattingProvider.set(this._languageFeaturesService.documentRangeFormattingEditProvider.all(model).length > 1);
this._isInWalkThrough.set(model.uri.scheme === Schemas.walkThroughSnippet);
});
}
}
class CodeEditorWidgetFocusTracker extends Disposable {
private _hasFocus: boolean;
private readonly _domFocusTracker: dom.IFocusTracker;
private readonly _onChange: Emitter<void> = this._register(new Emitter<void>());
public readonly onChange: Event<void> = this._onChange.event;
constructor(domElement: HTMLElement) {
super();
this._hasFocus = false;
this._domFocusTracker = this._register(dom.trackFocus(domElement));
this._register(this._domFocusTracker.onDidFocus(() => {
this._hasFocus = true;
this._onChange.fire(undefined);
}));
this._register(this._domFocusTracker.onDidBlur(() => {
this._hasFocus = false;
this._onChange.fire(undefined);
}));
}
public hasFocus(): boolean {
return this._hasFocus;
}
public refreshState(): void {
this._domFocusTracker.refreshState?.();
}
}
class EditorDecorationsCollection implements editorCommon.IEditorDecorationsCollection {
private _decorationIds: string[] = [];
private _isChangingDecorations: boolean = false;
public get length(): number {
return this._decorationIds.length;
}
constructor(
private readonly _editor: editorBrowser.ICodeEditor,
decorations: IModelDeltaDecoration[] | undefined
) {
if (Array.isArray(decorations) && decorations.length > 0) {
this.set(decorations);
}
}
public onDidChange(listener: (e: IModelDecorationsChangedEvent) => any, thisArgs?: any, disposables?: IDisposable[] | DisposableStore): IDisposable {
return this._editor.onDidChangeModelDecorations((e) => {
if (this._isChangingDecorations) {
return;
}
listener.call(thisArgs, e);
}, disposables);
}
public getRange(index: number): Range | null {
if (!this._editor.hasModel()) {
return null;
}
if (index >= this._decorationIds.length) {
return null;
}
return this._editor.getModel().getDecorationRange(this._decorationIds[index]);
}
public getRanges(): Range[] {
if (!this._editor.hasModel()) {
return [];
}
const model = this._editor.getModel();
const result: Range[] = [];
for (const decorationId of this._decorationIds) {
const range = model.getDecorationRange(decorationId);
if (range) {
result.push(range);
}
}
return result;
}
public has(decoration: IModelDecoration): boolean {
return this._decorationIds.includes(decoration.id);
}
public clear(): void {
if (this._decorationIds.length === 0) {
// nothing to do
return;
}
this.set([]);
}
public set(newDecorations: IModelDeltaDecoration[]): void {
try {
this._isChangingDecorations = true;
this._editor.changeDecorations((accessor) => {
this._decorationIds = accessor.deltaDecorations(this._decorationIds, newDecorations);
});
} finally {
this._isChangingDecorations = false;
}
}
}
const squigglyStart = encodeURIComponent(`<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 6 3' enable-background='new 0 0 6 3' height='3' width='6'><g fill='`);
const squigglyEnd = encodeURIComponent(`'><polygon points='5.5,0 2.5,3 1.1,3 4.1,0'/><polygon points='4,0 6,2 6,0.6 5.4,0'/><polygon points='0,2 1,3 2.4,3 0,0.6'/></g></svg>`);
function getSquigglySVGData(color: Color) {
return squigglyStart + encodeURIComponent(color.toString()) + squigglyEnd;
}
const dotdotdotStart = encodeURIComponent(`<svg xmlns="http://www.w3.org/2000/svg" height="3" width="12"><g fill="`);
const dotdotdotEnd = encodeURIComponent(`"><circle cx="1" cy="1" r="1"/><circle cx="5" cy="1" r="1"/><circle cx="9" cy="1" r="1"/></g></svg>`);
function getDotDotDotSVGData(color: Color) {
return dotdotdotStart + encodeURIComponent(color.toString()) + dotdotdotEnd;
}
registerThemingParticipant((theme, collector) => {
const errorBorderColor = theme.getColor(editorErrorBorder);
if (errorBorderColor) {
collector.addRule(`.monaco-editor .${ClassName.EditorErrorDecoration} { border-bottom: 4px double ${errorBorderColor}; }`);
}
const errorForeground = theme.getColor(editorErrorForeground);
if (errorForeground) {
collector.addRule(`.monaco-editor .${ClassName.EditorErrorDecoration} { background: url("data:image/svg+xml,${getSquigglySVGData(errorForeground)}") repeat-x bottom left; }`);
}
const errorBackground = theme.getColor(editorErrorBackground);
if (errorBackground) {
collector.addRule(`.monaco-editor .${ClassName.EditorErrorDecoration}::before { display: block; content: ''; width: 100%; height: 100%; background: ${errorBackground}; }`);
}
const warningBorderColor = theme.getColor(editorWarningBorder);
if (warningBorderColor) {
collector.addRule(`.monaco-editor .${ClassName.EditorWarningDecoration} { border-bottom: 4px double ${warningBorderColor}; }`);
}
const warningForeground = theme.getColor(editorWarningForeground);
if (warningForeground) {
collector.addRule(`.monaco-editor .${ClassName.EditorWarningDecoration} { background: url("data:image/svg+xml,${getSquigglySVGData(warningForeground)}") repeat-x bottom left; }`);
}
const warningBackground = theme.getColor(editorWarningBackground);
if (warningBackground) {
collector.addRule(`.monaco-editor .${ClassName.EditorWarningDecoration}::before { display: block; content: ''; width: 100%; height: 100%; background: ${warningBackground}; }`);
}
const infoBorderColor = theme.getColor(editorInfoBorder);
if (infoBorderColor) {
collector.addRule(`.monaco-editor .${ClassName.EditorInfoDecoration} { border-bottom: 4px double ${infoBorderColor}; }`);
}
const infoForeground = theme.getColor(editorInfoForeground);
if (infoForeground) {
collector.addRule(`.monaco-editor .${ClassName.EditorInfoDecoration} { background: url("data:image/svg+xml,${getSquigglySVGData(infoForeground)}") repeat-x bottom left; }`);
}
const infoBackground = theme.getColor(editorInfoBackground);
if (infoBackground) {
collector.addRule(`.monaco-editor .${ClassName.EditorInfoDecoration}::before { display: block; content: ''; width: 100%; height: 100%; background: ${infoBackground}; }`);
}
const hintBorderColor = theme.getColor(editorHintBorder);
if (hintBorderColor) {
collector.addRule(`.monaco-editor .${ClassName.EditorHintDecoration} { border-bottom: 2px dotted ${hintBorderColor}; }`);
}
const hintForeground = theme.getColor(editorHintForeground);
if (hintForeground) {
collector.addRule(`.monaco-editor .${ClassName.EditorHintDecoration} { background: url("data:image/svg+xml,${getDotDotDotSVGData(hintForeground)}") no-repeat bottom left; }`);
}
const unnecessaryForeground = theme.getColor(editorUnnecessaryCodeOpacity);
if (unnecessaryForeground) {
collector.addRule(`.monaco-editor.showUnused .${ClassName.EditorUnnecessaryInlineDecoration} { opacity: ${unnecessaryForeground.rgba.a}; }`);
}
const unnecessaryBorder = theme.getColor(editorUnnecessaryCodeBorder);
if (unnecessaryBorder) {
collector.addRule(`.monaco-editor.showUnused .${ClassName.EditorUnnecessaryDecoration} { border-bottom: 2px dashed ${unnecessaryBorder}; }`);
}
const deprecatedForeground = theme.getColor(editorForeground) || 'inherit';
collector.addRule(`.monaco-editor.showDeprecated .${ClassName.EditorDeprecatedInlineDecoration} { text-decoration: line-through; text-decoration-color: ${deprecatedForeground}}`);
});
|