@jupyterlab/lsp 4.0.0-alpha.19 → 4.0.0-alpha.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1285 @@
1
+ // Copyright (c) Jupyter Development Team.
2
+ // Distributed under the terms of the Modified BSD License.
3
+
4
+ import { IDisposable } from '@lumino/disposable';
5
+ import { IDocumentInfo } from '../ws-connection/types';
6
+ import { IPosition } from '../positioning';
7
+ import { CodeEditor } from '@jupyterlab/codeeditor';
8
+ import { ISignal, Signal } from '@lumino/signaling';
9
+
10
+ import { Document, ILSPCodeExtractorsManager } from '../tokens';
11
+ import { DocumentConnectionManager } from '../connection_manager';
12
+ import { IForeignCodeExtractor } from '../extractors/types';
13
+ import { LanguageIdentifier } from '../lsp';
14
+ import {
15
+ IEditorPosition,
16
+ IRootPosition,
17
+ ISourcePosition,
18
+ IVirtualPosition
19
+ } from '../positioning';
20
+ import { DefaultMap, untilReady } from '../utils';
21
+
22
+ type IRange = CodeEditor.IRange;
23
+
24
+ type language = string;
25
+
26
+ interface IVirtualLine {
27
+ /**
28
+ * Inspections for which document should be skipped for this virtual line?
29
+ */
30
+ skipInspect: Array<VirtualDocument.idPath>;
31
+
32
+ /**
33
+ * Where does the virtual line belongs to in the source document?
34
+ */
35
+ sourceLine: number | null;
36
+
37
+ /**
38
+ * The editor holding this virtual line
39
+ */
40
+ editor: Document.IEditor;
41
+ }
42
+
43
+ export type ForeignDocumentsMap = Map<IRange, Document.IVirtualDocumentBlock>;
44
+
45
+ interface ISourceLine {
46
+ /**
47
+ * Line corresponding to the block in the entire foreign document
48
+ */
49
+ virtualLine: number;
50
+
51
+ /**
52
+ * The CM editor associated with this virtual line.
53
+ */
54
+ editor: Document.IEditor;
55
+
56
+ /**
57
+ * Line in the CM editor corresponding to the virtual line.
58
+ */
59
+ editorLine: number;
60
+
61
+ /**
62
+ * Shift of the virtual line
63
+ */
64
+ editorShift: CodeEditor.IPosition;
65
+
66
+ /**
67
+ * Everything which is not in the range of foreign documents belongs to the host.
68
+ */
69
+ foreignDocumentsMap: ForeignDocumentsMap;
70
+ }
71
+
72
+ /**
73
+ * Check if given position is within range.
74
+ * Both start and end are inclusive.
75
+ * @param position
76
+ * @param range
77
+ */
78
+ export function isWithinRange(
79
+ position: CodeEditor.IPosition,
80
+ range: CodeEditor.IRange
81
+ ): boolean {
82
+ if (range.start.line === range.end.line) {
83
+ return (
84
+ position.line === range.start.line &&
85
+ position.column >= range.start.column &&
86
+ position.column <= range.end.column
87
+ );
88
+ }
89
+
90
+ return (
91
+ (position.line === range.start.line &&
92
+ position.column >= range.start.column &&
93
+ position.line < range.end.line) ||
94
+ (position.line > range.start.line &&
95
+ position.column <= range.end.column &&
96
+ position.line === range.end.line) ||
97
+ (position.line > range.start.line && position.line < range.end.line)
98
+ );
99
+ }
100
+
101
+ /**
102
+ * A virtual implementation of IDocumentInfo
103
+ */
104
+ export class VirtualDocumentInfo implements IDocumentInfo {
105
+ /**
106
+ * Creates an instance of VirtualDocumentInfo.
107
+ * @param document - the virtual document need to
108
+ * be wrapped.
109
+ */
110
+ constructor(document: VirtualDocument) {
111
+ this._document = document;
112
+ }
113
+
114
+ /**
115
+ * Current version of the virtual document.
116
+ */
117
+ version = 0;
118
+
119
+ /**
120
+ * Get the text content of the virtual document.
121
+ */
122
+ get text(): string {
123
+ return this._document.value;
124
+ }
125
+
126
+ /**
127
+ * Get the uri of the virtual document, if the document is not available,
128
+ * it returns an empty string, users need to check for the length of returned
129
+ * value before using it.
130
+ */
131
+ get uri(): string {
132
+ const uris = DocumentConnectionManager.solveUris(
133
+ this._document,
134
+ this.languageId
135
+ );
136
+ if (!uris) {
137
+ return '';
138
+ }
139
+ return uris.document;
140
+ }
141
+
142
+ /**
143
+ * Get the language identifier of the document.
144
+ */
145
+ get languageId(): string {
146
+ return this._document.language;
147
+ }
148
+
149
+ /**
150
+ * The wrapped virtual document.
151
+ */
152
+ private _document: VirtualDocument;
153
+ }
154
+
155
+ export namespace VirtualDocument {
156
+ export interface IOptions {
157
+ /**
158
+ * The language identifier of the document.
159
+ */
160
+ language: LanguageIdentifier;
161
+
162
+ /**
163
+ * The foreign code extractor manager token.
164
+ */
165
+ foreignCodeExtractors: ILSPCodeExtractorsManager;
166
+
167
+ /**
168
+ * Path to the document.
169
+ */
170
+ path: string;
171
+
172
+ /**
173
+ * File extension of the document.
174
+ */
175
+ fileExtension: string | undefined;
176
+
177
+ /**
178
+ * Notebooks or any other aggregates of documents are not supported
179
+ * by the LSP specification, and we need to make appropriate
180
+ * adjustments for them, pretending they are simple files
181
+ * so that the LSP servers do not refuse to cooperate.
182
+ */
183
+ hasLspSupportedFile: boolean;
184
+
185
+ /**
186
+ * Being standalone is relevant to foreign documents
187
+ * and defines whether following chunks of code in the same
188
+ * language should be appended to this document (false, not standalone)
189
+ * or should be considered separate documents (true, standalone)
190
+ *
191
+ */
192
+ standalone?: boolean;
193
+
194
+ /**
195
+ * Parent of the current virtual document.
196
+ */
197
+ parent?: VirtualDocument;
198
+ }
199
+ }
200
+
201
+ /**
202
+ *
203
+ * A notebook can hold one or more virtual documents; there is always one,
204
+ * "root" document, corresponding to the language of the kernel. All other
205
+ * virtual documents are extracted out of the notebook, based on magics,
206
+ * or other syntax constructs, depending on the kernel language.
207
+ *
208
+ * Virtual documents represent the underlying code in a single language,
209
+ * which has been parsed excluding interactive kernel commands (magics)
210
+ * which could be misunderstood by the specific LSP server.
211
+ *
212
+ * VirtualDocument has no awareness of the notebook or editor it lives in,
213
+ * however it is able to transform its content back to the notebook space,
214
+ * as it keeps editor coordinates for each virtual line.
215
+ *
216
+ * The notebook/editor aware transformations are preferred to be placed in
217
+ * VirtualEditor descendants rather than here.
218
+ *
219
+ * No dependency on editor implementation (such as CodeMirrorEditor)
220
+ * is allowed for VirtualEditor.
221
+ */
222
+ export class VirtualDocument implements IDisposable {
223
+ constructor(options: VirtualDocument.IOptions) {
224
+ this.options = options;
225
+ this.path = this.options.path;
226
+ this.fileExtension = options.fileExtension;
227
+ this.hasLspSupportedFile = options.hasLspSupportedFile;
228
+ this.parent = options.parent;
229
+ this.language = options.language;
230
+
231
+ this.virtualLines = new Map();
232
+ this.sourceLines = new Map();
233
+ this.foreignDocuments = new Map();
234
+ this._editorToSourceLine = new Map();
235
+ this._foreignCodeExtractors = options.foreignCodeExtractors;
236
+ this.standalone = options.standalone || false;
237
+ this.instanceId = VirtualDocument.instancesCount;
238
+ VirtualDocument.instancesCount += 1;
239
+ this.unusedStandaloneDocuments = new DefaultMap(
240
+ () => new Array<VirtualDocument>()
241
+ );
242
+ this._remainingLifetime = 6;
243
+
244
+ this.unusedDocuments = new Set();
245
+ this.documentInfo = new VirtualDocumentInfo(this);
246
+ this.updateManager = new UpdateManager(this);
247
+ this.updateManager.updateBegan.connect(this._updateBeganSlot, this);
248
+ this.updateManager.blockAdded.connect(this._blockAddedSlot, this);
249
+ this.updateManager.updateFinished.connect(this._updateFinishedSlot, this);
250
+ this.clear();
251
+ }
252
+
253
+ /**
254
+ * Convert from code editor position into code mirror position.
255
+ */
256
+ static ceToCm(position: CodeEditor.IPosition): IPosition {
257
+ return { line: position.line, ch: position.column };
258
+ }
259
+
260
+ /**
261
+ * Number of blank lines appended to the virtual document between
262
+ * each cell.
263
+ */
264
+ blankLinesBetweenCells: number = 2;
265
+
266
+ /**
267
+ * Line number of the last line in the real document.
268
+ */
269
+ lastSourceLine: number;
270
+
271
+ /**
272
+ * Line number of the last line in the virtual document.
273
+ */
274
+ lastVirtualLine: number;
275
+
276
+ /**
277
+ * the remote document uri, version and other server-related info
278
+ */
279
+ documentInfo: IDocumentInfo;
280
+
281
+ /**
282
+ * Parent of the current virtual document.
283
+ */
284
+ parent?: VirtualDocument | null;
285
+
286
+ /**
287
+ * The language identifier of the document.
288
+ */
289
+ readonly language: string;
290
+
291
+ /**
292
+ * Being standalone is relevant to foreign documents
293
+ * and defines whether following chunks of code in the same
294
+ * language should be appended to this document (false, not standalone)
295
+ * or should be considered separate documents (true, standalone)
296
+ */
297
+ readonly standalone: boolean;
298
+
299
+ /**
300
+ * Path to the document.
301
+ */
302
+ readonly path: string;
303
+
304
+ /**
305
+ * File extension of the document.
306
+ */
307
+ readonly fileExtension: string | undefined;
308
+
309
+ /**
310
+ * Notebooks or any other aggregates of documents are not supported
311
+ * by the LSP specification, and we need to make appropriate
312
+ * adjustments for them, pretending they are simple files
313
+ * so that the LSP servers do not refuse to cooperate.
314
+ */
315
+ readonly hasLspSupportedFile: boolean;
316
+
317
+ /**
318
+ * Map holding the children `VirtualDocument` .
319
+ */
320
+ readonly foreignDocuments: Map<VirtualDocument.virtualId, VirtualDocument>;
321
+
322
+ /**
323
+ * The update manager object.
324
+ */
325
+ readonly updateManager: UpdateManager;
326
+
327
+ /**
328
+ * Unique id of the virtual document.
329
+ */
330
+ readonly instanceId: number;
331
+
332
+ /**
333
+ * Test whether the document is disposed.
334
+ */
335
+ get isDisposed(): boolean {
336
+ return this._isDisposed;
337
+ }
338
+
339
+ /**
340
+ * Signal emitted when the foreign document is closed
341
+ */
342
+ get foreignDocumentClosed(): ISignal<
343
+ VirtualDocument,
344
+ Document.IForeignContext
345
+ > {
346
+ return this._foreignDocumentClosed;
347
+ }
348
+
349
+ /**
350
+ * Signal emitted when the foreign document is opened
351
+ */
352
+ get foreignDocumentOpened(): ISignal<
353
+ VirtualDocument,
354
+ Document.IForeignContext
355
+ > {
356
+ return this._foreignDocumentOpened;
357
+ }
358
+
359
+ /**
360
+ * Signal emitted when the foreign document is changed
361
+ */
362
+ get changed(): ISignal<VirtualDocument, VirtualDocument> {
363
+ return this._changed;
364
+ }
365
+
366
+ /**
367
+ * Id of the virtual document.
368
+ */
369
+ get virtualId(): VirtualDocument.virtualId {
370
+ // for easier debugging, the language information is included in the ID:
371
+ return this.standalone
372
+ ? this.instanceId + '(' + this.language + ')'
373
+ : this.language;
374
+ }
375
+
376
+ /**
377
+ * Return the ancestry to this document.
378
+ */
379
+ get ancestry(): Array<VirtualDocument> {
380
+ if (!this.parent) {
381
+ return [this];
382
+ }
383
+ return this.parent.ancestry.concat([this]);
384
+ }
385
+
386
+ /**
387
+ * Return the id path to the virtual document.
388
+ */
389
+ get idPath(): VirtualDocument.idPath {
390
+ if (!this.parent) {
391
+ return this.virtualId;
392
+ }
393
+ return this.parent.idPath + '-' + this.virtualId;
394
+ }
395
+
396
+ /**
397
+ * Get the uri of the virtual document.
398
+ */
399
+ get uri(): VirtualDocument.uri {
400
+ const encodedPath = encodeURI(this.path);
401
+ if (!this.parent) {
402
+ return encodedPath;
403
+ }
404
+ return encodedPath + '.' + this.idPath + '.' + this.fileExtension;
405
+ }
406
+
407
+ /**
408
+ * Get the text value of the document
409
+ */
410
+ get value(): string {
411
+ let linesPadding = '\n'.repeat(this.blankLinesBetweenCells);
412
+ return this.lineBlocks.join(linesPadding);
413
+ }
414
+
415
+ /**
416
+ * Get the last line in the virtual document
417
+ */
418
+ get lastLine(): string {
419
+ const linesInLastBlock =
420
+ this.lineBlocks[this.lineBlocks.length - 1].split('\n');
421
+ return linesInLastBlock[linesInLastBlock.length - 1];
422
+ }
423
+
424
+ /**
425
+ * Get the root document of current virtual document.
426
+ */
427
+ get root(): VirtualDocument {
428
+ return this.parent ? this.parent.root : this;
429
+ }
430
+
431
+ /**
432
+ * Dispose the virtual document.
433
+ */
434
+ dispose(): void {
435
+ if (this._isDisposed) {
436
+ return;
437
+ }
438
+ this._isDisposed = true;
439
+
440
+ this.parent = null;
441
+
442
+ this.closeAllForeignDocuments();
443
+
444
+ this.updateManager.dispose();
445
+ // clear all the maps
446
+
447
+ this.foreignDocuments.clear();
448
+ this.sourceLines.clear();
449
+ this.unusedDocuments.clear();
450
+ this.unusedStandaloneDocuments.clear();
451
+ this.virtualLines.clear();
452
+
453
+ // just to be sure - if anything is accessed after disposal (it should not) we
454
+ // will get altered by errors in the console AND this will limit memory leaks
455
+
456
+ this.documentInfo = null as any;
457
+ this.lineBlocks = null as any;
458
+
459
+ Signal.clearData(this);
460
+ }
461
+
462
+ /**
463
+ * Clear the virtual document and all related stuffs
464
+ */
465
+ clear(): void {
466
+ for (let document of this.foreignDocuments.values()) {
467
+ document.clear();
468
+ }
469
+
470
+ // TODO - deep clear (assure that there is no memory leak)
471
+ this.unusedStandaloneDocuments.clear();
472
+
473
+ this.unusedDocuments = new Set();
474
+ this.virtualLines.clear();
475
+ this.sourceLines.clear();
476
+ this.lastVirtualLine = 0;
477
+ this.lastSourceLine = 0;
478
+ this.lineBlocks = [];
479
+ }
480
+
481
+ /**
482
+ * Get the virtual document from the cursor position of the source
483
+ * document
484
+ * @param position - position in source document
485
+ */
486
+ documentAtSourcePosition(position: ISourcePosition): VirtualDocument {
487
+ let sourceLine = this.sourceLines.get(position.line);
488
+
489
+ if (!sourceLine) {
490
+ return this;
491
+ }
492
+
493
+ let sourcePositionCe: CodeEditor.IPosition = {
494
+ line: sourceLine.editorLine,
495
+ column: position.ch
496
+ };
497
+
498
+ for (let [
499
+ range,
500
+ { virtualDocument: document }
501
+ ] of sourceLine.foreignDocumentsMap) {
502
+ if (isWithinRange(sourcePositionCe, range)) {
503
+ let sourcePositionCm = {
504
+ line: sourcePositionCe.line - range.start.line,
505
+ ch: sourcePositionCe.column - range.start.column
506
+ };
507
+
508
+ return document.documentAtSourcePosition(
509
+ sourcePositionCm as ISourcePosition
510
+ );
511
+ }
512
+ }
513
+
514
+ return this;
515
+ }
516
+
517
+ /**
518
+ * Detect if the input source position is belong to the current
519
+ * virtual document.
520
+ *
521
+ * @param sourcePosition - position in the source document
522
+ */
523
+ isWithinForeign(sourcePosition: ISourcePosition): boolean {
524
+ let sourceLine = this.sourceLines.get(sourcePosition.line)!;
525
+
526
+ let sourcePositionCe: CodeEditor.IPosition = {
527
+ line: sourceLine.editorLine,
528
+ column: sourcePosition.ch
529
+ };
530
+ for (let [range] of sourceLine.foreignDocumentsMap) {
531
+ if (isWithinRange(sourcePositionCe, range)) {
532
+ return true;
533
+ }
534
+ }
535
+ return false;
536
+ }
537
+
538
+ /**
539
+ * Compute the position in root document from the position of
540
+ * a child editor.
541
+ *
542
+ * @param editor - the active editor.
543
+ * @param position - position in the active editor.
544
+ */
545
+ transformFromEditorToRoot(
546
+ editor: Document.IEditor,
547
+ position: IEditorPosition
548
+ ): IRootPosition | null {
549
+ if (!this._editorToSourceLine.has(editor)) {
550
+ console.log('Editor not found in _editorToSourceLine map');
551
+ return null;
552
+ }
553
+ let shift = this._editorToSourceLine.get(editor)!;
554
+ return {
555
+ ...(position as IPosition),
556
+ line: position.line + shift
557
+ } as IRootPosition;
558
+ }
559
+
560
+ /**
561
+ * Compute the position in the virtual document from the position
562
+ * if the source document.
563
+ *
564
+ * @param sourcePosition - position in source document
565
+ */
566
+ virtualPositionAtDocument(sourcePosition: ISourcePosition): IVirtualPosition {
567
+ let sourceLine = this.sourceLines.get(sourcePosition.line);
568
+ if (sourceLine == null) {
569
+ throw new Error('Source line not mapped to virtual position');
570
+ }
571
+ let virtualLine = sourceLine.virtualLine;
572
+
573
+ // position inside the cell (block)
574
+ let sourcePositionCe: CodeEditor.IPosition = {
575
+ line: sourceLine.editorLine,
576
+ column: sourcePosition.ch
577
+ };
578
+
579
+ for (let [range, content] of sourceLine.foreignDocumentsMap) {
580
+ const { virtualLine, virtualDocument: document } = content;
581
+ if (isWithinRange(sourcePositionCe, range)) {
582
+ // position inside the foreign document block
583
+ let sourcePositionCm = {
584
+ line: sourcePositionCe.line - range.start.line,
585
+ ch: sourcePositionCe.column - range.start.column
586
+ };
587
+ if (document.isWithinForeign(sourcePositionCm as ISourcePosition)) {
588
+ return this.virtualPositionAtDocument(
589
+ sourcePositionCm as ISourcePosition
590
+ );
591
+ } else {
592
+ // where in this block in the entire foreign document?
593
+ sourcePositionCm.line += virtualLine;
594
+ return sourcePositionCm as IVirtualPosition;
595
+ }
596
+ }
597
+ }
598
+
599
+ return {
600
+ ch: sourcePosition.ch,
601
+ line: virtualLine
602
+ } as IVirtualPosition;
603
+ }
604
+
605
+ /**
606
+ * Append a code block to the end of the virtual document.
607
+ *
608
+ * @param block - block to be appended
609
+ * @param editorShift - position shift in source
610
+ * document
611
+ * @param [virtualShift] - position shift in
612
+ * virtual document.
613
+ */
614
+ appendCodeBlock(
615
+ block: Document.ICodeBlockOptions,
616
+ editorShift: CodeEditor.IPosition = { line: 0, column: 0 },
617
+ virtualShift?: CodeEditor.IPosition
618
+ ): void {
619
+ let cellCode = block.value;
620
+ let ceEditor = block.ceEditor;
621
+
622
+ if (this.isDisposed) {
623
+ console.warn('Cannot append code block: document disposed');
624
+ return;
625
+ }
626
+ let sourceCellLines = cellCode.split('\n');
627
+ let { lines, foreignDocumentsMap } = this.prepareCodeBlock(
628
+ block,
629
+ editorShift
630
+ );
631
+
632
+ for (let i = 0; i < lines.length; i++) {
633
+ this.virtualLines.set(this.lastVirtualLine + i, {
634
+ skipInspect: [],
635
+ editor: ceEditor,
636
+ // TODO this is incorrect, wont work if something was extracted
637
+ sourceLine: this.lastSourceLine + i
638
+ });
639
+ }
640
+ for (let i = 0; i < sourceCellLines.length; i++) {
641
+ this.sourceLines.set(this.lastSourceLine + i, {
642
+ editorLine: i,
643
+ editorShift: {
644
+ line: editorShift.line - (virtualShift?.line || 0),
645
+ column: i === 0 ? editorShift.column - (virtualShift?.column || 0) : 0
646
+ },
647
+ // TODO: move those to a new abstraction layer (DocumentBlock class)
648
+ editor: ceEditor,
649
+ foreignDocumentsMap,
650
+ // TODO this is incorrect, wont work if something was extracted
651
+ virtualLine: this.lastVirtualLine + i
652
+ });
653
+ }
654
+
655
+ this.lastVirtualLine += lines.length;
656
+
657
+ // one empty line is necessary to separate code blocks, next 'n' lines are to silence linters;
658
+ // the final cell does not get the additional lines (thanks to the use of join, see below)
659
+
660
+ this.lineBlocks.push(lines.join('\n') + '\n');
661
+
662
+ // adding the virtual lines for the blank lines
663
+ for (let i = 0; i < this.blankLinesBetweenCells; i++) {
664
+ this.virtualLines.set(this.lastVirtualLine + i, {
665
+ skipInspect: [this.idPath],
666
+ editor: ceEditor,
667
+ sourceLine: null
668
+ });
669
+ }
670
+
671
+ this.lastVirtualLine += this.blankLinesBetweenCells;
672
+ this.lastSourceLine += sourceCellLines.length;
673
+ }
674
+
675
+ /**
676
+ * Extract a code block into list of string in supported language and
677
+ * a map of foreign document if any.
678
+ * @param block - block to be appended
679
+ * @param editorShift - position shift in source document
680
+ */
681
+ prepareCodeBlock(
682
+ block: Document.ICodeBlockOptions,
683
+ editorShift: CodeEditor.IPosition = { line: 0, column: 0 }
684
+ ): {
685
+ lines: string[];
686
+ foreignDocumentsMap: Map<CodeEditor.IRange, Document.IVirtualDocumentBlock>;
687
+ } {
688
+ let { cellCodeKept, foreignDocumentsMap } = this.extractForeignCode(
689
+ block,
690
+ editorShift
691
+ );
692
+ let lines = cellCodeKept.split('\n');
693
+ return { lines, foreignDocumentsMap };
694
+ }
695
+
696
+ /**
697
+ * Extract the foreign code from input block by using the registered
698
+ * extractors.
699
+ * @param block - block to be appended
700
+ * @param editorShift - position shift in source document
701
+ */
702
+ extractForeignCode(
703
+ block: Document.ICodeBlockOptions,
704
+ editorShift: CodeEditor.IPosition
705
+ ): {
706
+ cellCodeKept: string;
707
+ foreignDocumentsMap: Map<CodeEditor.IRange, Document.IVirtualDocumentBlock>;
708
+ } {
709
+ let foreignDocumentsMap = new Map<
710
+ CodeEditor.IRange,
711
+ Document.IVirtualDocumentBlock
712
+ >();
713
+
714
+ let cellCode = block.value;
715
+ const extractorsForAnyLang = this._foreignCodeExtractors.getExtractors(
716
+ block.type,
717
+ null
718
+ );
719
+ const extractorsForCurrentLang = this._foreignCodeExtractors.getExtractors(
720
+ block.type,
721
+ this.language
722
+ );
723
+
724
+ for (let extractor of [
725
+ ...extractorsForAnyLang,
726
+ ...extractorsForCurrentLang
727
+ ]) {
728
+ if (!extractor.hasForeignCode(cellCode, block.type)) {
729
+ continue;
730
+ }
731
+
732
+ let results = extractor.extractForeignCode(cellCode);
733
+
734
+ let keptCellCode = '';
735
+
736
+ for (let result of results) {
737
+ if (result.foreignCode !== null) {
738
+ // result.range should only be null if result.foregin_code is null
739
+ if (result.range === null) {
740
+ console.log(
741
+ 'Failure in foreign code extraction: `range` is null but `foreign_code` is not!'
742
+ );
743
+ continue;
744
+ }
745
+ let foreignDocument = this.chooseForeignDocument(extractor);
746
+ foreignDocumentsMap.set(result.range, {
747
+ virtualLine: foreignDocument.lastVirtualLine,
748
+ virtualDocument: foreignDocument,
749
+ editor: block.ceEditor
750
+ });
751
+ let foreignShift = {
752
+ line: editorShift.line + result.range.start.line,
753
+ column: editorShift.column + result.range.start.column
754
+ };
755
+ foreignDocument.appendCodeBlock(
756
+ {
757
+ value: result.foreignCode,
758
+ ceEditor: block.ceEditor,
759
+ type: 'code'
760
+ },
761
+ foreignShift,
762
+ result.virtualShift!
763
+ );
764
+ }
765
+ if (result.hostCode != null) {
766
+ keptCellCode += result.hostCode;
767
+ }
768
+ }
769
+ // not breaking - many extractors are allowed to process the code, one after each other
770
+ // (think JS and CSS in HTML, or %R inside of %%timeit).
771
+
772
+ cellCode = keptCellCode;
773
+ }
774
+
775
+ return { cellCodeKept: cellCode, foreignDocumentsMap };
776
+ }
777
+
778
+ /**
779
+ * Close a foreign document and disconnect all associated signals
780
+ */
781
+ closeForeign(document: VirtualDocument): void {
782
+ this._foreignDocumentClosed.emit({
783
+ foreignDocument: document,
784
+ parentHost: this
785
+ });
786
+ // remove it from foreign documents list
787
+ this.foreignDocuments.delete(document.virtualId);
788
+ // and delete the documents within it
789
+ document.closeAllForeignDocuments();
790
+
791
+ document.foreignDocumentClosed.disconnect(this.forwardClosedSignal, this);
792
+ document.foreignDocumentOpened.disconnect(this.forwardOpenedSignal, this);
793
+ document.dispose();
794
+ }
795
+
796
+ /**
797
+ * Close all foreign documents.
798
+ */
799
+ closeAllForeignDocuments(): void {
800
+ for (let document of this.foreignDocuments.values()) {
801
+ this.closeForeign(document);
802
+ }
803
+ }
804
+
805
+ /**
806
+ * Close all expired documents.
807
+ */
808
+ closeExpiredDocuments(): void {
809
+ for (let document of this.unusedDocuments.values()) {
810
+ document.remainingLifetime -= 1;
811
+ if (document.remainingLifetime <= 0) {
812
+ document.dispose();
813
+ }
814
+ }
815
+ }
816
+
817
+ /**
818
+ * Transform the position of the source to the editor
819
+ * position.
820
+ *
821
+ * @param pos - position in the source document
822
+ * @return position in the editor.
823
+ */
824
+ transformSourceToEditor(pos: ISourcePosition): IEditorPosition {
825
+ let sourceLine = this.sourceLines.get(pos.line)!;
826
+ let editorLine = sourceLine.editorLine;
827
+ let editorShift = sourceLine.editorShift;
828
+ return {
829
+ // only shift column in the line beginning the virtual document (first list of the editor in cell magics, but might be any line of editor in line magics!)
830
+ ch: pos.ch + (editorLine === 0 ? editorShift.column : 0),
831
+ line: editorLine + editorShift.line
832
+ // TODO or:
833
+ // line: pos.line + editor_shift.line - this.first_line_of_the_block(editor)
834
+ } as IEditorPosition;
835
+ }
836
+
837
+ /**
838
+ * Transform the position in the virtual document to the
839
+ * editor position.
840
+ * Can be null because some lines are added as padding/anchors
841
+ * to the virtual document and those do not exist in the source document
842
+ * and thus they are absent in the editor.
843
+ */
844
+ transformVirtualToEditor(
845
+ virtualPosition: IVirtualPosition
846
+ ): IEditorPosition | null {
847
+ let sourcePosition = this.transformVirtualToSource(virtualPosition);
848
+ if (sourcePosition == null) {
849
+ return null;
850
+ }
851
+ return this.transformSourceToEditor(sourcePosition);
852
+ }
853
+
854
+ /**
855
+ * Transform the position in the virtual document to the source.
856
+ * Can be null because some lines are added as padding/anchors
857
+ * to the virtual document and those do not exist in the source document.
858
+ */
859
+ transformVirtualToSource(position: IVirtualPosition): ISourcePosition | null {
860
+ const line = this.virtualLines.get(position.line)!.sourceLine;
861
+ if (line == null) {
862
+ return null;
863
+ }
864
+ return {
865
+ ch: position.ch,
866
+ line: line
867
+ } as ISourcePosition;
868
+ }
869
+
870
+ /**
871
+ * Get the corresponding editor of the virtual line.
872
+ */
873
+ getEditorAtVirtualLine(pos: IVirtualPosition): Document.IEditor {
874
+ let line = pos.line;
875
+ // tolerate overshot by one (the hanging blank line at the end)
876
+ if (!this.virtualLines.has(line)) {
877
+ line -= 1;
878
+ }
879
+ return this.virtualLines.get(line)!.editor;
880
+ }
881
+
882
+ /**
883
+ * Get the corresponding editor of the source line
884
+ */
885
+ getEditorAtSourceLine(pos: ISourcePosition): Document.IEditor {
886
+ return this.sourceLines.get(pos.line)!.editor;
887
+ }
888
+
889
+ /**
890
+ * Recursively emits changed signal from the document or any descendant foreign document.
891
+ */
892
+ maybeEmitChanged(): void {
893
+ if (this.value !== this.previousValue) {
894
+ this._changed.emit(this);
895
+ }
896
+ this.previousValue = this.value;
897
+ for (let document of this.foreignDocuments.values()) {
898
+ document.maybeEmitChanged();
899
+ }
900
+ }
901
+
902
+ /**
903
+ * When this counter goes down to 0, the document will be destroyed and the associated connection will be closed;
904
+ * This is meant to reduce the number of open connections when a a foreign code snippet was removed from the document.
905
+ *
906
+ * Note: top level virtual documents are currently immortal (unless killed by other means); it might be worth
907
+ * implementing culling of unused documents, but if and only if JupyterLab will also implement culling of
908
+ * idle kernels - otherwise the user experience could be a bit inconsistent, and we would need to invent our own rules.
909
+ */
910
+ protected get remainingLifetime(): number {
911
+ if (!this.parent) {
912
+ return Infinity;
913
+ }
914
+ return this._remainingLifetime;
915
+ }
916
+
917
+ protected set remainingLifetime(value: number) {
918
+ if (this.parent) {
919
+ this._remainingLifetime = value;
920
+ }
921
+ }
922
+
923
+ /**
924
+ * Virtual lines keep all the lines present in the document AND extracted to the foreign document.
925
+ */
926
+ protected virtualLines: Map<number, IVirtualLine>;
927
+ protected sourceLines: Map<number, ISourceLine>;
928
+ protected lineBlocks: Array<string>;
929
+
930
+ protected unusedDocuments: Set<VirtualDocument>;
931
+ protected unusedStandaloneDocuments: DefaultMap<
932
+ language,
933
+ Array<VirtualDocument>
934
+ >;
935
+
936
+ private _isDisposed = false;
937
+ private _remainingLifetime: number;
938
+ private _editorToSourceLine: Map<Document.IEditor, number>;
939
+ private _editorToSourceLineNew: Map<Document.IEditor, number>;
940
+ private _foreignCodeExtractors: ILSPCodeExtractorsManager;
941
+ private previousValue: string;
942
+ private static instancesCount = 0;
943
+ private readonly options: VirtualDocument.IOptions;
944
+
945
+ /**
946
+ * Get the foreign document that can be opened with the input extractor.
947
+ */
948
+ private chooseForeignDocument(
949
+ extractor: IForeignCodeExtractor
950
+ ): VirtualDocument {
951
+ let foreignDocument: VirtualDocument;
952
+ // if not standalone, try to append to existing document
953
+ let foreignExists = this.foreignDocuments.has(extractor.language);
954
+ if (!extractor.standalone && foreignExists) {
955
+ foreignDocument = this.foreignDocuments.get(extractor.language)!;
956
+ } else {
957
+ // if (previous document does not exists) or (extractor produces standalone documents
958
+ // and no old standalone document could be reused): create a new document
959
+ foreignDocument = this.openForeign(
960
+ extractor.language,
961
+ extractor.standalone,
962
+ extractor.fileExtension
963
+ );
964
+ }
965
+ return foreignDocument;
966
+ }
967
+
968
+ /**
969
+ * Create a foreign document from input language and file extension.
970
+ *
971
+ * @param language - the required language
972
+ * @param standalone - the document type is supported natively by LSP?
973
+ * @param fileExtension - File extension.
974
+ */
975
+ private openForeign(
976
+ language: language,
977
+ standalone: boolean,
978
+ fileExtension: string
979
+ ): VirtualDocument {
980
+ let document = new VirtualDocument({
981
+ ...this.options,
982
+ parent: this,
983
+ standalone: standalone,
984
+ fileExtension: fileExtension,
985
+ language: language
986
+ });
987
+ const context: Document.IForeignContext = {
988
+ foreignDocument: document,
989
+ parentHost: this
990
+ };
991
+ this._foreignDocumentOpened.emit(context);
992
+ // pass through any future signals
993
+ document.foreignDocumentClosed.connect(this.forwardClosedSignal, this);
994
+ document.foreignDocumentOpened.connect(this.forwardOpenedSignal, this);
995
+
996
+ this.foreignDocuments.set(document.virtualId, document);
997
+
998
+ return document;
999
+ }
1000
+
1001
+ /**
1002
+ * Forward the closed signal from the foreign document to the host document's
1003
+ * signal
1004
+ */
1005
+ private forwardClosedSignal(
1006
+ host: VirtualDocument,
1007
+ context: Document.IForeignContext
1008
+ ) {
1009
+ this._foreignDocumentClosed.emit(context);
1010
+ }
1011
+
1012
+ /**
1013
+ * Forward the opened signal from the foreign document to the host document's
1014
+ * signal
1015
+ */
1016
+ private forwardOpenedSignal(
1017
+ host: VirtualDocument,
1018
+ context: Document.IForeignContext
1019
+ ) {
1020
+ this._foreignDocumentOpened.emit(context);
1021
+ }
1022
+
1023
+ /**
1024
+ * Slot of the `updateBegan` signal.
1025
+ */
1026
+ private _updateBeganSlot(): void {
1027
+ this._editorToSourceLineNew = new Map();
1028
+ }
1029
+
1030
+ /**
1031
+ * Slot of the `blockAdded` signal.
1032
+ */
1033
+ private _blockAddedSlot(
1034
+ updateManager: UpdateManager,
1035
+ blockData: IBlockAddedInfo
1036
+ ): void {
1037
+ this._editorToSourceLineNew.set(
1038
+ blockData.block.ceEditor,
1039
+ blockData.virtualDocument.lastSourceLine
1040
+ );
1041
+ }
1042
+
1043
+ /**
1044
+ * Slot of the `updateFinished` signal.
1045
+ */
1046
+ private _updateFinishedSlot(): void {
1047
+ this._editorToSourceLine = this._editorToSourceLineNew;
1048
+ }
1049
+
1050
+ private _foreignDocumentClosed = new Signal<
1051
+ VirtualDocument,
1052
+ Document.IForeignContext
1053
+ >(this);
1054
+ private _foreignDocumentOpened = new Signal<
1055
+ VirtualDocument,
1056
+ Document.IForeignContext
1057
+ >(this);
1058
+ private _changed = new Signal<VirtualDocument, VirtualDocument>(this);
1059
+ }
1060
+
1061
+ export namespace VirtualDocument {
1062
+ /**
1063
+ * Identifier composed of `virtual_id`s of a nested structure of documents,
1064
+ * used to aide assignment of the connection to the virtual document
1065
+ * handling specific, nested language usage; it will be appended to the file name
1066
+ * when creating a connection.
1067
+ */
1068
+ export type idPath = string;
1069
+ /**
1070
+ * Instance identifier for standalone documents (snippets), or language identifier
1071
+ * for documents which should be interpreted as one when stretched across cells.
1072
+ */
1073
+ export type virtualId = string;
1074
+ /**
1075
+ * Identifier composed of the file path and id_path.
1076
+ */
1077
+ export type uri = string;
1078
+ }
1079
+
1080
+ /**
1081
+ * Create foreign documents if available from input virtual documents.
1082
+ * @param virtualDocument - the virtual document to be collected
1083
+ * @return - Set of generated foreign documents
1084
+ */
1085
+ export function collectDocuments(
1086
+ virtualDocument: VirtualDocument
1087
+ ): Set<VirtualDocument> {
1088
+ let collected = new Set<VirtualDocument>();
1089
+ collected.add(virtualDocument);
1090
+ for (let foreign of virtualDocument.foreignDocuments.values()) {
1091
+ let foreignLanguages = collectDocuments(foreign);
1092
+ foreignLanguages.forEach(collected.add, collected);
1093
+ }
1094
+ return collected;
1095
+ }
1096
+
1097
+ export interface IBlockAddedInfo {
1098
+ /**
1099
+ * The virtual document.
1100
+ */
1101
+ virtualDocument: VirtualDocument;
1102
+
1103
+ /**
1104
+ * Option of the code block.
1105
+ */
1106
+ block: Document.ICodeBlockOptions;
1107
+ }
1108
+
1109
+ export class UpdateManager implements IDisposable {
1110
+ constructor(private virtualDocument: VirtualDocument) {
1111
+ this._blockAdded = new Signal<UpdateManager, IBlockAddedInfo>(this);
1112
+ this._documentUpdated = new Signal<UpdateManager, VirtualDocument>(this);
1113
+ this._updateBegan = new Signal<UpdateManager, Document.ICodeBlockOptions[]>(
1114
+ this
1115
+ );
1116
+ this._updateFinished = new Signal<
1117
+ UpdateManager,
1118
+ Document.ICodeBlockOptions[]
1119
+ >(this);
1120
+ this.documentUpdated.connect(this._onUpdated, this);
1121
+ }
1122
+
1123
+ /**
1124
+ * Promise resolved when the updating process finishes.
1125
+ */
1126
+ get updateDone(): Promise<void> {
1127
+ return this._updateDone;
1128
+ }
1129
+ /**
1130
+ * Test whether the document is disposed.
1131
+ */
1132
+ get isDisposed(): boolean {
1133
+ return this._isDisposed;
1134
+ }
1135
+
1136
+ /**
1137
+ * Signal emitted when a code block is added to the document.
1138
+ */
1139
+ get blockAdded(): ISignal<UpdateManager, IBlockAddedInfo> {
1140
+ return this._blockAdded;
1141
+ }
1142
+
1143
+ /**
1144
+ * Signal emitted by the editor that triggered the update,
1145
+ * providing the root document of the updated documents.
1146
+ */
1147
+ get documentUpdated(): ISignal<UpdateManager, VirtualDocument> {
1148
+ return this._documentUpdated;
1149
+ }
1150
+
1151
+ /**
1152
+ * Signal emitted when the update is started
1153
+ */
1154
+ get updateBegan(): ISignal<UpdateManager, Document.ICodeBlockOptions[]> {
1155
+ return this._updateBegan;
1156
+ }
1157
+
1158
+ /**
1159
+ * Signal emitted when the update is finished
1160
+ */
1161
+ get updateFinished(): ISignal<UpdateManager, Document.ICodeBlockOptions[]> {
1162
+ return this._updateFinished;
1163
+ }
1164
+
1165
+ /**
1166
+ * Dispose the class
1167
+ */
1168
+ dispose(): void {
1169
+ if (this._isDisposed) {
1170
+ return;
1171
+ }
1172
+ this._isDisposed = true;
1173
+ this.documentUpdated.disconnect(this._onUpdated);
1174
+ Signal.clearData(this);
1175
+ }
1176
+
1177
+ /**
1178
+ * Execute provided callback within an update-locked context, which guarantees that:
1179
+ * - the previous updates must have finished before the callback call, and
1180
+ * - no update will happen when executing the callback
1181
+ * @param fn - the callback to execute in update lock
1182
+ */
1183
+ async withUpdateLock(fn: () => void): Promise<void> {
1184
+ await untilReady(() => this._canUpdate(), 12, 10).then(() => {
1185
+ try {
1186
+ this._updateLock = true;
1187
+ fn();
1188
+ } finally {
1189
+ this._updateLock = false;
1190
+ }
1191
+ });
1192
+ }
1193
+
1194
+ /**
1195
+ * Update all the virtual documents, emit documents updated with root document if succeeded,
1196
+ * and resolve a void promise. The promise does not contain the text value of the root document,
1197
+ * as to avoid an easy trap of ignoring the changes in the virtual documents.
1198
+ */
1199
+ async updateDocuments(blocks: Document.ICodeBlockOptions[]): Promise<void> {
1200
+ let update = new Promise<void>((resolve, reject) => {
1201
+ // defer the update by up to 50 ms (10 retrials * 5 ms break),
1202
+ // awaiting for the previous update to complete.
1203
+ untilReady(() => this._canUpdate(), 10, 5)
1204
+ .then(() => {
1205
+ if (this.isDisposed || !this.virtualDocument) {
1206
+ resolve();
1207
+ }
1208
+ try {
1209
+ this._isUpdateInProgress = true;
1210
+ this._updateBegan.emit(blocks);
1211
+
1212
+ this.virtualDocument.clear();
1213
+
1214
+ for (let codeBlock of blocks) {
1215
+ this._blockAdded.emit({
1216
+ block: codeBlock,
1217
+ virtualDocument: this.virtualDocument
1218
+ });
1219
+ this.virtualDocument.appendCodeBlock(codeBlock);
1220
+ }
1221
+
1222
+ this._updateFinished.emit(blocks);
1223
+
1224
+ if (this.virtualDocument) {
1225
+ this._documentUpdated.emit(this.virtualDocument);
1226
+ this.virtualDocument.maybeEmitChanged();
1227
+ }
1228
+
1229
+ resolve();
1230
+ } catch (e) {
1231
+ console.warn('Documents update failed:', e);
1232
+ reject(e);
1233
+ } finally {
1234
+ this._isUpdateInProgress = false;
1235
+ }
1236
+ })
1237
+ .catch(console.error);
1238
+ });
1239
+ this._updateDone = update;
1240
+ return update;
1241
+ }
1242
+
1243
+ private _isDisposed = false;
1244
+
1245
+ /**
1246
+ * Promise resolved when the updating process finishes.
1247
+ */
1248
+ private _updateDone: Promise<void> = new Promise<void>(resolve => {
1249
+ resolve();
1250
+ });
1251
+
1252
+ /**
1253
+ * Virtual documents update guard.
1254
+ */
1255
+ private _isUpdateInProgress: boolean = false;
1256
+
1257
+ /**
1258
+ * Update lock to prevent multiple updates are applied at the same time.
1259
+ */
1260
+ private _updateLock: boolean = false;
1261
+
1262
+ private _blockAdded: Signal<UpdateManager, IBlockAddedInfo>;
1263
+ private _documentUpdated: Signal<UpdateManager, VirtualDocument>;
1264
+ private _updateBegan: Signal<UpdateManager, Document.ICodeBlockOptions[]>;
1265
+ private _updateFinished: Signal<UpdateManager, Document.ICodeBlockOptions[]>;
1266
+
1267
+ /**
1268
+ * Once all the foreign documents were refreshed, the unused documents (and their connections)
1269
+ * should be terminated if their lifetime has expired.
1270
+ */
1271
+ private _onUpdated(manager: UpdateManager, rootDocument: VirtualDocument) {
1272
+ try {
1273
+ rootDocument.closeExpiredDocuments();
1274
+ } catch (e) {
1275
+ console.warn('Failed to close expired documents');
1276
+ }
1277
+ }
1278
+
1279
+ /**
1280
+ * Check if the document can be updated.
1281
+ */
1282
+ private _canUpdate() {
1283
+ return !this.isDisposed && !this._isUpdateInProgress && !this._updateLock;
1284
+ }
1285
+ }