-
Notifications
You must be signed in to change notification settings - Fork 293
/
interactiveWindow.ts
704 lines (644 loc) · 29.2 KB
/
interactiveWindow.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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import type * as nbformat from '@jupyterlab/nbformat';
import * as path from 'path';
import {
Event,
EventEmitter,
NotebookCell,
NotebookCellData,
NotebookCellKind,
NotebookDocument,
NotebookEditorRevealType,
NotebookRange,
Uri,
workspace,
WorkspaceEdit,
notebooks,
Position,
Range,
Selection,
commands,
TextEditorRevealType,
ViewColumn,
NotebookEditor,
Disposable,
window,
ThemeColor
} from 'vscode';
import { IPythonExtensionChecker } from '../../api/types';
import {
IApplicationShell,
ICommandManager,
IDocumentManager,
IWorkspaceService
} from '../../common/application/types';
import { JVSC_EXTENSION_ID, MARKDOWN_LANGUAGE, PYTHON_LANGUAGE } from '../../common/constants';
import '../../common/extensions';
import { traceInfo, traceInfoIfCI } from '../../common/logger';
import { IFileSystem } from '../../common/platform/types';
import * as uuid from 'uuid/v4';
import { IConfigurationService, IDisposableRegistry, InteractiveWindowMode, Resource } from '../../common/types';
import { createDeferred, Deferred } from '../../common/utils/async';
import { noop } from '../../common/utils/misc';
import { generateCellsFromNotebookDocument } from '../cellFactory';
import { CellMatcher } from '../cellMatcher';
import { Commands, defaultNotebookFormat } from '../constants';
import { ExportFormat, IExportDialog } from '../export/types';
import { InteractiveWindowMessages } from '../interactive-common/interactiveWindowTypes';
import { IKernel, IKernelProvider, NotebookCellRunState } from '../jupyter/kernels/types';
import { INotebookControllerManager } from '../notebook/types';
import { VSCodeNotebookController } from '../notebook/vscodeNotebookController';
import { updateNotebookMetadata } from '../notebookStorage/baseModel';
import { IInteractiveWindow, IInteractiveWindowLoadable, IJupyterDebugger, INotebookExporter } from '../types';
import { getInteractiveWindowTitle } from './identity';
import { generateMarkdownFromCodeLines } from '../../../datascience-ui/common';
import { chainWithPendingUpdates } from '../notebook/helpers/notebookUpdater';
import { LineQueryRegex, linkCommandAllowList } from '../interactive-common/linkProvider';
import { INativeInteractiveWindow } from './types';
import { generateInteractiveCode } from '../../../datascience-ui/common/cellFactory';
import { initializeInteractiveOrNotebookTelemetryBasedOnUserAction } from '../telemetry/telemetry';
import { InteractiveWindowView } from '../notebook/constants';
type InteractiveCellMetadata = {
inputCollapsed: boolean;
interactiveWindowCellMarker: string;
interactive: {
file: string;
line: number;
originalSource: string;
};
id: string;
};
export function getInteractiveCellMetadata(cell: NotebookCell): InteractiveCellMetadata | undefined {
if (cell.metadata.interactive !== undefined) {
return cell.metadata as InteractiveCellMetadata;
}
}
export class InteractiveWindow implements IInteractiveWindowLoadable {
public get onDidChangeViewState(): Event<void> {
return this._onDidChangeViewState.event;
}
// Promise that resolves when the interactive window is ready to handle code execution.
public get readyPromise(): Promise<void> {
return Promise.all([this._editorReadyPromise, this._kernelReadyPromise]).then(noop, noop);
}
public get closed(): Event<IInteractiveWindow> {
return this.closedEvent.event;
}
public get owner(): Resource {
return this._owner;
}
public get submitters(): Uri[] {
return this._submitters;
}
public get notebookUri(): Uri | undefined {
return this._notebookDocument?.uri;
}
public get notebookEditor(): NotebookEditor | undefined {
return this._notebookEditor;
}
public get notebookDocument(): NotebookDocument | undefined {
return this._notebookDocument;
}
private _onDidChangeViewState = new EventEmitter<void>();
private closedEvent: EventEmitter<IInteractiveWindow> = new EventEmitter<IInteractiveWindow>();
private _owner: Uri | undefined;
private _submitters: Uri[] = [];
private mode: InteractiveWindowMode = 'multiple';
private fileInKernel: string | undefined;
private cellMatcher;
private internalDisposables: Disposable[] = [];
private _editorReadyPromise: Promise<NotebookEditor>;
private _controllerReadyPromise: Deferred<VSCodeNotebookController>;
private _kernelReadyPromise: Promise<IKernel> | undefined;
private _notebookDocument: NotebookDocument | undefined;
private executionPromise: Promise<boolean> | undefined;
private _notebookEditor: NotebookEditor | undefined;
private _inputUri: Uri | undefined;
constructor(
private readonly applicationShell: IApplicationShell,
private readonly documentManager: IDocumentManager,
private readonly fs: IFileSystem,
private readonly configuration: IConfigurationService,
private readonly commandManager: ICommandManager,
private readonly jupyterExporter: INotebookExporter,
private readonly workspaceService: IWorkspaceService,
owner: Resource,
mode: InteractiveWindowMode,
private readonly extensionChecker: IPythonExtensionChecker,
private readonly exportDialog: IExportDialog,
private readonly notebookControllerManager: INotebookControllerManager,
private readonly kernelProvider: IKernelProvider,
private readonly disposables: IDisposableRegistry,
private readonly jupyterDebugger: IJupyterDebugger
) {
// Set our owner and first submitter
this._owner = owner;
this.mode = mode;
if (owner) {
this._submitters.push(owner);
}
// Request creation of the interactive window from VS Code
this._editorReadyPromise = this.createEditorReadyPromise();
// Wait for a controller to get selected
this._controllerReadyPromise = createDeferred<VSCodeNotebookController>();
// Set up promise for kernel ready
this._kernelReadyPromise = this.createKernelReadyPromise();
workspace.onDidCloseNotebookDocument((notebookDocument) => {
if (notebookDocument === this._notebookDocument) {
this.closedEvent.fire(this);
}
}, this.internalDisposables);
this.cellMatcher = new CellMatcher(this.configuration.getSettings(this.owningResource));
}
private async createKernelReadyPromise(): Promise<IKernel> {
const editor = await this._editorReadyPromise;
const controller = await this._controllerReadyPromise.promise;
initializeInteractiveOrNotebookTelemetryBasedOnUserAction(this.owner, controller.connection);
const kernel = this.kernelProvider.getOrCreate(editor.document, {
metadata: controller.connection,
controller: controller.controller,
resourceUri: this.owner
});
kernel.onRestarted(
async () => {
traceInfoIfCI('Restart event handled in IW');
this.fileInKernel = undefined;
const promise = this.runIntialization(kernel, this.owner);
this._kernelReadyPromise = promise.then(() => kernel);
await promise;
},
this,
this.internalDisposables
);
this.internalDisposables.push(kernel);
await kernel.start();
this.fileInKernel = undefined;
await this.runIntialization(kernel, this.owner);
return kernel;
}
private async createEditorReadyPromise(): Promise<NotebookEditor> {
const preferredController = await this.notebookControllerManager.getActiveInterpreterOrDefaultController(
InteractiveWindowView,
this.owner
);
const controllerId = preferredController ? `${JVSC_EXTENSION_ID}/${preferredController.id}` : undefined;
traceInfo(`Starting interactive window with controller ID ${controllerId}`);
const hasOwningFile = this.owner !== undefined;
const { inputUri, notebookEditor } = ((await this.commandManager.executeCommand(
'interactive.open',
// Keep focus on the owning file if there is one
{ viewColumn: ViewColumn.Beside, preserveFocus: hasOwningFile },
undefined,
controllerId,
this.owner && this.mode === 'perFile' ? getInteractiveWindowTitle(this.owner) : undefined
)) as unknown) as INativeInteractiveWindow;
if (!notebookEditor) {
// This means VS Code failed to create an interactive window.
// This should never happen.
throw new Error('Failed to request creation of interactive window from VS Code.');
}
this._notebookEditor = notebookEditor;
this._notebookDocument = notebookEditor.document;
this._inputUri = inputUri;
this.internalDisposables.push(
window.onDidChangeActiveNotebookEditor((e) => {
if (e === this._notebookEditor) {
this._onDidChangeViewState.fire();
}
})
);
this.listenForControllerSelection(notebookEditor.document);
this.initializeRendererCommunication();
return notebookEditor;
}
private initializeRendererCommunication() {
const messageChannel = notebooks.createRendererMessaging('jupyter-error-renderer');
this.disposables.push(
messageChannel.onDidReceiveMessage(async (e) => {
const message = e.message;
if (message.message === InteractiveWindowMessages.OpenLink) {
const href = message.payload;
if (href.startsWith('file')) {
await this.openFile(href);
} else if (href.startsWith('https://command:')) {
const temp: string = href.split(':')[2];
const params: string[] = temp.includes('/?') ? temp.split('/?')[1].split(',') : [];
let command = temp.split('/?')[0];
if (command.endsWith('/')) {
command = command.substring(0, command.length - 1);
}
if (linkCommandAllowList.includes(command)) {
await commands.executeCommand(command, params);
}
} else {
this.applicationShell.openUrl(href);
}
}
})
);
}
private async openFile(fileUri: string) {
const uri = Uri.parse(fileUri);
let selection: Range = new Range(new Position(0, 0), new Position(0, 0));
if (uri.query) {
// Might have a line number query on the file name
const lineMatch = LineQueryRegex.exec(uri.query);
if (lineMatch) {
const lineNumber = parseInt(lineMatch[1], 10);
selection = new Range(new Position(lineNumber, 0), new Position(lineNumber, 0));
}
}
// Show the matching editor if there is one
let editor = this.documentManager.visibleTextEditors.find((e) => this.fs.arePathsSame(e.document.uri, uri));
if (editor) {
return this.documentManager
.showTextDocument(editor.document, { selection, viewColumn: editor.viewColumn })
.then((e) => {
e.revealRange(selection, TextEditorRevealType.InCenter);
});
} else {
// Not a visible editor, try opening otherwise
return this.commandManager.executeCommand('vscode.open', uri).then(() => {
// See if that opened a text document
editor = this.documentManager.visibleTextEditors.find((e) => this.fs.arePathsSame(e.document.uri, uri));
if (editor) {
// Force the selection to change
editor.revealRange(selection);
editor.selection = new Selection(selection.start, selection.start);
}
});
}
}
private registerControllerChangeListener(controller: VSCodeNotebookController, notebookDocument: NotebookDocument) {
const controllerChangeListener = controller.controller.onDidChangeSelectedNotebooks(
(selectedEvent: { notebook: NotebookDocument; selected: boolean }) => {
// Controller was deselected for this InteractiveWindow's NotebookDocument
if (selectedEvent.selected === false && selectedEvent.notebook === notebookDocument) {
this._controllerReadyPromise = createDeferred<VSCodeNotebookController>();
this._kernelReadyPromise = undefined;
this.executionPromise = undefined;
controllerChangeListener.dispose();
}
},
this,
this.internalDisposables
);
}
private listenForControllerSelection(notebookDocument: NotebookDocument) {
const controller = this.notebookControllerManager.getSelectedNotebookController(notebookDocument);
if (controller !== undefined) {
this.registerControllerChangeListener(controller, notebookDocument);
this._controllerReadyPromise.resolve(controller);
}
// Ensure we hear about any controller changes so we can update our cached promises
this.notebookControllerManager.onNotebookControllerSelected(
(e: { notebook: NotebookDocument; controller: VSCodeNotebookController }) => {
if (e.notebook !== notebookDocument) {
return;
}
// Clear cached kernel when the selected controller for this document changes
this.registerControllerChangeListener(e.controller, notebookDocument);
this._controllerReadyPromise.resolve(e.controller);
// Recreate the kernel ready promise now that we have a new controller
this._kernelReadyPromise = this.createKernelReadyPromise();
},
this,
this.internalDisposables
);
}
public async show(): Promise<void> {
await this.commandManager.executeCommand(
'interactive.open',
{ preserveFocus: true },
this.notebookUri,
undefined,
undefined
);
}
public get inputUri() {
return this._inputUri;
}
public dispose() {
this.internalDisposables.forEach((d) => d.dispose());
}
// Add message to the notebook document in a markdown cell
public async addMessage(message: string): Promise<void> {
const notebookEditor = await this._editorReadyPromise;
const edit = new WorkspaceEdit();
const markdownCell = new NotebookCellData(NotebookCellKind.Markup, message, MARKDOWN_LANGUAGE);
markdownCell.metadata = { isInteractiveWindowMessageCell: true };
edit.replaceNotebookCells(
notebookEditor.document.uri,
new NotebookRange(notebookEditor.document.cellCount, notebookEditor.document.cellCount),
[markdownCell]
);
await workspace.applyEdit(edit);
}
public changeMode(mode: InteractiveWindowMode): void {
if (this.mode !== mode) {
this.mode = mode;
}
}
public async addCode(code: string, file: Uri, line: number): Promise<boolean> {
return this.submitCodeImpl(code, file, line, false);
}
public async debugCode(code: string, fileUri: Uri, line: number): Promise<boolean> {
let saved = true;
const file = fileUri.fsPath;
// Make sure the file is saved before debugging
const doc = this.documentManager.textDocuments.find((d) => this.fs.areLocalPathsSame(d.fileName, file));
if (doc && doc.isUntitled) {
// Before we start, get the list of documents
const beforeSave = [...this.documentManager.textDocuments];
saved = await doc.save();
// If that worked, we have to open the new document. It should be
// the new entry in the list
if (saved) {
const diff = this.documentManager.textDocuments.filter((f) => beforeSave.indexOf(f) === -1);
if (diff && diff.length > 0) {
fileUri = diff[0].uri;
// Open the new document
await this.documentManager.openTextDocument(fileUri);
}
}
}
let result = true;
// Call the internal method if we were able to save
if (saved) {
return this.submitCodeImpl(code, fileUri, line, true);
}
return result;
}
private async submitCodeImpl(code: string, fileUri: Uri, line: number, isDebug: boolean) {
// Do not execute or render empty cells
if (this.cellMatcher.stripFirstMarker(code).trim().length === 0) {
return true;
}
// Chain execution promises so that cells are executed in the right order
if (this.executionPromise) {
this.executionPromise = this.executionPromise.then(() =>
this.createExecutionPromise(code, fileUri, line, isDebug)
);
} else {
this.executionPromise = this.createExecutionPromise(code, fileUri, line, isDebug);
}
return this.executionPromise;
}
private async createExecutionPromise(code: string, fileUri: Uri, line: number, isDebug: boolean) {
traceInfoIfCI('InteractiveWindow.ts.createExecutionPromise.start');
const [notebookEditor, kernel] = await Promise.all([
this._editorReadyPromise,
this._kernelReadyPromise,
this.updateOwners(fileUri)
]);
const id = uuid();
// Compute isAtBottom based on last notebook cell before adding a notebook cell,
// since the notebook cell we're going to add is by definition not visible
const isLastCellVisible = notebookEditor?.visibleRanges.find((r) => {
return r.end === notebookEditor.document.cellCount - 1;
});
traceInfoIfCI('InteractiveWindow.ts.createExecutionPromise.before.AddNotebookCell');
const notebookCell = await this.addNotebookCell(notebookEditor.document, code, fileUri, line, id);
traceInfoIfCI('InteractiveWindow.ts.createExecutionPromise.after.AddNotebookCell');
const settings = this.configuration.getSettings(this.owningResource);
// The default behavior is to scroll to the last cell if the user is already at the bottom
// of the history, but not to scroll if the user has scrolled somewhere in the middle
// of the history. The jupyter.alwaysScrollOnNewCell setting overrides this to always scroll
// to newly-inserted cells.
if (settings.alwaysScrollOnNewCell || isLastCellVisible) {
this.revealCell(notebookCell, notebookEditor, false);
}
if (!kernel) {
return false;
}
const file = fileUri.fsPath;
let result = true;
try {
if (isDebug) {
await kernel!.executeHidden(
`import os;os.environ["IPYKERNEL_CELL_NAME"] = '${file.replace(/\\/g, '\\\\')}'`
);
await this.jupyterDebugger.startDebugging(kernel!);
}
traceInfoIfCI('InteractiveWindow.ts.createExecutionPromise.kernel.executeCell');
result = (await kernel!.executeCell(notebookCell)) !== NotebookCellRunState.Error;
traceInfo(`Finished execution for ${id}`);
} finally {
if (isDebug) {
await this.jupyterDebugger.stopDebugging(kernel!);
}
}
return result;
}
private async runIntialization(kernel: IKernel, fileUri: Resource) {
if (!fileUri) {
traceInfoIfCI('Unable to run initialization for IW');
return;
}
// If the file isn't unknown, set the active kernel's __file__ variable to point to that same file.
await this.setFileInKernel(fileUri.fsPath, kernel!);
traceInfoIfCI('file in kernel set for IW');
}
public async exportCells() {
throw new Error('Method not implemented.');
}
public async expandAllCells() {
const notebookEditor = await this._editorReadyPromise;
const edit = new WorkspaceEdit();
notebookEditor.document.getCells().forEach((cell, index) => {
const metadata = {
...(cell.metadata || {}),
inputCollapsed: false,
outputCollapsed: false
};
edit.replaceNotebookCellMetadata(notebookEditor.document.uri, index, metadata);
});
await workspace.applyEdit(edit);
}
public async collapseAllCells() {
const notebookEditor = await this._editorReadyPromise;
const edit = new WorkspaceEdit();
notebookEditor.document.getCells().forEach((cell, index) => {
if (cell.kind !== NotebookCellKind.Code) {
return;
}
const metadata = { ...(cell.metadata || {}), inputCollapsed: true, outputCollapsed: false };
edit.replaceNotebookCellMetadata(notebookEditor.document.uri, index, metadata);
});
await workspace.applyEdit(edit);
}
public async scrollToCell(id: string): Promise<void> {
const notebookEditor = await this._editorReadyPromise;
const matchingCell = notebookEditor.document
.getCells()
.find((cell) => getInteractiveCellMetadata(cell)?.id === id);
if (matchingCell) {
this.revealCell(matchingCell, notebookEditor, true);
}
}
private revealCell(notebookCell: NotebookCell, notebookEditor: NotebookEditor, useDecoration: boolean) {
const notebookRange = new NotebookRange(notebookCell.index, notebookCell.index + 1);
const decorationType = useDecoration
? notebooks.createNotebookEditorDecorationType({
backgroundColor: new ThemeColor('peekViewEditor.background'),
top: {}
})
: undefined;
// This will always try to reveal the whole cell--input + output combined
setTimeout(() => {
notebookEditor.revealRange(notebookRange, NotebookEditorRevealType.Default);
// Also add a decoration to make it look highlighted (peek background color)
if (decorationType) {
notebookEditor.setDecorations(decorationType, notebookRange);
// Fire another timeout to dispose of the decoration
setTimeout(() => {
decorationType.dispose();
}, 2000);
}
}, 200); // Rendering output is async so the output is not guaranteed to immediately exist
}
public async hasCell(id: string): Promise<boolean> {
const notebookEditor = await this._editorReadyPromise;
if (!notebookEditor) {
return false;
}
return notebookEditor.document.getCells().some((cell) => getInteractiveCellMetadata(cell)?.id === id);
}
public get owningResource(): Resource {
if (this.owner) {
return this.owner;
}
const root = this.workspaceService.rootPath;
if (root) {
return Uri.file(root);
}
return undefined;
}
private async setFileInKernel(file: string, kernel: IKernel): Promise<void> {
// If in perFile mode, set only once
if (this.mode === 'perFile' && !this.fileInKernel) {
traceInfoIfCI(`Initializing __file__ in setFileInKernel with ${file} for mode ${this.mode}`);
this.fileInKernel = file;
await kernel.executeHidden(`__file__ = '${file.replace(/\\/g, '\\\\')}'`);
} else if (
(!this.fileInKernel || !this.fs.areLocalPathsSame(this.fileInKernel, file)) &&
this.mode !== 'perFile'
) {
traceInfoIfCI(`Initializing __file__ in setFileInKernel with ${file} for mode ${this.mode}`);
// Otherwise we need to reset it every time
this.fileInKernel = file;
await kernel.executeHidden(`__file__ = '${file.replace(/\\/g, '\\\\')}'`);
} else {
traceInfoIfCI(
`Not Initializing __file__ in setFileInKernel with ${file} for mode ${this.mode} currently ${this.fileInKernel}`
);
}
}
private async updateOwners(file: Uri) {
// Update the owner for this window if not already set
if (!this._owner) {
this._owner = file;
}
// Add to the list of 'submitters' for this window.
if (!this._submitters.find((s) => this.fs.areLocalPathsSame(s.fsPath, file.fsPath))) {
this._submitters.push(file);
}
// Make sure our web panel opens.
await this.show();
}
private async addNotebookCell(
notebookDocument: NotebookDocument,
code: string,
file: Uri,
line: number,
id: string
): Promise<NotebookCell> {
// ensure editor is opened but not focused
await this.commandManager.executeCommand(
'interactive.open',
{ preserveFocus: true },
notebookDocument.uri,
this.notebookControllerManager.getSelectedNotebookController(notebookDocument)?.id,
undefined
);
// Strip #%% and store it in the cell metadata so we can reconstruct the cell structure when exporting to Python files
const settings = this.configuration.getSettings(this.owningResource);
const isMarkdown = this.cellMatcher.getCellType(code) === MARKDOWN_LANGUAGE;
const strippedCode = isMarkdown
? generateMarkdownFromCodeLines(code.splitLines()).join('')
: generateInteractiveCode(code, settings, this.cellMatcher);
const interactiveWindowCellMarker = this.cellMatcher.getFirstMarker(code);
// Insert cell into NotebookDocument
const language =
workspace.textDocuments.find((document) => document.uri.toString() === this.owner?.toString())
?.languageId ?? PYTHON_LANGUAGE;
const notebookCellData = new NotebookCellData(
isMarkdown ? NotebookCellKind.Markup : NotebookCellKind.Code,
strippedCode,
isMarkdown ? MARKDOWN_LANGUAGE : language
);
notebookCellData.metadata = <InteractiveCellMetadata>{
inputCollapsed: !isMarkdown && settings.collapseCellInputCodeByDefault,
interactiveWindowCellMarker,
interactive: {
file: file.fsPath,
line: line,
originalSource: code
},
id: id
};
await chainWithPendingUpdates(notebookDocument, (edit) => {
edit.replaceNotebookCells(
notebookDocument.uri,
new NotebookRange(notebookDocument.cellCount, notebookDocument.cellCount),
[notebookCellData]
);
});
return notebookDocument.cellAt(notebookDocument.cellCount - 1);
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any, no-empty,@typescript-eslint/no-empty-function
public async export() {
const notebookEditor = await this._editorReadyPromise;
// Export requires the python extension
if (!this.extensionChecker.isPythonExtensionInstalled) {
return this.extensionChecker.showPythonExtensionInstallRequiredPrompt();
}
const { magicCommandsAsComments } = this.configuration.getSettings(this.owningResource);
const cells = generateCellsFromNotebookDocument(notebookEditor.document, magicCommandsAsComments);
// Should be an array of cells
if (cells && this.exportDialog) {
// Bring up the export file dialog box
const uri = await this.exportDialog.showDialog(ExportFormat.ipynb, this.owningResource);
if (uri) {
await this.jupyterExporter.exportToFile(cells, uri.fsPath);
}
}
}
public async exportAs() {
const kernel = await this._kernelReadyPromise;
// Export requires the python extension
if (!this.extensionChecker.isPythonExtensionInstalled) {
return this.extensionChecker.showPythonExtensionInstallRequiredPrompt();
}
// Pull out the metadata from our active notebook
const metadata: nbformat.INotebookMetadata = { orig_nbformat: defaultNotebookFormat.major };
if (kernel) {
updateNotebookMetadata(metadata, kernel.kernelConnectionMetadata);
}
let defaultFileName;
if (this.submitters && this.submitters.length) {
const lastSubmitter = this.submitters[this.submitters.length - 1];
defaultFileName = path.basename(lastSubmitter.fsPath, path.extname(lastSubmitter.fsPath));
}
// Then run the export command with these contents
this.commandManager
.executeCommand(
Commands.Export,
this.notebookDocument,
defaultFileName,
kernel?.kernelConnectionMetadata.interpreter
)
.then(noop, noop);
}
}