forked from jupyterlab/jupyterlab
/
index.ts
760 lines (667 loc) · 21.5 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
import {
ILayoutRestorer,
JupyterFrontEnd,
JupyterFrontEndPlugin
} from '@jupyterlab/application';
import { ICommandPalette, WidgetTracker } from '@jupyterlab/apputils';
import { CodeEditor, IEditorServices } from '@jupyterlab/codeeditor';
import { IConsoleTracker } from '@jupyterlab/console';
import {
ISettingRegistry,
MarkdownCodeBlocks,
PathExt
} from '@jupyterlab/coreutils';
import { IDocumentWidget } from '@jupyterlab/docregistry';
import { IFileBrowserFactory } from '@jupyterlab/filebrowser';
import {
FileEditor,
FileEditorFactory,
IEditorTracker,
TabSpaceStatus
} from '@jupyterlab/fileeditor';
import { ILauncher } from '@jupyterlab/launcher';
import {
IEditMenu,
IFileMenu,
IMainMenu,
IRunMenu,
IViewMenu
} from '@jupyterlab/mainmenu';
import { IStatusBar } from '@jupyterlab/statusbar';
import { JSONObject, ReadonlyJSONObject } from '@phosphor/coreutils';
import { Menu } from '@phosphor/widgets';
/**
* The class name for the text editor icon from the default theme.
*/
const EDITOR_ICON_CLASS = 'jp-MaterialIcon jp-TextEditorIcon';
/**
* The class name for the text editor icon from the default theme.
*/
const MARKDOWN_ICON_CLASS = 'jp-MaterialIcon jp-MarkdownIcon';
/**
* The name of the factory that creates editor widgets.
*/
const FACTORY = 'Editor';
/**
* The command IDs used by the fileeditor plugin.
*/
namespace CommandIDs {
export const createNew = 'fileeditor:create-new';
export const createNewMarkdown = 'fileeditor:create-new-markdown-file';
export const changeFontSize = 'fileeditor:change-font-size';
export const lineNumbers = 'fileeditor:toggle-line-numbers';
export const lineWrap = 'fileeditor:toggle-line-wrap';
export const changeTabs = 'fileeditor:change-tabs';
export const matchBrackets = 'fileeditor:toggle-match-brackets';
export const autoClosingBrackets = 'fileeditor:toggle-autoclosing-brackets';
export const createConsole = 'fileeditor:create-console';
export const runCode = 'fileeditor:run-code';
export const runAllCode = 'fileeditor:run-all';
export const markdownPreview = 'fileeditor:markdown-preview';
}
/**
* The editor tracker extension.
*/
const plugin: JupyterFrontEndPlugin<IEditorTracker> = {
activate,
id: '@jupyterlab/fileeditor-extension:plugin',
requires: [
IConsoleTracker,
IEditorServices,
IFileBrowserFactory,
ISettingRegistry
],
optional: [ICommandPalette, ILauncher, IMainMenu, ILayoutRestorer],
provides: IEditorTracker,
autoStart: true
};
/**
* A plugin that provides a status item allowing the user to
* switch tabs vs spaces and tab widths for text editors.
*/
export const tabSpaceStatus: JupyterFrontEndPlugin<void> = {
id: '@jupyterlab/fileeditor-extension:tab-space-status',
autoStart: true,
requires: [IStatusBar, IEditorTracker, ISettingRegistry],
activate: (
app: JupyterFrontEnd,
statusBar: IStatusBar,
editorTracker: IEditorTracker,
settingRegistry: ISettingRegistry
) => {
// Create a menu for switching tabs vs spaces.
const menu = new Menu({ commands: app.commands });
const command = 'fileeditor:change-tabs';
const { shell } = app;
const args: JSONObject = {
insertSpaces: false,
size: 4,
name: 'Indent with Tab'
};
menu.addItem({ command, args });
for (let size of [1, 2, 4, 8]) {
let args: JSONObject = {
insertSpaces: true,
size,
name: `Spaces: ${size} `
};
menu.addItem({ command, args });
}
// Create the status item.
const item = new TabSpaceStatus({ menu });
// Keep a reference to the code editor config from the settings system.
const updateSettings = (settings: ISettingRegistry.ISettings): void => {
item.model!.config = {
...CodeEditor.defaultConfig,
...(settings.get('editorConfig').composite as JSONObject)
};
};
void Promise.all([
settingRegistry.load('@jupyterlab/fileeditor-extension:plugin'),
app.restored
]).then(([settings]) => {
updateSettings(settings);
settings.changed.connect(updateSettings);
});
// Add the status item.
statusBar.registerStatusItem(
'@jupyterlab/fileeditor-extension:tab-space-status',
{
item,
align: 'right',
rank: 1,
isActive: () => {
return shell.currentWidget && editorTracker.has(shell.currentWidget);
}
}
);
}
};
/**
* Export the plugins as default.
*/
const plugins: JupyterFrontEndPlugin<any>[] = [plugin, tabSpaceStatus];
export default plugins;
/**
* Activate the editor tracker plugin.
*/
function activate(
app: JupyterFrontEnd,
consoleTracker: IConsoleTracker,
editorServices: IEditorServices,
browserFactory: IFileBrowserFactory,
settingRegistry: ISettingRegistry,
palette: ICommandPalette | null,
launcher: ILauncher | null,
menu: IMainMenu | null,
restorer: ILayoutRestorer | null
): IEditorTracker {
const id = plugin.id;
const namespace = 'editor';
const factory = new FileEditorFactory({
editorServices,
factoryOptions: {
name: FACTORY,
fileTypes: ['markdown', '*'], // Explicitly add the markdown fileType so
defaultFor: ['markdown', '*'] // it outranks the defaultRendered viewer.
}
});
const { commands, restored, shell } = app;
const tracker = new WidgetTracker<IDocumentWidget<FileEditor>>({
namespace
});
const isEnabled = () =>
tracker.currentWidget !== null &&
tracker.currentWidget === shell.currentWidget;
let config: CodeEditor.IConfig = { ...CodeEditor.defaultConfig };
// Handle state restoration.
if (restorer) {
void restorer.restore(tracker, {
command: 'docmanager:open',
args: widget => ({ path: widget.context.path, factory: FACTORY }),
name: widget => widget.context.path
});
}
/**
* Update the setting values.
*/
function updateSettings(settings: ISettingRegistry.ISettings): void {
config = {
...CodeEditor.defaultConfig,
...(settings.get('editorConfig').composite as JSONObject)
};
// Trigger a refresh of the rendered commands
app.commands.notifyCommandChanged();
}
/**
* Update the settings of the current tracker instances.
*/
function updateTracker(): void {
tracker.forEach(widget => {
updateWidget(widget.content);
});
}
/**
* Update the settings of a widget.
*/
function updateWidget(widget: FileEditor): void {
const editor = widget.editor;
Object.keys(config).forEach((key: keyof CodeEditor.IConfig) => {
editor.setOption(key, config[key]);
});
}
// Add a console creator to the File menu
// Fetch the initial state of the settings.
Promise.all([settingRegistry.load(id), restored])
.then(([settings]) => {
updateSettings(settings);
updateTracker();
settings.changed.connect(() => {
updateSettings(settings);
updateTracker();
});
})
.catch((reason: Error) => {
console.error(reason.message);
updateTracker();
});
factory.widgetCreated.connect((sender, widget) => {
widget.title.icon = EDITOR_ICON_CLASS;
// Notify the widget tracker if restore data needs to update.
widget.context.pathChanged.connect(() => {
void tracker.save(widget);
});
void tracker.add(widget);
updateWidget(widget.content);
});
app.docRegistry.addWidgetFactory(factory);
// Handle the settings of new widgets.
tracker.widgetAdded.connect((sender, widget) => {
updateWidget(widget.content);
});
// Add a command to change font size.
commands.addCommand(CommandIDs.changeFontSize, {
execute: args => {
const delta = Number(args['delta']);
if (Number.isNaN(delta)) {
console.error(
`${CommandIDs.changeFontSize}: delta arg must be a number`
);
return;
}
const style = window.getComputedStyle(document.documentElement);
const cssSize = parseInt(
style.getPropertyValue('--jp-code-font-size'),
10
);
const currentSize = config.fontSize || cssSize;
config.fontSize = currentSize + delta;
return settingRegistry
.set(id, 'editorConfig', (config as unknown) as JSONObject)
.catch((reason: Error) => {
console.error(`Failed to set ${id}: ${reason.message}`);
});
},
label: args => args['name'] as string
});
commands.addCommand(CommandIDs.lineNumbers, {
execute: () => {
config.lineNumbers = !config.lineNumbers;
return settingRegistry
.set(id, 'editorConfig', (config as unknown) as JSONObject)
.catch((reason: Error) => {
console.error(`Failed to set ${id}: ${reason.message}`);
});
},
isEnabled,
isToggled: () => config.lineNumbers,
label: 'Line Numbers'
});
type wrappingMode = 'on' | 'off' | 'wordWrapColumn' | 'bounded';
commands.addCommand(CommandIDs.lineWrap, {
execute: args => {
const lineWrap = (args['mode'] as wrappingMode) || 'off';
config.lineWrap = lineWrap;
return settingRegistry
.set(id, 'editorConfig', (config as unknown) as JSONObject)
.catch((reason: Error) => {
console.error(`Failed to set ${id}: ${reason.message}`);
});
},
isEnabled,
isToggled: args => {
const lineWrap = (args['mode'] as wrappingMode) || 'off';
return config.lineWrap === lineWrap;
},
label: 'Word Wrap'
});
commands.addCommand(CommandIDs.changeTabs, {
label: args => args['name'] as string,
execute: args => {
config.tabSize = (args['size'] as number) || 4;
config.insertSpaces = !!args['insertSpaces'];
return settingRegistry
.set(id, 'editorConfig', (config as unknown) as JSONObject)
.catch((reason: Error) => {
console.error(`Failed to set ${id}: ${reason.message}`);
});
},
isToggled: args => {
const insertSpaces = !!args['insertSpaces'];
const size = (args['size'] as number) || 4;
return config.insertSpaces === insertSpaces && config.tabSize === size;
}
});
commands.addCommand(CommandIDs.matchBrackets, {
execute: () => {
config.matchBrackets = !config.matchBrackets;
return settingRegistry
.set(id, 'editorConfig', (config as unknown) as JSONObject)
.catch((reason: Error) => {
console.error(`Failed to set ${id}: ${reason.message}`);
});
},
label: 'Match Brackets',
isEnabled,
isToggled: () => config.matchBrackets
});
commands.addCommand(CommandIDs.autoClosingBrackets, {
execute: () => {
config.autoClosingBrackets = !config.autoClosingBrackets;
return settingRegistry
.set(id, 'editorConfig', (config as unknown) as JSONObject)
.catch((reason: Error) => {
console.error(`Failed to set ${id}: ${reason.message}`);
});
},
label: 'Auto Close Brackets for Text Editor',
isToggled: () => config.autoClosingBrackets
});
async function createConsole(
widget: IDocumentWidget<FileEditor>,
args?: ReadonlyJSONObject
): Promise<void> {
const options = args || {};
const console = await commands.execute('console:create', {
activate: options['activate'],
name: widget.context.contentsModel.name,
path: widget.context.path,
preferredLanguage: widget.context.model.defaultKernelLanguage,
ref: widget.id,
insertMode: 'split-bottom'
});
widget.context.pathChanged.connect((sender, value) => {
console.session.setPath(value);
console.session.setName(widget.context.contentsModel.name);
});
}
commands.addCommand(CommandIDs.createConsole, {
execute: args => {
const widget = tracker.currentWidget;
if (!widget) {
return;
}
return createConsole(widget, args);
},
isEnabled,
label: 'Create Console for Editor'
});
commands.addCommand(CommandIDs.runCode, {
execute: () => {
// Run the appropriate code, taking into account a ```fenced``` code block.
const widget = tracker.currentWidget.content;
if (!widget) {
return;
}
let code = '';
const editor = widget.editor;
const path = widget.context.path;
const extension = PathExt.extname(path);
const selection = editor.getSelection();
const { start, end } = selection;
let selected = start.column !== end.column || start.line !== end.line;
if (selected) {
// Get the selected code from the editor.
const start = editor.getOffsetAt(selection.start);
const end = editor.getOffsetAt(selection.end);
code = editor.model.value.text.substring(start, end);
} else if (MarkdownCodeBlocks.isMarkdown(extension)) {
const { text } = editor.model.value;
const blocks = MarkdownCodeBlocks.findMarkdownCodeBlocks(text);
for (let block of blocks) {
if (block.startLine <= start.line && start.line <= block.endLine) {
code = block.code;
selected = true;
break;
}
}
}
if (!selected) {
// no selection, submit whole line and advance
code = editor.getLine(selection.start.line);
const cursor = editor.getCursorPosition();
if (cursor.line + 1 === editor.lineCount) {
let text = editor.model.value.text;
editor.model.value.text = text + '\n';
}
editor.setCursorPosition({
line: cursor.line + 1,
column: cursor.column
});
}
const activate = false;
if (code) {
return commands.execute('console:inject', { activate, code, path });
} else {
return Promise.resolve(void 0);
}
},
isEnabled,
label: 'Run Code'
});
commands.addCommand(CommandIDs.runAllCode, {
execute: () => {
let widget = tracker.currentWidget.content;
if (!widget) {
return;
}
let code = '';
let editor = widget.editor;
let text = editor.model.value.text;
let path = widget.context.path;
let extension = PathExt.extname(path);
if (MarkdownCodeBlocks.isMarkdown(extension)) {
// For Markdown files, run only code blocks.
const blocks = MarkdownCodeBlocks.findMarkdownCodeBlocks(text);
for (let block of blocks) {
code += block.code;
}
} else {
code = text;
}
const activate = false;
if (code) {
return commands.execute('console:inject', { activate, code, path });
} else {
return Promise.resolve(void 0);
}
},
isEnabled,
label: 'Run All Code'
});
commands.addCommand(CommandIDs.markdownPreview, {
execute: () => {
let widget = tracker.currentWidget;
if (!widget) {
return;
}
let path = widget.context.path;
return commands.execute('markdownviewer:open', {
path,
options: {
mode: 'split-right'
}
});
},
isVisible: () => {
let widget = tracker.currentWidget;
return (
(widget && PathExt.extname(widget.context.path) === '.md') || false
);
},
label: 'Show Markdown Preview'
});
// Function to create a new untitled text file, given
// the current working directory.
const createNew = (cwd: string, ext: string = 'txt') => {
return commands
.execute('docmanager:new-untitled', {
path: cwd,
type: 'file',
ext
})
.then(model => {
return commands.execute('docmanager:open', {
path: model.path,
factory: FACTORY
});
});
};
// Add a command for creating a new text file.
commands.addCommand(CommandIDs.createNew, {
label: args => (args['isPalette'] ? 'New Text File' : 'Text File'),
caption: 'Create a new text file',
iconClass: args => (args['isPalette'] ? '' : EDITOR_ICON_CLASS),
execute: args => {
let cwd = args['cwd'] || browserFactory.defaultBrowser.model.path;
return createNew(cwd as string);
}
});
// Add a command for creating a new Markdown file.
commands.addCommand(CommandIDs.createNewMarkdown, {
label: args => (args['isPalette'] ? 'New Markdown File' : 'Markdown File'),
caption: 'Create a new markdown file',
iconClass: args => (args['isPalette'] ? '' : MARKDOWN_ICON_CLASS),
execute: args => {
let cwd = args['cwd'] || browserFactory.defaultBrowser.model.path;
return createNew(cwd as string, 'md');
}
});
// Add a launcher item if the launcher is available.
if (launcher) {
launcher.add({
command: CommandIDs.createNew,
category: 'Other',
rank: 1
});
launcher.add({
command: CommandIDs.createNewMarkdown,
category: 'Other',
rank: 2
});
}
if (palette) {
const category = 'Text Editor';
let args: JSONObject = {
insertSpaces: false,
size: 4,
name: 'Indent with Tab'
};
let command = 'fileeditor:change-tabs';
palette.addItem({ command, args, category });
for (let size of [1, 2, 4, 8]) {
let args: JSONObject = {
insertSpaces: true,
size,
name: `Spaces: ${size} `
};
palette.addItem({ command, args, category });
}
args = { isPalette: true };
command = CommandIDs.createNew;
palette.addItem({ command, args, category });
args = { isPalette: true };
command = CommandIDs.createNewMarkdown;
palette.addItem({ command, args, category });
args = { name: 'Increase Font Size', delta: 1 };
command = CommandIDs.changeFontSize;
palette.addItem({ command, args, category });
args = { name: 'Decrease Font Size', delta: -1 };
command = CommandIDs.changeFontSize;
palette.addItem({ command, args, category });
}
if (menu) {
// Add the editing commands to the settings menu.
const tabMenu = new Menu({ commands });
tabMenu.title.label = 'Text Editor Indentation';
let args: JSONObject = {
insertSpaces: false,
size: 4,
name: 'Indent with Tab'
};
let command = 'fileeditor:change-tabs';
tabMenu.addItem({ command, args });
for (let size of [1, 2, 4, 8]) {
let args: JSONObject = {
insertSpaces: true,
size,
name: `Spaces: ${size} `
};
tabMenu.addItem({ command, args });
}
menu.settingsMenu.addGroup(
[
{
command: CommandIDs.changeFontSize,
args: { name: 'Increase Text Editor Font Size', delta: +1 }
},
{
command: CommandIDs.changeFontSize,
args: { name: 'Decrease Text Editor Font Size', delta: -1 }
},
{ type: 'submenu', submenu: tabMenu },
{ command: CommandIDs.autoClosingBrackets }
],
30
);
// Add new text file creation to the file menu.
menu.fileMenu.newMenu.addGroup([{ command: CommandIDs.createNew }], 30);
// Add new markdown file creation to the file menu.
menu.fileMenu.newMenu.addGroup(
[{ command: CommandIDs.createNewMarkdown }],
30
);
// Add undo/redo hooks to the edit menu.
menu.editMenu.undoers.add({
tracker,
undo: widget => {
widget.content.editor.undo();
},
redo: widget => {
widget.content.editor.redo();
}
} as IEditMenu.IUndoer<IDocumentWidget<FileEditor>>);
// Add editor view options.
menu.viewMenu.editorViewers.add({
tracker,
toggleLineNumbers: widget => {
const lineNumbers = !widget.content.editor.getOption('lineNumbers');
widget.content.editor.setOption('lineNumbers', lineNumbers);
},
toggleWordWrap: widget => {
const oldValue = widget.content.editor.getOption('lineWrap');
const newValue = oldValue === 'off' ? 'on' : 'off';
widget.content.editor.setOption('lineWrap', newValue);
},
toggleMatchBrackets: widget => {
const matchBrackets = !widget.content.editor.getOption('matchBrackets');
widget.content.editor.setOption('matchBrackets', matchBrackets);
},
lineNumbersToggled: widget =>
widget.content.editor.getOption('lineNumbers'),
wordWrapToggled: widget =>
widget.content.editor.getOption('lineWrap') !== 'off',
matchBracketsToggled: widget =>
widget.content.editor.getOption('matchBrackets')
} as IViewMenu.IEditorViewer<IDocumentWidget<FileEditor>>);
// Add a console creator the the Kernel menu.
menu.fileMenu.consoleCreators.add({
tracker,
name: 'Editor',
createConsole
} as IFileMenu.IConsoleCreator<IDocumentWidget<FileEditor>>);
// Add a code runner to the Run menu.
menu.runMenu.codeRunners.add({
tracker,
noun: 'Code',
isEnabled: current =>
!!consoleTracker.find(c => c.session.path === current.context.path),
run: () => commands.execute(CommandIDs.runCode),
runAll: () => commands.execute(CommandIDs.runAllCode),
restartAndRunAll: current => {
const console = consoleTracker.find(
console => console.session.path === current.context.path
);
if (console) {
return console.session.restart().then(restarted => {
if (restarted) {
void commands.execute(CommandIDs.runAllCode);
}
return restarted;
});
}
}
} as IRunMenu.ICodeRunner<IDocumentWidget<FileEditor>>);
}
app.contextMenu.addItem({
command: CommandIDs.createConsole,
selector: '.jp-FileEditor'
});
app.contextMenu.addItem({
command: CommandIDs.markdownPreview,
selector: '.jp-FileEditor'
});
return tracker;
}