-
-
Notifications
You must be signed in to change notification settings - Fork 3.1k
/
actions.tsx
3009 lines (2750 loc) · 87 KB
/
actions.tsx
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) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
import {
Clipboard,
Dialog,
ISessionContext,
ISessionContextDialogs,
showDialog
} from '@jupyterlab/apputils';
import {
Cell,
CodeCell,
ICellModel,
ICodeCellModel,
isMarkdownCellModel,
isRawCellModel,
MarkdownCell
} from '@jupyterlab/cells';
import { PageConfig, URLExt, signalToPromise } from '@jupyterlab/coreutils';
import * as nbformat from '@jupyterlab/nbformat';
import { KernelMessage, ServerConnection } from '@jupyterlab/services';
import { ISharedAttachmentsCell } from '@jupyter/ydoc';
import { ITranslator, nullTranslator } from '@jupyterlab/translation';
import { every, findIndex } from '@lumino/algorithm';
import { JSONExt, JSONObject } from '@lumino/coreutils';
import { ISignal, Signal } from '@lumino/signaling';
import * as React from 'react';
import { Notebook, StaticNotebook } from './widget';
import { NotebookWindowedLayout } from './windowing';
/**
* The mimetype used for Jupyter cell data.
*/
const JUPYTER_CELL_MIME = 'application/vnd.jupyter.cells';
export class KernelError extends Error {
/**
* Exception name
*/
readonly errorName: string;
/**
* Exception value
*/
readonly errorValue: string;
/**
* Traceback
*/
readonly traceback: string[];
/**
* Construct the kernel error.
*/
constructor(content: KernelMessage.IExecuteReplyMsg['content']) {
const errorContent = content as KernelMessage.IReplyErrorContent;
const errorName = errorContent.ename;
const errorValue = errorContent.evalue;
super(`KernelReplyNotOK: ${errorName} ${errorValue}`);
this.errorName = errorName;
this.errorValue = errorValue;
this.traceback = errorContent.traceback;
Object.setPrototypeOf(this, KernelError.prototype);
}
}
/**
* A collection of actions that run against notebooks.
*
* #### Notes
* All of the actions are a no-op if there is no model on the notebook.
* The actions set the widget `mode` to `'command'` unless otherwise specified.
* The actions will preserve the selection on the notebook widget unless
* otherwise specified.
*/
export class NotebookActions {
/**
* A signal that emits whenever a cell completes execution.
*/
static get executed(): ISignal<
any,
{
notebook: Notebook;
cell: Cell;
success: boolean;
error?: KernelError | null;
}
> {
return Private.executed;
}
/**
* A signal that emits whenever a cell execution is scheduled.
*/
static get executionScheduled(): ISignal<
any,
{ notebook: Notebook; cell: Cell }
> {
return Private.executionScheduled;
}
/**
* A signal that emits when one notebook's cells are all executed.
*/
static get selectionExecuted(): ISignal<
any,
{ notebook: Notebook; lastCell: Cell }
> {
return Private.selectionExecuted;
}
/**
* A signal that emits when a cell's output is cleared.
*/
static get outputCleared(): ISignal<any, { notebook: Notebook; cell: Cell }> {
return Private.outputCleared;
}
/**
* A private constructor for the `NotebookActions` class.
*
* #### Notes
* This class can never be instantiated. Its static member `executed` will be
* merged with the `NotebookActions` namespace. The reason it exists as a
* standalone class is because at run time, the `Private.executed` variable
* does not yet exist, so it needs to be referenced via a getter.
*/
private constructor() {
// Intentionally empty.
}
}
/**
* A namespace for `NotebookActions` static methods.
*/
export namespace NotebookActions {
/**
* Split the active cell into two or more cells.
*
* @param notebook The target notebook widget.
*
* #### Notes
* It will preserve the existing mode.
* The last cell will be activated if no selection is found.
* If text was selected, the cell containing the selection will
* be activated.
* The existing selection will be cleared.
* The activated cell will have focus and the cursor will
* remain in the initial position.
* The leading whitespace in the second cell will be removed.
* If there is no content, two empty cells will be created.
* Both cells will have the same type as the original cell.
* This action can be undone.
*/
export function splitCell(notebook: Notebook): void {
if (!notebook.model || !notebook.activeCell) {
return;
}
const state = Private.getState(notebook);
// We force the notebook back in edit mode as splitting a cell
// requires using the cursor position within a cell (aka it was recently in edit mode)
// However the focus may be stolen if the action is triggered
// from the menu entry; switching the notebook in command mode.
notebook.mode = 'edit';
notebook.deselectAll();
const nbModel = notebook.model;
const index = notebook.activeCellIndex;
const child = notebook.widgets[index];
const editor = child.editor;
if (!editor) {
// TODO
return;
}
const selections = editor.getSelections();
const orig = child.model.sharedModel.getSource();
const offsets = [0];
let start: number = -1;
let end: number = -1;
for (let i = 0; i < selections.length; i++) {
// append start and end to handle selections
// cursors will have same start and end
start = editor.getOffsetAt(selections[i].start);
end = editor.getOffsetAt(selections[i].end);
if (start < end) {
offsets.push(start);
offsets.push(end);
} else if (end < start) {
offsets.push(end);
offsets.push(start);
} else {
offsets.push(start);
}
}
offsets.push(orig.length);
const clones = offsets.slice(0, -1).map((offset, offsetIdx) => {
const { cell_type, metadata } = child.model.sharedModel.toJSON();
return {
cell_type,
metadata,
source: orig
.slice(offset, offsets[offsetIdx + 1])
.replace(/^\n+/, '')
.replace(/\n+$/, '')
};
});
nbModel.sharedModel.transact(() => {
nbModel.sharedModel.deleteCell(index);
nbModel.sharedModel.insertCells(index, clones);
});
// If there is a selection the selected cell will be activated
const activeCellDelta = start !== end ? 2 : 1;
notebook.activeCellIndex = index + clones.length - activeCellDelta;
notebook
.scrollToItem(notebook.activeCellIndex)
.then(() => {
notebook.activeCell?.editor!.focus();
})
.catch(reason => {
// no-op
});
void Private.handleState(notebook, state);
}
/**
* Merge the selected cells.
*
* @param notebook - The target notebook widget.
*
* @param mergeAbove - If only one cell is selected, indicates whether to merge it
* with the cell above (true) or below (false, default).
*
* #### Notes
* The widget mode will be preserved.
* If only one cell is selected and `mergeAbove` is true, the above cell will be selected.
* If only one cell is selected and `mergeAbove` is false, the below cell will be selected.
* If the active cell is a code cell, its outputs will be cleared.
* This action can be undone.
* The final cell will have the same type as the active cell.
* If the active cell is a markdown cell, it will be unrendered.
*/
export function mergeCells(
notebook: Notebook,
mergeAbove: boolean = false
): void {
if (!notebook.model || !notebook.activeCell) {
return;
}
const state = Private.getState(notebook);
const toMerge: string[] = [];
const toDelete: number[] = [];
const model = notebook.model;
const cells = model.cells;
const primary = notebook.activeCell;
const active = notebook.activeCellIndex;
const attachments: nbformat.IAttachments = {};
// Get the cells to merge.
notebook.widgets.forEach((child, index) => {
if (notebook.isSelectedOrActive(child)) {
toMerge.push(child.model.sharedModel.getSource());
if (index !== active) {
toDelete.push(index);
}
// Collect attachments if the cell is a markdown cell or a raw cell
const model = child.model;
if (isRawCellModel(model) || isMarkdownCellModel(model)) {
for (const key of model.attachments.keys) {
attachments[key] = model.attachments.get(key)!.toJSON();
}
}
}
});
// Check for only a single cell selected.
if (toMerge.length === 1) {
// Merge with the cell above when mergeAbove is true
if (mergeAbove === true) {
// Bail if it is the first cell.
if (active === 0) {
return;
}
// Otherwise merge with the previous cell.
const cellModel = cells.get(active - 1);
toMerge.unshift(cellModel.sharedModel.getSource());
toDelete.push(active - 1);
} else if (mergeAbove === false) {
// Bail if it is the last cell.
if (active === cells.length - 1) {
return;
}
// Otherwise merge with the next cell.
const cellModel = cells.get(active + 1);
toMerge.push(cellModel.sharedModel.getSource());
toDelete.push(active + 1);
}
}
notebook.deselectAll();
const primaryModel = primary.model.sharedModel;
const { cell_type, metadata } = primaryModel.toJSON();
if (primaryModel.cell_type === 'code') {
// We can trust this cell because the outputs will be removed.
metadata.trusted = true;
}
const newModel = {
cell_type,
metadata,
source: toMerge.join('\n\n'),
attachments:
primaryModel.cell_type === 'markdown' ||
primaryModel.cell_type === 'raw'
? attachments
: undefined
};
// Make the changes while preserving history.
model.sharedModel.transact(() => {
model.sharedModel.deleteCell(active);
model.sharedModel.insertCell(active, newModel);
toDelete
.sort((a, b) => b - a)
.forEach(index => {
model.sharedModel.deleteCell(index);
});
});
// If the original cell is a markdown cell, make sure
// the new cell is unrendered.
if (primary instanceof MarkdownCell) {
(notebook.activeCell as MarkdownCell).rendered = false;
}
void Private.handleState(notebook, state);
}
/**
* Delete the selected cells.
*
* @param notebook - The target notebook widget.
*
* #### Notes
* The cell after the last selected cell will be activated.
* It will add a code cell if all cells are deleted.
* This action can be undone.
*/
export function deleteCells(notebook: Notebook): void {
if (!notebook.model || !notebook.activeCell) {
return;
}
const state = Private.getState(notebook);
Private.deleteCells(notebook);
void Private.handleState(notebook, state, true);
}
/**
* Insert a new code cell above the active cell or in index 0 if the notebook is empty.
*
* @param notebook - The target notebook widget.
*
* #### Notes
* The widget mode will be preserved.
* This action can be undone.
* The existing selection will be cleared.
* The new cell will the active cell.
*/
export function insertAbove(notebook: Notebook): void {
if (!notebook.model) {
return;
}
const state = Private.getState(notebook);
const model = notebook.model;
const newIndex = notebook.activeCell ? notebook.activeCellIndex : 0;
model.sharedModel.insertCell(newIndex, {
cell_type: notebook.notebookConfig.defaultCell,
metadata:
notebook.notebookConfig.defaultCell === 'code'
? {
// This is an empty cell created by user, thus is trusted
trusted: true
}
: {}
});
// Make the newly inserted cell active.
notebook.activeCellIndex = newIndex;
notebook.deselectAll();
void Private.handleState(notebook, state, true);
}
/**
* Insert a new code cell below the active cell or in index 0 if the notebook is empty.
*
* @param notebook - The target notebook widget.
*
* #### Notes
* The widget mode will be preserved.
* This action can be undone.
* The existing selection will be cleared.
* The new cell will be the active cell.
*/
export function insertBelow(notebook: Notebook): void {
if (!notebook.model) {
return;
}
const state = Private.getState(notebook);
const model = notebook.model;
const newIndex = notebook.activeCell ? notebook.activeCellIndex + 1 : 0;
model.sharedModel.insertCell(newIndex, {
cell_type: notebook.notebookConfig.defaultCell,
metadata:
notebook.notebookConfig.defaultCell === 'code'
? {
// This is an empty cell created by user, thus is trusted
trusted: true
}
: {}
});
// Make the newly inserted cell active.
notebook.activeCellIndex = newIndex;
notebook.deselectAll();
void Private.handleState(notebook, state, true);
}
function move(notebook: Notebook, shift: number): void {
if (!notebook.model || !notebook.activeCell) {
return;
}
const state = Private.getState(notebook);
const firstIndex = notebook.widgets.findIndex(w =>
notebook.isSelectedOrActive(w)
);
let lastIndex = notebook.widgets
.slice(firstIndex + 1)
.findIndex(w => !notebook.isSelectedOrActive(w));
if (lastIndex >= 0) {
lastIndex += firstIndex + 1;
} else {
lastIndex = notebook.model.cells.length;
}
if (shift > 0) {
notebook.moveCell(firstIndex, lastIndex, lastIndex - firstIndex);
} else {
notebook.moveCell(firstIndex, firstIndex + shift, lastIndex - firstIndex);
}
void Private.handleState(notebook, state, true);
}
/**
* Move the selected cell(s) down.
*
* @param notebook = The target notebook widget.
*/
export function moveDown(notebook: Notebook): void {
move(notebook, 1);
}
/**
* Move the selected cell(s) up.
*
* @param notebook - The target notebook widget.
*/
export function moveUp(notebook: Notebook): void {
move(notebook, -1);
}
/**
* Change the selected cell type(s).
*
* @param notebook - The target notebook widget.
*
* @param value - The target cell type.
*
* #### Notes
* It should preserve the widget mode.
* This action can be undone.
* The existing selection will be cleared.
* Any cells converted to markdown will be unrendered.
*/
export function changeCellType(
notebook: Notebook,
value: nbformat.CellType
): void {
if (!notebook.model || !notebook.activeCell) {
return;
}
const state = Private.getState(notebook);
Private.changeCellType(notebook, value);
void Private.handleState(notebook, state);
}
/**
* Run the selected cell(s).
*
* @param notebook - The target notebook widget.
* @param sessionContext - The client session object.
* @param sessionDialogs - The session dialogs.
* @param translator - The application translator.
*
* #### Notes
* The last selected cell will be activated, but not scrolled into view.
* The existing selection will be cleared.
* An execution error will prevent the remaining code cells from executing.
* All markdown cells will be rendered.
*/
export function run(
notebook: Notebook,
sessionContext?: ISessionContext,
sessionDialogs?: ISessionContextDialogs,
translator?: ITranslator
): Promise<boolean> {
if (!notebook.model || !notebook.activeCell) {
return Promise.resolve(false);
}
const state = Private.getState(notebook);
const promise = Private.runSelected(
notebook,
sessionContext,
sessionDialogs,
translator
);
void Private.handleRunState(notebook, state, false);
return promise;
}
/**
* Run specified cells.
*
* @param notebook - The target notebook widget.
* @param cells - The cells to run.
* @param sessionContext - The client session object.
* @param sessionDialogs - The session dialogs.
* @param translator - The application translator.
*
* #### Notes
* The existing selection will be preserved.
* The mode will be changed to command.
* An execution error will prevent the remaining code cells from executing.
* All markdown cells will be rendered.
*/
export function runCells(
notebook: Notebook,
cells: readonly Cell[],
sessionContext?: ISessionContext,
sessionDialogs?: ISessionContextDialogs,
translator?: ITranslator
): Promise<boolean> {
if (!notebook.model) {
return Promise.resolve(false);
}
const state = Private.getState(notebook);
const promise = Private.runCells(
notebook,
cells,
sessionContext,
sessionDialogs,
translator
);
void Private.handleRunState(notebook, state, false);
return promise;
}
/**
* Run the selected cell(s) and advance to the next cell.
*
* @param notebook - The target notebook widget.
* @param sessionContext - The client session object.
* @param sessionDialogs - The session dialogs.
* @param translator - The application translator.
*
* #### Notes
* The existing selection will be cleared.
* The cell after the last selected cell will be activated and scrolled into view.
* An execution error will prevent the remaining code cells from executing.
* All markdown cells will be rendered.
* If the last selected cell is the last cell, a new code cell
* will be created in `'edit'` mode. The new cell creation can be undone.
*/
export async function runAndAdvance(
notebook: Notebook,
sessionContext?: ISessionContext,
sessionDialogs?: ISessionContextDialogs,
translator?: ITranslator
): Promise<boolean> {
if (!notebook.model || !notebook.activeCell) {
return Promise.resolve(false);
}
const state = Private.getState(notebook);
const promise = Private.runSelected(
notebook,
sessionContext,
sessionDialogs,
translator
);
const model = notebook.model;
if (notebook.activeCellIndex === notebook.widgets.length - 1) {
// Do not use push here, as we want an widget insertion
// to make sure no placeholder widget is rendered.
model.sharedModel.insertCell(notebook.widgets.length, {
cell_type: notebook.notebookConfig.defaultCell,
metadata:
notebook.notebookConfig.defaultCell === 'code'
? {
// This is an empty cell created by user, thus is trusted
trusted: true
}
: {}
});
notebook.activeCellIndex++;
if (notebook.activeCell?.inViewport === false) {
await signalToPromise(notebook.activeCell.inViewportChanged, 200).catch(
() => {
// no-op
}
);
}
notebook.mode = 'edit';
} else {
notebook.activeCellIndex++;
}
void Private.handleRunState(notebook, state, true);
return promise;
}
/**
* Run the selected cell(s) and insert a new code cell.
*
* @param notebook - The target notebook widget.
* @param sessionContext - The client session object.
* @param sessionDialogs - The session dialogs.
* @param translator - The application translator.
*
* #### Notes
* An execution error will prevent the remaining code cells from executing.
* All markdown cells will be rendered.
* The widget mode will be set to `'edit'` after running.
* The existing selection will be cleared.
* The cell insert can be undone.
* The new cell will be scrolled into view.
*/
export async function runAndInsert(
notebook: Notebook,
sessionContext?: ISessionContext,
sessionDialogs?: ISessionContextDialogs,
translator?: ITranslator
): Promise<boolean> {
if (!notebook.model || !notebook.activeCell) {
return Promise.resolve(false);
}
const state = Private.getState(notebook);
const promise = Private.runSelected(
notebook,
sessionContext,
sessionDialogs,
translator
);
const model = notebook.model;
model.sharedModel.insertCell(notebook.activeCellIndex + 1, {
cell_type: notebook.notebookConfig.defaultCell,
metadata:
notebook.notebookConfig.defaultCell === 'code'
? {
// This is an empty cell created by user, thus is trusted
trusted: true
}
: {}
});
notebook.activeCellIndex++;
if (notebook.activeCell?.inViewport === false) {
await signalToPromise(notebook.activeCell.inViewportChanged, 200).catch(
() => {
// no-op
}
);
}
notebook.mode = 'edit';
void Private.handleRunState(notebook, state, true);
return promise;
}
/**
* Run all of the cells in the notebook.
*
* @param notebook - The target notebook widget.
* @param sessionContext - The client session object.
* @param sessionDialogs - The session dialogs.
* @param translator - The application translator.
*
* #### Notes
* The existing selection will be cleared.
* An execution error will prevent the remaining code cells from executing.
* All markdown cells will be rendered.
* The last cell in the notebook will be activated and scrolled into view.
*/
export function runAll(
notebook: Notebook,
sessionContext?: ISessionContext,
sessionDialogs?: ISessionContextDialogs,
translator?: ITranslator
): Promise<boolean> {
if (!notebook.model || !notebook.activeCell) {
return Promise.resolve(false);
}
const state = Private.getState(notebook);
const lastIndex = notebook.widgets.length;
const promise = Private.runCells(
notebook,
notebook.widgets,
sessionContext,
sessionDialogs,
translator
);
notebook.activeCellIndex = lastIndex;
notebook.deselectAll();
void Private.handleRunState(notebook, state, true);
return promise;
}
export function renderAllMarkdown(notebook: Notebook): Promise<boolean> {
if (!notebook.model || !notebook.activeCell) {
return Promise.resolve(false);
}
const previousIndex = notebook.activeCellIndex;
const state = Private.getState(notebook);
notebook.widgets.forEach((child, index) => {
if (child.model.type === 'markdown') {
notebook.select(child);
// This is to make sure that the activeCell
// does not get executed
notebook.activeCellIndex = index;
}
});
if (notebook.activeCell.model.type !== 'markdown') {
return Promise.resolve(true);
}
const promise = Private.runSelected(notebook);
notebook.activeCellIndex = previousIndex;
void Private.handleRunState(notebook, state, true);
return promise;
}
/**
* Run all of the cells before the currently active cell (exclusive).
*
* @param notebook - The target notebook widget.
* @param sessionContext - The client session object.
* @param sessionDialogs - The session dialogs.
* @param translator - The application translator.
*
* #### Notes
* The existing selection will be cleared.
* An execution error will prevent the remaining code cells from executing.
* All markdown cells will be rendered.
* The currently active cell will remain selected.
*/
export function runAllAbove(
notebook: Notebook,
sessionContext?: ISessionContext,
sessionDialogs?: ISessionContextDialogs,
translator?: ITranslator
): Promise<boolean> {
const { activeCell, activeCellIndex, model } = notebook;
if (!model || !activeCell || activeCellIndex < 1) {
return Promise.resolve(false);
}
const state = Private.getState(notebook);
const promise = Private.runCells(
notebook,
notebook.widgets.slice(0, notebook.activeCellIndex),
sessionContext,
sessionDialogs,
translator
);
notebook.deselectAll();
void Private.handleRunState(notebook, state, true);
return promise;
}
/**
* Run all of the cells after the currently active cell (inclusive).
*
* @param notebook - The target notebook widget.
* @param sessionContext - The client session object.
* @param sessionDialogs - The session dialogs.
* @param translator - The application translator.
*
* #### Notes
* The existing selection will be cleared.
* An execution error will prevent the remaining code cells from executing.
* All markdown cells will be rendered.
* The last cell in the notebook will be activated and scrolled into view.
*/
export function runAllBelow(
notebook: Notebook,
sessionContext?: ISessionContext,
sessionDialogs?: ISessionContextDialogs,
translator?: ITranslator
): Promise<boolean> {
if (!notebook.model || !notebook.activeCell) {
return Promise.resolve(false);
}
const state = Private.getState(notebook);
const lastIndex = notebook.widgets.length;
const promise = Private.runCells(
notebook,
notebook.widgets.slice(notebook.activeCellIndex),
sessionContext,
sessionDialogs,
translator
);
notebook.activeCellIndex = lastIndex;
notebook.deselectAll();
void Private.handleRunState(notebook, state, true);
return promise;
}
/**
* Replaces the selection in the active cell of the notebook.
*
* @param notebook - The target notebook widget.
* @param text - The text to replace the selection.
*/
export function replaceSelection(notebook: Notebook, text: string): void {
if (!notebook.model || !notebook.activeCell?.editor) {
return;
}
notebook.activeCell.editor.replaceSelection?.(text);
}
/**
* Select the above the active cell.
*
* @param notebook - The target notebook widget.
*
* #### Notes
* The widget mode will be preserved.
* This is a no-op if the first cell is the active cell.
* This will skip any collapsed cells.
* The existing selection will be cleared.
*/
export function selectAbove(notebook: Notebook): void {
if (!notebook.model || !notebook.activeCell) {
return;
}
const footer = (notebook.layout as NotebookWindowedLayout).footer;
if (footer && document.activeElement === footer.node) {
footer.node.blur();
notebook.mode = 'command';
return;
}
if (notebook.activeCellIndex === 0) {
return;
}
let possibleNextCellIndex = notebook.activeCellIndex - 1;
// find first non hidden cell above current cell
while (possibleNextCellIndex >= 0) {
const possibleNextCell = notebook.widgets[possibleNextCellIndex];
if (!possibleNextCell.inputHidden && !possibleNextCell.isHidden) {
break;
}
possibleNextCellIndex -= 1;
}
const state = Private.getState(notebook);
notebook.activeCellIndex = possibleNextCellIndex;
notebook.deselectAll();
void Private.handleState(notebook, state, true);
}
/**
* Select the cell below the active cell.
*
* @param notebook - The target notebook widget.
*
* #### Notes
* The widget mode will be preserved.
* This is a no-op if the last cell is the active cell.
* This will skip any collapsed cells.
* The existing selection will be cleared.
*/
export function selectBelow(notebook: Notebook): void {
if (!notebook.model || !notebook.activeCell) {
return;
}
let maxCellIndex = notebook.widgets.length - 1;
// Find last non-hidden cell
while (
notebook.widgets[maxCellIndex].isHidden ||
notebook.widgets[maxCellIndex].inputHidden
) {
maxCellIndex -= 1;
}
if (notebook.activeCellIndex === maxCellIndex) {
const footer = (notebook.layout as NotebookWindowedLayout).footer;
footer?.node.focus();
return;
}
let possibleNextCellIndex = notebook.activeCellIndex + 1;
// find first non hidden cell below current cell
while (possibleNextCellIndex < maxCellIndex) {
let possibleNextCell = notebook.widgets[possibleNextCellIndex];
if (!possibleNextCell.inputHidden && !possibleNextCell.isHidden) {
break;
}
possibleNextCellIndex += 1;
}
const state = Private.getState(notebook);
notebook.activeCellIndex = possibleNextCellIndex;
notebook.deselectAll();
void Private.handleState(notebook, state, true);
}
/** Insert new heading of same level above active cell.
*
* @param notebook - The target notebook widget
*/
export async function insertSameLevelHeadingAbove(
notebook: Notebook
): Promise<void> {
if (!notebook.model || !notebook.activeCell) {
return;
}
let headingLevel = Private.Headings.determineHeadingLevel(
notebook.activeCell,
notebook
);
if (headingLevel == -1) {
await Private.Headings.insertHeadingAboveCellIndex(0, 1, notebook);
} else {
await Private.Headings.insertHeadingAboveCellIndex(
notebook.activeCellIndex!,
headingLevel,
notebook
);
}
}
/** Insert new heading of same level at end of current section.
*
* @param notebook - The target notebook widget
*/
export async function insertSameLevelHeadingBelow(
notebook: Notebook
): Promise<void> {
if (!notebook.model || !notebook.activeCell) {