-
Notifications
You must be signed in to change notification settings - Fork 325
/
notebook.ts
1200 lines (1090 loc) · 46.8 KB
/
notebook.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
import * as vscode from 'vscode';
import * as proto from 'vscode-languageserver-protocol';
import {
StaticRegistrationOptions, NotebookDocumentFilter, TextDocumentItem, NotebookCellTextDocumentFilter, LSPAny,
NotebookDocumentFilterWithCells, NotebookDocumentFilterWithNotebook
} from 'vscode-languageserver-protocol';
import * as UUID from './utils/uuid';
import * as Is from './utils/is';
import * as _c2p from './codeConverter';
import * as _p2c from './protocolConverter';
import { DynamicFeature, FeatureClient, RegistrationData, FeatureState } from './features';
import { matchGlobPattern } from './utils/globPattern';
function ensure<T, K extends keyof T>(target: T, key: K): T[K] {
if (target[key] === void 0) {
target[key] = {} as any;
}
return target[key];
}
type $LSPObject = { [key: string]: LSPAny };
type $LSPArray = LSPAny[];
namespace Converter {
export namespace c2p {
export function asVersionedNotebookDocumentIdentifier(notebookDocument: vscode.NotebookDocument, base: _c2p.Converter): proto.VersionedNotebookDocumentIdentifier {
return {
version: notebookDocument.version,
uri: base.asUri(notebookDocument.uri)
};
}
export function asNotebookDocument(notebookDocument: vscode.NotebookDocument, cells: vscode.NotebookCell[], base: _c2p.Converter): proto.NotebookDocument {
const result = proto.NotebookDocument.create(base.asUri(notebookDocument.uri), notebookDocument.notebookType, notebookDocument.version, asNotebookCells(cells, base));
if (Object.keys(notebookDocument.metadata).length > 0) {
result.metadata = asMetadata(notebookDocument.metadata);
}
return result;
}
export function asNotebookCells(cells: vscode.NotebookCell[], base: _c2p.Converter): proto.NotebookCell[] {
return cells.map(cell => asNotebookCell(cell, base));
}
export function asMetadata(metadata: { [key: string]: any}): $LSPObject {
const seen: Set<any> = new Set();
return deepCopy(seen, metadata);
}
export function asNotebookCell(cell: vscode.NotebookCell, base: _c2p.Converter): proto.NotebookCell {
const result = proto.NotebookCell.create(asNotebookCellKind(cell.kind), base.asUri(cell.document.uri));
if (Object.keys(cell.metadata).length > 0) {
result.metadata = asMetadata(cell.metadata);
}
if (cell.executionSummary !== undefined && (Is.number(cell.executionSummary.executionOrder) && Is.boolean(cell.executionSummary.success))) {
result.executionSummary = {
executionOrder: cell.executionSummary.executionOrder,
success: cell.executionSummary.success
};
}
return result;
}
function asNotebookCellKind(kind: vscode.NotebookCellKind): proto.NotebookCellKind {
switch (kind) {
case vscode.NotebookCellKind.Markup:
return proto.NotebookCellKind.Markup;
case vscode.NotebookCellKind.Code:
return proto.NotebookCellKind.Code;
}
}
function deepCopy(seen: Set<any>, value: {[key: string]: any}): $LSPObject;
function deepCopy(seen: Set<any>, value: any[]): $LSPArray;
function deepCopy(seen: Set<any>, value: {[key: string]: any} | any[]): $LSPArray | $LSPObject {
if (seen.has(value)) {
throw new Error(`Can't deep copy cyclic structures.`);
}
if (Array.isArray(value)) {
const result: $LSPArray = [];
for (const elem of value) {
if (elem !== null && typeof elem === 'object' || Array.isArray(elem)) {
result.push(deepCopy(seen, elem));
} else {
if (elem instanceof RegExp) {
throw new Error(`Can't transfer regular expressions to the server`);
}
result.push(elem);
}
}
return result;
} else {
const props = Object.keys(value);
const result: $LSPObject = Object.create(null);
for (const prop of props) {
const elem = value[prop];
if (elem !== null && typeof elem === 'object' || Array.isArray(elem)) {
result[prop] = deepCopy(seen, elem);
} else {
if (elem instanceof RegExp) {
throw new Error(`Can't transfer regular expressions to the server`);
}
result[prop] = elem;
}
}
return result;
}
}
type TextContent = Required<Required<Required<proto.NotebookDocumentChangeEvent>['cells']>['textContent']>[0];
export function asTextContentChange(event: vscode.TextDocumentChangeEvent, base: _c2p.Converter): TextContent {
const params = base.asChangeTextDocumentParams(event, event.document.uri, event.document.version);
return { document: params.textDocument, changes: params.contentChanges };
}
export function asNotebookDocumentChangeEvent(event: VNotebookDocumentChangeEvent, base: _c2p.Converter): proto.NotebookDocumentChangeEvent {
const result: proto.NotebookDocumentChangeEvent = Object.create(null);
if (event.metadata) {
result.metadata = Converter.c2p.asMetadata(event.metadata);
}
if (event.cells !== undefined) {
const cells: Required<proto.NotebookDocumentChangeEvent>['cells'] = Object.create(null);
const changedCells = event.cells;
if (changedCells.structure) {
cells.structure = {
array: {
start: changedCells.structure.array.start,
deleteCount: changedCells.structure.array.deleteCount,
cells: changedCells.structure.array.cells !== undefined ? changedCells.structure.array.cells.map(cell => Converter.c2p.asNotebookCell(cell, base)) : undefined
},
didOpen: changedCells.structure.didOpen !== undefined
? changedCells.structure.didOpen.map(cell => base.asOpenTextDocumentParams(cell.document).textDocument)
: undefined,
didClose: changedCells.structure.didClose !== undefined
? changedCells.structure.didClose.map(cell => base.asCloseTextDocumentParams(cell.document).textDocument)
: undefined
};
}
if (changedCells.data !== undefined) {
cells.data = changedCells.data.map(cell => Converter.c2p.asNotebookCell(cell, base));
}
if (changedCells.textContent !== undefined) {
cells.textContent = changedCells.textContent.map(event => Converter.c2p.asTextContentChange(event, base));
}
if (Object.keys(cells).length > 0) {
result.cells = cells;
}
}
return result;
}
}
}
namespace $NotebookCell {
type ComputeDiffReturnType = { start: number; deleteCount: number; cells?: vscode.NotebookCell[] };
export function computeDiff(originalCells: vscode.NotebookCell[], modifiedCells: vscode.NotebookCell[], compareMetadata: boolean): ComputeDiffReturnType | undefined {
const originalLength = originalCells.length;
const modifiedLength = modifiedCells.length;
let startIndex = 0;
while(startIndex < modifiedLength && startIndex < originalLength && equals(originalCells[startIndex], modifiedCells[startIndex], compareMetadata)) {
startIndex++;
}
if (startIndex < modifiedLength && startIndex < originalLength) {
let originalEndIndex = originalLength - 1;
let modifiedEndIndex = modifiedLength - 1;
while (originalEndIndex >= 0 && modifiedEndIndex >= 0 && equals(originalCells[originalEndIndex], modifiedCells[modifiedEndIndex], compareMetadata)) {
originalEndIndex--;
modifiedEndIndex--;
}
const deleteCount = (originalEndIndex + 1) - startIndex;
const newCells = startIndex === modifiedEndIndex + 1 ? undefined : modifiedCells.slice(startIndex, modifiedEndIndex + 1);
return newCells !== undefined ? { start: startIndex, deleteCount, cells: newCells } : { start: startIndex, deleteCount };
} else if (startIndex < modifiedLength) {
return { start: startIndex, deleteCount: 0, cells: modifiedCells.slice(startIndex) } ;
} else if (startIndex < originalLength) {
return { start: startIndex, deleteCount: originalLength - startIndex };
} else {
// The two arrays are the same.
return undefined;
}
}
/**
* We only sync kind, document, execution and metadata to the server. So we only need to compare those.
*/
function equals(one: vscode.NotebookCell, other: vscode.NotebookCell, compareMetaData: boolean = true): boolean {
if (one.kind !== other.kind || one.document.uri.toString() !== other.document.uri.toString() || one.document.languageId !== other.document.languageId ||
!equalsExecution(one.executionSummary, other.executionSummary))
{
return false;
}
return !compareMetaData || (compareMetaData && equalsMetadata(one.metadata, other.metadata));
}
function equalsExecution(one: vscode.NotebookCellExecutionSummary | undefined, other: vscode.NotebookCellExecutionSummary | undefined): boolean {
if (one === other) {
return true;
}
if (one === undefined || other === undefined) {
return false;
}
return one.executionOrder === other.executionOrder && one.success === other.success && equalsTiming(one.timing, other.timing);
}
function equalsTiming(one: { startTime: number; endTime: number } | undefined, other: { startTime: number; endTime: number } | undefined): boolean {
if (one === other) {
return true;
}
if (one === undefined || other === undefined) {
return false;
}
return one.startTime === other.startTime && one.endTime === other.endTime;
}
function equalsMetadata(one: any, other: any | undefined): boolean {
if (one === other) {
return true;
}
if (one === null || one === undefined || other === null || other === undefined) {
return false;
}
if (typeof one !== typeof other) {
return false;
}
if (typeof one !== 'object') {
return false;
}
const oneArray = Array.isArray(one);
const otherArray = Array.isArray(other);
if (oneArray !== otherArray) {
return false;
}
if (oneArray && otherArray) {
if (one.length !== other.length) {
return false;
}
for (let i = 0; i < one.length; i++) {
if (!equalsMetadata(one[i], other[i])) {
return false;
}
}
}
if (isObjectLiteral(one) && isObjectLiteral(other)) {
const oneKeys = Object.keys(one);
const otherKeys = Object.keys(other);
if (oneKeys.length !== otherKeys.length) {
return false;
}
oneKeys.sort();
otherKeys.sort();
if (!equalsMetadata(oneKeys, otherKeys)) {
return false;
}
for (let i = 0; i < oneKeys.length; i++) {
const prop = oneKeys[i];
if (!equalsMetadata((one as $LSPObject)[prop], (other as $LSPObject)[prop])) {
return false;
}
}
return true;
}
return false;
}
export function isObjectLiteral(value: any): value is object {
return value !== null && typeof value === 'object';
}
}
namespace $NotebookDocumentFilter {
export function matchNotebook(filter: string | NotebookDocumentFilter, notebookDocument: vscode.NotebookDocument): boolean {
if (typeof filter === 'string') {
return filter === '*' || notebookDocument.notebookType === filter;
}
if (filter.notebookType !== undefined && filter.notebookType !== '*' && notebookDocument.notebookType !== filter.notebookType) {
return false;
}
const uri = notebookDocument.uri;
if (filter.scheme !== undefined && filter.scheme !== '*' && uri.scheme !== filter.scheme) {
return false;
}
if (filter.pattern !== undefined) {
if (!matchGlobPattern(filter.pattern, uri)) {
return false;
}
}
return true;
}
}
namespace $NotebookDocumentSyncOptions {
export function asDocumentSelector(options: proto.NotebookDocumentSyncOptions): proto.DocumentSelector {
const selector = options.notebookSelector;
const result: proto.DocumentSelector = [];
for (const element of selector) {
const notebookType = (typeof element.notebook === 'string' ? element.notebook : element.notebook?.notebookType) ?? '*';
const scheme = (typeof element.notebook === 'string') ? undefined : element.notebook?.scheme;
const pattern = (typeof element.notebook === 'string') ? undefined : element.notebook?.pattern;
if (element.cells !== undefined) {
for (const cell of element.cells) {
result.push(asDocumentFilter(notebookType, scheme, pattern, cell.language));
}
} else {
result.push(asDocumentFilter(notebookType, scheme, pattern, undefined));
}
}
return result;
}
function asDocumentFilter(notebookType: string, scheme: string | undefined, pattern: proto.GlobPattern | undefined, language: string | undefined): proto.NotebookCellTextDocumentFilter {
return scheme === undefined && pattern === undefined
? { notebook: notebookType, language }
: { notebook: { notebookType, scheme, pattern }, language };
}
}
type SyncInfo = {
/**
* The synced VS Code notebook cells.
*/
cells: vscode.NotebookCell[];
/**
* A set of VS Code URIs of the synced
* VS Code notebook cell text documents.
*/
uris: Set<string>;
};
namespace SyncInfo {
export function create(cells: vscode.NotebookCell[]): SyncInfo {
return {
cells,
uris: new Set(cells.map(cell => cell.document.uri.toString()))
};
}
}
export type VNotebookDocumentChangeEvent = {
/**
* The notebook document
*/
notebook: vscode.NotebookDocument;
/**
* The changed meta data if any.
*/
metadata?: { [key: string]: any };
/**
* Changes to cells.
*/
cells?: {
/**
* Changes to the cell structure to add or
* remove cells.
*/
structure?: {
/**
* The change to the cell array.
*/
array: { start: number; deleteCount: number; cells?: vscode.NotebookCell[] };
/**
* Additional opened cell text documents.
*/
didOpen?: vscode.NotebookCell[];
/**
* Additional closed cell text documents.
*/
didClose?: vscode.NotebookCell[];
};
/**
* Changes to notebook cells properties like its
* kind or metadata.
*/
data?: vscode.NotebookCell[];
/**
* Changes to the text content of notebook cells.
*/
textContent?: vscode.TextDocumentChangeEvent[];
};
};
export type NotebookDocumentOptions = {
filterCells?(notebookDocument: vscode.NotebookDocument, cells: vscode.NotebookCell[]): vscode.NotebookCell[];
};
export type $NotebookDocumentOptions = {
notebookDocumentOptions?: NotebookDocumentOptions;
};
export type NotebookDocumentMiddleware = {
notebooks?: {
didOpen?: (this: void, notebookDocument: vscode.NotebookDocument, cells: vscode.NotebookCell[], next: (this: void, notebookDocument: vscode.NotebookDocument, cells: vscode.NotebookCell[]) => Promise<void>) => Promise<void>;
didSave?: (this: void, notebookDocument: vscode.NotebookDocument, next: (this: void, notebookDocument: vscode.NotebookDocument) => Promise<void>) => Promise<void>;
didChange?: (this: void, event: VNotebookDocumentChangeEvent, next: (this: void, event: VNotebookDocumentChangeEvent) => Promise<void>) => Promise<void>;
didClose?: (this: void, notebookDocument: vscode.NotebookDocument, cells: vscode.NotebookCell[], next: (this: void, notebookDocument: vscode.NotebookDocument, cells: vscode.NotebookCell[]) => Promise<void>) => Promise<void>;
};
};
export interface NotebookDocumentSyncFeatureShape {
sendDidOpenNotebookDocument(notebookDocument: vscode.NotebookDocument): Promise<void>;
sendDidSaveNotebookDocument(notebookDocument: vscode.NotebookDocument): Promise<void>;
sendDidChangeNotebookDocument(event: VNotebookDocumentChangeEvent): Promise<void>;
sendDidCloseNotebookDocument(notebookDocument: vscode.NotebookDocument): Promise<void>;
getSynchronizedCells(notebookDocument: vscode.NotebookDocument): vscode.NotebookCell[] | undefined;
}
class NotebookDocumentSyncFeatureProvider implements NotebookDocumentSyncFeatureShape {
private readonly client: FeatureClient<NotebookDocumentMiddleware, $NotebookDocumentOptions>;
private readonly options: proto.NotebookDocumentSyncOptions;
private readonly notebookSyncInfo: Map<string, SyncInfo>;
private readonly notebookDidOpen: Set<string>;
private readonly disposables: vscode.Disposable[];
private readonly selector: vscode.DocumentSelector;
private readonly onChangeNotificationSent: vscode.EventEmitter<VNotebookDocumentChangeEvent>;
private readonly onOpenNotificationSent: vscode.EventEmitter<vscode.NotebookDocument>;
private readonly onCloseNotificationSent: vscode.EventEmitter<vscode.NotebookDocument>;
private readonly onSaveNotificationSent: vscode.EventEmitter<vscode.NotebookDocument>;
constructor(
client: FeatureClient<NotebookDocumentMiddleware, $NotebookDocumentOptions>,
options: proto.NotebookDocumentSyncOptions,
onChangeNotificationSent: vscode.EventEmitter<VNotebookDocumentChangeEvent>,
onOpenNotificationSent: vscode.EventEmitter<vscode.NotebookDocument>,
onCloseNotificationSent: vscode.EventEmitter<vscode.NotebookDocument>,
onSaveNotificationSent: vscode.EventEmitter<vscode.NotebookDocument>
) {
this.client = client;
this.options = options;
this.notebookSyncInfo = new Map();
this.notebookDidOpen = new Set();
this.disposables = [];
this.selector = client.protocol2CodeConverter.asDocumentSelector($NotebookDocumentSyncOptions.asDocumentSelector(options));
this.onChangeNotificationSent = onChangeNotificationSent;
this.onOpenNotificationSent = onOpenNotificationSent;
this.onCloseNotificationSent = onCloseNotificationSent;
this.onSaveNotificationSent = onSaveNotificationSent;
// open
vscode.workspace.onDidOpenNotebookDocument((notebookDocument) => {
this.notebookDidOpen.add(notebookDocument.uri.toString());
this.didOpen(notebookDocument);
}, undefined, this.disposables);
for (const notebookDocument of vscode.workspace.notebookDocuments) {
this.notebookDidOpen.add(notebookDocument.uri.toString());
this.didOpen(notebookDocument);
}
// Notebook document changed.
vscode.workspace.onDidChangeNotebookDocument(event => this.didChangeNotebookDocument(event), undefined, this.disposables);
//save
if (this.options.save === true) {
vscode.workspace.onDidSaveNotebookDocument(notebookDocument => this.didSave(notebookDocument), undefined, this.disposables);
}
// close
vscode.workspace.onDidCloseNotebookDocument((notebookDocument) => {
this.didClose(notebookDocument);
this.notebookDidOpen.delete(notebookDocument.uri.toString());
}, undefined, this.disposables);
}
public getState(): FeatureState {
for (const notebook of vscode.workspace.notebookDocuments) {
const matchingCells = this.getMatchingCellsConsideringSyncInfo(notebook);
if (matchingCells !== undefined) {
return { kind: 'document', id: '$internal', registrations: true, matches: true };
}
}
return { kind: 'document', id: '$internal', registrations: true, matches: false };
}
public get mode(): 'notebook' {
return 'notebook';
}
public handles(textDocument: vscode.TextDocument): boolean {
if (vscode.languages.match(this.selector, textDocument) > 0) {
return true;
}
// Work around for https://github.com/microsoft/vscode/issues/202163
const key = textDocument.uri.toString();
for (const syncInfo of this.notebookSyncInfo.values()) {
if (syncInfo.uris.has(key)) {
return true;
}
}
return false;
}
public didOpenNotebookCellTextDocument(notebookDocument: vscode.NotebookDocument, cell: vscode.NotebookCell): void {
if (vscode.languages.match(this.selector, cell.document) === 0) {
return;
}
if (!this.notebookDidOpen.has(notebookDocument.uri.toString())) {
// We have never received an open notification for the notebook document.
// VS Code guarantees that we first get cell document open and then
// notebook open. So simply wait for the notebook open.
return;
}
const syncInfo = this.getSyncInfo(notebookDocument);
// In VS Code we receive a notebook open before a cell document open.
// The document and the cell is synced.
const cellMatches = this.cellMatches(notebookDocument, cell);
if (syncInfo !== undefined) {
const cellIsSynced = syncInfo.uris.has(cell.document.uri.toString());
if ((cellMatches && cellIsSynced) || (!cellMatches && !cellIsSynced)) {
// The cell doesn't match and was not synced or it matches and is synced.
// In both cases nothing to do.
//
// Note that if the language mode of a document changes we remove the
// cell and add it back to update the language mode on the server side.
return;
}
if (cellMatches) {
// don't use cells from above since there might be more matching cells in the notebook
// Since we had a matching cell above we will have matching cells now.
const matchingCells = this.mergeCells(notebookDocument, syncInfo, [cell]);
if (matchingCells !== undefined) {
const event = this.asNotebookDocumentChangeEvent(notebookDocument, undefined, syncInfo, matchingCells);
if (event !== undefined) {
this.doSendChange(event, matchingCells).catch(() => { /* handled in send change */ });
}
}
}
} else {
// No sync info. But we have a open event for the notebook document
// itself. If the cell matches then we need to send an open with
// exactly that cell.
if (cellMatches) {
this.doSendOpen(notebookDocument, [cell]).catch(() => { /* handled in open */ });
}
}
}
public didChangeNotebookCellTextDocument(notebookDocument: vscode.NotebookDocument, cell: vscode.NotebookCell, event: vscode.TextDocumentChangeEvent): void {
// No match with the selector
if (vscode.languages.match(this.selector, event.document) === 0) {
return;
}
const syncInfo = this.getSyncInfo(notebookDocument);
// Notebook got never synced. So it doesn't matter if a cell document changes.
if (syncInfo === undefined || !syncInfo.uris.has(cell.document.uri.toString())) {
return;
}
this.doSendChange({
notebook: notebookDocument,
cells: { textContent: [event] }
}, syncInfo.cells).catch(() => { /* error handled in doSendChange */ });
}
public didCloseNotebookCellTextDocument(notebookDocument: vscode.NotebookDocument, cell: vscode.NotebookCell): void {
const syncInfo = this.getSyncInfo(notebookDocument);
if (syncInfo === undefined) {
// The notebook document got never synced. So it doesn't matter if a cell
// document closes.
return;
}
const cellUri = cell.document.uri;
const index = syncInfo.cells.findIndex((item) => item.document.uri.toString() === cellUri.toString());
if (index === -1) {
// The cell never got synced or it got deleted and we now received the document
// close event.
return;
}
if (index === 0 && syncInfo.cells.length === 1) {
// The last cell. Close the notebook document in the server.
this.doSendClose(notebookDocument, syncInfo.cells).catch(() => { /* error handled in doSendClose */ });
} else {
const newCells = syncInfo.cells.slice();
const deleted = newCells.splice(index, 1);
this.doSendChange({
notebook: notebookDocument,
cells: {
structure: {
array: { start: index, deleteCount: 1 },
didClose: deleted
}
}
}, newCells).catch(() => { /* error handled in doSendChange */ });
}
}
public dispose(): void {
for (const disposable of this.disposables) {
disposable.dispose();
}
}
private didOpen(notebookDocument: vscode.NotebookDocument, matchingCells?: vscode.NotebookCell[] | undefined, syncInfo: SyncInfo | undefined = this.getSyncInfo(notebookDocument)): void {
if (syncInfo !== undefined) {
if (matchingCells === undefined) {
matchingCells = syncInfo.cells.slice();
}
if (matchingCells !== undefined) {
const event = this.asNotebookDocumentChangeEvent(notebookDocument, undefined, syncInfo, matchingCells);
if (event !== undefined) {
this.doSendChange(event, matchingCells).catch(() => { /* handled in send change */ });
}
} else {
this.doSendClose(notebookDocument, []).catch(() => { /* handled in send close */} );
}
} else {
matchingCells = this.getMatchingCells(notebookDocument);
// Check if we need to sync the notebook document.
if (matchingCells === undefined) {
return;
}
this.doSendOpen(notebookDocument, matchingCells).catch(() => { /* error handled in doSendOpen */ });
}
}
private didChangeNotebookDocument(event: vscode.NotebookDocumentChangeEvent): void {
const notebookDocument = event.notebook;
const syncInfo = this.getSyncInfo(notebookDocument);
if (syncInfo === undefined) {
// We have no changes to the cells. Since the notebook wasn't synced
// it will not be synced now.
if (event.contentChanges.length === 0) {
return;
}
// Check if we have new matching cells.
const cells = this.getMatchingCells(notebookDocument);
// No matching cells and the notebook never synced. So still no need
// to sync it.
if (cells === undefined) {
return;
}
// Open the notebook document and ignore the rest of the changes
// this the notebooks will be synced with the correct settings.
this.didOpen(notebookDocument, cells, syncInfo);
} else {
// The notebook is synced. First check if we have no matching
// cells anymore and if so close the notebook
const cells = this.getMatchingCellsFromEvent(notebookDocument, syncInfo, event);
if (cells === undefined) {
this.didClose(notebookDocument, syncInfo);
return;
}
const newEvent = this.asNotebookDocumentChangeEvent(event.notebook, event, syncInfo, cells);
if (newEvent !== undefined) {
this.doSendChange(newEvent, cells).catch(() => { /* error handled in doSendChange */ });
}
}
}
private didSave(notebookDocument: vscode.NotebookDocument): void {
const syncInfo = this.getSyncInfo(notebookDocument);
if (syncInfo === undefined) {
return;
}
this.doSendSave(notebookDocument).catch(() => {/* error handled in doSendSave */});
}
private didClose(notebookDocument: vscode.NotebookDocument, syncInfo: SyncInfo | undefined = this.getSyncInfo(notebookDocument)): void {
if (syncInfo === undefined) {
return;
}
const syncedCells = notebookDocument.getCells().filter(cell => syncInfo.uris.has(cell.document.uri.toString()));
this.doSendClose(notebookDocument, syncedCells).catch(() => {/* error handled in doSendClose */ });
}
public async sendDidOpenNotebookDocument(notebookDocument: vscode.NotebookDocument): Promise<void> {
const syncInfo = this.getSyncInfo(notebookDocument);
if (syncInfo !== undefined) {
throw new Error(`Notebook document ${notebookDocument.uri.toString()} is already open`);
}
const cells = this.getMatchingCells(notebookDocument);
if (cells === undefined) {
return;
}
return this.doSendOpen(notebookDocument, cells);
}
private async doSendOpen(notebookDocument: vscode.NotebookDocument, cells: vscode.NotebookCell[]): Promise<void> {
const send = async (notebookDocument: vscode.NotebookDocument, cells: vscode.NotebookCell[]): Promise<void> => {
const cellDocuments: TextDocumentItem[] = cells.map(cell => this.client.code2ProtocolConverter.asTextDocumentItem(cell.document));
try {
await this.client.sendNotification(proto.DidOpenNotebookDocumentNotification.type, {
notebookDocument: Converter.c2p.asNotebookDocument(notebookDocument, cells, this.client.code2ProtocolConverter),
cellTextDocuments: cellDocuments
});
this.onOpenNotificationSent.fire(notebookDocument);
} catch (error) {
this.client.error('Sending DidOpenNotebookDocumentNotification failed', error);
throw error;
}
};
const middleware = this.client.middleware?.notebooks;
this.notebookSyncInfo.set(notebookDocument.uri.toString(), SyncInfo.create(cells));
return middleware?.didOpen !== undefined ? middleware.didOpen(notebookDocument, cells, send) : send(notebookDocument, cells);
}
public async sendDidChangeNotebookDocument(event: VNotebookDocumentChangeEvent): Promise<void> {
const cells = this.getMatchingCellsFromSyncInfo(event.notebook);
if (cells === undefined) {
throw new Error(`Received changed event for un-synced notebook ${event.notebook.uri.toString()}`);
}
return this.doSendChange(event, cells);
}
private async doSendChange(event: VNotebookDocumentChangeEvent, cells: vscode.NotebookCell[]): Promise<void> {
const send = async (event: VNotebookDocumentChangeEvent): Promise<void> => {
try {
await this.client.sendNotification(proto.DidChangeNotebookDocumentNotification.type, {
notebookDocument: Converter.c2p.asVersionedNotebookDocumentIdentifier(event.notebook, this.client.code2ProtocolConverter),
change: Converter.c2p.asNotebookDocumentChangeEvent(event, this.client.code2ProtocolConverter)
});
this.onChangeNotificationSent.fire(event);
} catch (error) {
this.client.error('Sending DidChangeNotebookDocumentNotification failed', error);
throw error;
}
};
const middleware = this.client.middleware?.notebooks;
if (event.cells?.structure !== undefined) {
this.notebookSyncInfo.set(event.notebook.uri.toString(), SyncInfo.create(cells));
}
return middleware?.didChange !== undefined ? middleware?.didChange(event, send) : send(event);
}
public async sendDidSaveNotebookDocument(notebookDocument: vscode.NotebookDocument): Promise<void> {
return this.doSendSave(notebookDocument);
}
private async doSendSave(notebookDocument: vscode.NotebookDocument): Promise<void> {
const send = async (notebookDocument: vscode.NotebookDocument): Promise<void> => {
try {
await this.client.sendNotification(proto.DidSaveNotebookDocumentNotification.type, {
notebookDocument: { uri: this.client.code2ProtocolConverter.asUri(notebookDocument.uri) }
});
this.onSaveNotificationSent.fire(notebookDocument);
} catch (error) {
this.client.error('Sending DidSaveNotebookDocumentNotification failed', error);
throw error;
}
};
const middleware = this.client.middleware?.notebooks;
return middleware?.didSave !== undefined ? middleware.didSave(notebookDocument, send) : send(notebookDocument);
}
public async sendDidCloseNotebookDocument(notebookDocument: vscode.NotebookDocument): Promise<void> {
const cells = this.getMatchingCellsFromSyncInfo(notebookDocument);
if (cells === undefined) {
throw new Error(`Received close event for un-synced notebook ${notebookDocument.uri.toString()}`);
}
return this.doSendClose(notebookDocument, cells);
}
private async doSendClose(notebookDocument: vscode.NotebookDocument, cells: vscode.NotebookCell[]): Promise<void> {
const send = async (notebookDocument: vscode.NotebookDocument, cells: vscode.NotebookCell[]): Promise<void> => {
try {
await this.client.sendNotification(proto.DidCloseNotebookDocumentNotification.type, {
notebookDocument: { uri: this.client.code2ProtocolConverter.asUri(notebookDocument.uri) },
cellTextDocuments: cells.map(cell => this.client.code2ProtocolConverter.asTextDocumentIdentifier(cell.document))
});
this.onCloseNotificationSent.fire(notebookDocument);
} catch (error) {
this.client.error('Sending DidCloseNotebookDocumentNotification failed', error);
throw error;
}
};
const middleware = this.client.middleware?.notebooks;
this.notebookSyncInfo.delete(notebookDocument.uri.toString());
return middleware?.didClose !== undefined ? middleware.didClose(notebookDocument, cells, send) : send(notebookDocument, cells);
}
public getSynchronizedCells(notebookDocument: vscode.NotebookDocument): vscode.NotebookCell[] | undefined {
const syncInfo = this.getSyncInfo(notebookDocument);
return syncInfo?.cells;
}
private asNotebookDocumentChangeEvent(notebook: vscode.NotebookDocument, event: vscode.NotebookDocumentChangeEvent | undefined, syncInfo: SyncInfo, matchingCells: vscode.NotebookCell[]): VNotebookDocumentChangeEvent | undefined {
if (event !== undefined && event.notebook !== notebook) {
throw new Error('Notebook must be identical');
}
const result: VNotebookDocumentChangeEvent = {
notebook: notebook
};
if (event?.metadata !== undefined) {
result.metadata = Converter.c2p.asMetadata(event.metadata);
}
let matchingCellsSet: Set<string> | undefined;
if (event?.cellChanges !== undefined && event.cellChanges.length > 0) {
const data: vscode.NotebookCell[] = [];
// Only consider the new matching cells.
matchingCellsSet = new Set(matchingCells.map(cell => cell.document.uri.toString()));
for (const cellChange of event.cellChanges) {
if (matchingCellsSet.has(cellChange.cell.document.uri.toString()) && (cellChange.executionSummary !== undefined || cellChange.metadata !== undefined)) {
data.push(cellChange.cell);
}
}
if (data.length > 0) {
result.cells = result.cells ?? {};
result.cells.data = data;
}
}
if (((event?.contentChanges !== undefined && event.contentChanges.length > 0) || event === undefined) && syncInfo !== undefined && matchingCells !== undefined) {
// We still have matching cells. Check if the cell changes
// affect the notebook on the server side.
const oldCells = syncInfo.cells;
const newCells = matchingCells;
// meta data changes are reported using on the cell itself. So we can ignore comparing
// it which has a positive effect on performance.
const diff = $NotebookCell.computeDiff(oldCells, newCells, false);
let addedCells: Map<string, vscode.NotebookCell> | undefined;
let removedCells: Map<string, vscode.NotebookCell> | undefined;
if (diff !== undefined) {
addedCells = diff.cells === undefined
? new Map()
: new Map(diff.cells.map(cell => [cell.document.uri.toString(), cell]));
removedCells = diff.deleteCount === 0
? new Map()
: new Map(oldCells.slice(diff.start, diff.start + diff.deleteCount).map(cell => [cell.document.uri.toString(), cell]));
// Remove the onces that got deleted and inserted again.
for (const key of Array.from(removedCells.keys())) {
if (addedCells.has(key)) {
removedCells.delete(key);
addedCells.delete(key);
}
}
result.cells = result.cells ?? {};
type structure = Required<Required<Required<VNotebookDocumentChangeEvent>['cells']>['structure']>;
const didOpen: structure['didOpen'] = [];
const didClose: structure['didClose'] = [];
if (addedCells.size > 0 || removedCells.size > 0) {
for (const cell of addedCells.values()) {
didOpen.push(cell);
}
for (const cell of removedCells.values()) {
didClose.push(cell);
}
}
result.cells.structure = {
array: diff,
didOpen,
didClose
};
}
}
// The notebook is a property as well.
return Object.keys(result).length > 1 ? result : undefined;
}
private getMatchingCells(notebookDocument: vscode.NotebookDocument, cells: vscode.NotebookCell[] = notebookDocument.getCells()): vscode.NotebookCell[] | undefined {
if (this.options.notebookSelector === undefined) {
return undefined;
}
for (const item of this.options.notebookSelector) {
if (item.notebook === undefined || $NotebookDocumentFilter.matchNotebook(item.notebook, notebookDocument)) {
const filtered = this.filterCells(notebookDocument, cells, item.cells);
return filtered.length === 0 ? undefined : filtered;
}
}
return undefined;
}
private getMatchingCellsFromEvent(notebookDocument: vscode.NotebookDocument, syncInfo: SyncInfo, event: vscode.NotebookDocumentChangeEvent): vscode.NotebookCell[] | undefined {
if (this.options.notebookSelector === undefined) {
return undefined;
}
let selector: NotebookDocumentFilterWithNotebook | NotebookDocumentFilterWithCells | undefined;
for (const item of this.options.notebookSelector) {
if (item.notebook === undefined || $NotebookDocumentFilter.matchNotebook(item.notebook, notebookDocument)) {
selector = item;
break;
}
}
if (selector === undefined) {
return undefined;
}
if ((event.cellChanges === undefined || event.cellChanges.length === 0) && (event.contentChanges === undefined || event.contentChanges.length === 0)) {
return syncInfo.cells;
}
let cells: Set<string> | undefined;
if (event.cellChanges !== undefined && event.cellChanges.length > 0) {
const changedCells = event.cellChanges.map(item => item.cell);
const filtered = this.filterCells(notebookDocument, changedCells, selector.cells);
if (filtered.length !== changedCells.length) {
cells = new Set(syncInfo.uris);
for (const cell of changedCells) {
cells.delete(cell.document.uri.toString());
}
for (const cell of filtered) {
cells.add(cell.document.uri.toString());
}
}
}
if (event.contentChanges !== undefined && event.contentChanges.length > 0) {
if (cells === undefined) {
cells = new Set(syncInfo.uris);
}
for (const item of event.contentChanges) {
for (const cell of item.removedCells) {
cells.delete(cell.document.uri.toString());
}
const filtered = this.filterCells(notebookDocument, new Array(...item.addedCells), selector.cells);
for (const cell of filtered) {
cells.add(cell.document.uri.toString());
}
}
}
if (cells === undefined) {
return syncInfo.cells;
}
// Only return the cells that are still in the set, but keep the order
// as present in the current notebook.
const result: vscode.NotebookCell[] = [];
const current = notebookDocument.getCells();
for (const cell of current) {
if (cells.has(cell.document.uri.toString())) {
result.push(cell);
}
}
return result;
}
private getMatchingCellsFromSyncInfo(notebook: vscode.NotebookDocument): vscode.NotebookCell[] | undefined {
const syncInfo = this.getSyncInfo(notebook);
return syncInfo !== undefined ? syncInfo.cells : undefined;
}
private getMatchingCellsConsideringSyncInfo(notebook: vscode.NotebookDocument): vscode.NotebookCell[] | undefined {
const syncInfo = this.getSyncInfo(notebook);
return syncInfo !== undefined ? syncInfo.cells : this.getMatchingCells(notebook);
}
private mergeCells(notebookDocument: vscode.NotebookDocument, syncInfo: SyncInfo, cells: vscode.NotebookCell[]): vscode.NotebookCell[] {
const result: vscode.NotebookCell[] = [];
const merged = new Set(syncInfo.uris);
for (const cell of cells) {
merged.add(cell.document.uri.toString());
}
// Keep the cell order of the current notebook.
for (const cell of notebookDocument.getCells()) {
if (merged.has(cell.document.uri.toString())) {
result.push(cell);
}
}
return result;
}
private cellMatches(notebookDocument: vscode.NotebookDocument, cell: vscode.NotebookCell) {
const cells = this.getMatchingCells(notebookDocument, [cell]);
return cells !== undefined && cells[0] === cell;
}
private filterCells(notebookDocument: vscode.NotebookDocument, cells: vscode.NotebookCell[], cellSelector: undefined | { language: string }[]): vscode.NotebookCell[] {
const filtered = cellSelector !== undefined ? cells.filter((cell) => {
const cellLanguage = cell.document.languageId;
return cellSelector.some((filter => (filter.language === '*' || cellLanguage === filter.language)));
}) : cells;
return typeof this.client.clientOptions.notebookDocumentOptions?.filterCells === 'function'
? this.client.clientOptions.notebookDocumentOptions.filterCells(notebookDocument, filtered)
: filtered;
}
private getSyncInfo(notebook: vscode.NotebookDocument): SyncInfo | undefined {
return this.notebookSyncInfo.get(notebook.uri.toString());
}
}
export type $NotebookCellTextDocumentFilter = NotebookCellTextDocumentFilter & { sync: true };
export type NotebookDocumentProviderShape = {
onOpenNotificationSent: vscode.Event<vscode.NotebookDocument>;
onChangeNotificationSent: vscode.Event<VNotebookDocumentChangeEvent>;
onCloseNotificationSent: vscode.Event<vscode.NotebookDocument>;
onSaveNotificationSent: vscode.Event<vscode.NotebookDocument>;
getProvider(notebookCell: vscode.NotebookCell): NotebookDocumentSyncFeatureShape |undefined;
};
export class NotebookDocumentSyncFeature implements DynamicFeature<proto.NotebookDocumentSyncRegistrationOptions>, NotebookDocumentProviderShape {