-
-
Notifications
You must be signed in to change notification settings - Fork 3.1k
/
commands.ts
1319 lines (1177 loc) · 37.1 KB
/
commands.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
import {
Clipboard,
ICommandPalette,
ISessionContextDialogs,
sessionContextDialogs,
WidgetTracker
} from '@jupyterlab/apputils';
import { CodeEditor } from '@jupyterlab/codeeditor';
import { CodeMirrorEditor } from '@jupyterlab/codemirror';
import { IConsoleTracker } from '@jupyterlab/console';
import { MarkdownCodeBlocks, PathExt } from '@jupyterlab/coreutils';
import { IDocumentWidget } from '@jupyterlab/docregistry';
import { IFileBrowserFactory } from '@jupyterlab/filebrowser';
import { FileEditor } from '@jupyterlab/fileeditor';
import { ILauncher } from '@jupyterlab/launcher';
import {
IEditMenu,
IFileMenu,
IMainMenu,
IRunMenu,
IViewMenu
} from '@jupyterlab/mainmenu';
import { ISettingRegistry } from '@jupyterlab/settingregistry';
import { TranslationBundle } from '@jupyterlab/translation';
import {
consoleIcon,
copyIcon,
cutIcon,
LabIcon,
markdownIcon,
pasteIcon,
redoIcon,
textEditorIcon,
undoIcon
} from '@jupyterlab/ui-components';
import { CommandRegistry } from '@lumino/commands';
import {
JSONObject,
ReadonlyJSONObject,
ReadonlyPartialJSONObject
} from '@lumino/coreutils';
const autoClosingBracketsNotebook = 'notebook:toggle-autoclosing-brackets';
const autoClosingBracketsConsole = 'console:toggle-autoclosing-brackets';
/**
* The command IDs used by the fileeditor plugin.
*/
export 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 autoClosingBracketsUniversal =
'fileeditor:toggle-autoclosing-brackets-universal';
export const createConsole = 'fileeditor:create-console';
export const replaceSelection = 'fileeditor:replace-selection';
export const runCode = 'fileeditor:run-code';
export const runAllCode = 'fileeditor:run-all';
export const markdownPreview = 'fileeditor:markdown-preview';
export const undo = 'fileeditor:undo';
export const redo = 'fileeditor:redo';
export const cut = 'fileeditor:cut';
export const copy = 'fileeditor:copy';
export const paste = 'fileeditor:paste';
export const selectAll = 'fileeditor:select-all';
}
export interface IFileTypeData extends ReadonlyJSONObject {
fileExt: string;
iconName: string;
launcherLabel: string;
paletteLabel: string;
caption: string;
}
/**
* The name of the factory that creates editor widgets.
*/
export const FACTORY = 'Editor';
const userSettings = [
'autoClosingBrackets',
'codeFolding',
'cursorBlinkRate',
'fontFamily',
'fontSize',
'insertSpaces',
'lineHeight',
'lineNumbers',
'lineWrap',
'matchBrackets',
'readOnly',
'rulers',
'showTrailingSpace',
'tabSize',
'wordWrapColumn'
];
function filterUserSettings(config: CodeEditor.IConfig): CodeEditor.IConfig {
const filteredConfig = { ...config };
// Delete parts of the config that are not user settings (like handlePaste).
for (let k of Object.keys(config)) {
if (!userSettings.includes(k)) {
delete (config as any)[k];
}
}
return filteredConfig;
}
let config: CodeEditor.IConfig = filterUserSettings(CodeEditor.defaultConfig);
/**
* A utility class for adding commands and menu items,
* for use by the File Editor extension or other Editor extensions.
*/
export namespace Commands {
/**
* Accessor function that returns the createConsole function for use by Create Console commands
*/
function getCreateConsoleFunction(
commands: CommandRegistry
): (
widget: IDocumentWidget<FileEditor>,
args?: ReadonlyPartialJSONObject
) => Promise<void> {
return async function createConsole(
widget: IDocumentWidget<FileEditor>,
args?: ReadonlyPartialJSONObject
): 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);
});
};
}
/**
* Update the setting values.
*/
export function updateSettings(
settings: ISettingRegistry.ISettings,
commands: CommandRegistry
): void {
config = filterUserSettings({
...CodeEditor.defaultConfig,
...(settings.get('editorConfig').composite as JSONObject)
});
// Trigger a refresh of the rendered commands
commands.notifyCommandChanged();
}
/**
* Update the settings of the current tracker instances.
*/
export function updateTracker(
tracker: WidgetTracker<IDocumentWidget<FileEditor>>
): void {
tracker.forEach(widget => {
updateWidget(widget.content);
});
}
/**
* Update the settings of a widget.
* Skip global settings for transient editor specific configs.
*/
export function updateWidget(widget: FileEditor): void {
const editor = widget.editor;
editor.setOptions({ ...config });
}
/**
* Wrapper function for adding the default File Editor commands
*/
export function addCommands(
commands: CommandRegistry,
settingRegistry: ISettingRegistry,
trans: TranslationBundle,
id: string,
isEnabled: () => boolean,
tracker: WidgetTracker<IDocumentWidget<FileEditor>>,
browserFactory: IFileBrowserFactory
): void {
// Add a command to change font size.
addChangeFontSizeCommand(commands, settingRegistry, trans, id);
addLineNumbersCommand(commands, settingRegistry, trans, id, isEnabled);
addWordWrapCommand(commands, settingRegistry, trans, id, isEnabled);
addChangeTabsCommand(commands, settingRegistry, trans, id);
addMatchBracketsCommand(commands, settingRegistry, trans, id, isEnabled);
addAutoClosingBracketsCommand(commands, settingRegistry, trans, id);
addReplaceSelectionCommand(commands, tracker, trans, isEnabled);
addCreateConsoleCommand(commands, tracker, trans, isEnabled);
addRunCodeCommand(commands, tracker, trans, isEnabled);
addRunAllCodeCommand(commands, tracker, trans, isEnabled);
addMarkdownPreviewCommand(commands, tracker, trans);
// Add a command for creating a new text file.
addCreateNewCommand(commands, browserFactory, trans);
// Add a command for creating a new Markdown file.
addCreateNewMarkdownCommand(commands, browserFactory, trans);
addUndoCommand(commands, tracker, trans, isEnabled);
addRedoCommand(commands, tracker, trans, isEnabled);
addCutCommand(commands, tracker, trans, isEnabled);
addCopyCommand(commands, tracker, trans, isEnabled);
addPasteCommand(commands, tracker, trans, isEnabled);
addSelectAllCommand(commands, tracker, trans, isEnabled);
}
/**
* Add a command to change font size for File Editor
*/
export function addChangeFontSizeCommand(
commands: CommandRegistry,
settingRegistry: ISettingRegistry,
trans: TranslationBundle,
id: string
): void {
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 => {
if ((args.delta ?? 0) > 0) {
return args.isMenu
? trans.__('Increase Text Editor Font Size')
: trans.__('Increase Font Size');
} else {
return args.isMenu
? trans.__('Decrease Text Editor Font Size')
: trans.__('Decrease Font Size');
}
}
});
}
/**
* Add the Line Numbers command
*/
export function addLineNumbersCommand(
commands: CommandRegistry,
settingRegistry: ISettingRegistry,
trans: TranslationBundle,
id: string,
isEnabled: () => boolean
): void {
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: trans.__('Line Numbers')
});
}
/**
* Add the Word Wrap command
*/
export function addWordWrapCommand(
commands: CommandRegistry,
settingRegistry: ISettingRegistry,
trans: TranslationBundle,
id: string,
isEnabled: () => boolean
): void {
type wrappingMode = 'on' | 'off' | 'wordWrapColumn' | 'bounded';
commands.addCommand(CommandIDs.lineWrap, {
execute: args => {
config.lineWrap = (args['mode'] as wrappingMode) || 'off';
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: trans.__('Word Wrap')
});
}
/**
* Add command for changing tabs size or type in File Editor
*/
export function addChangeTabsCommand(
commands: CommandRegistry,
settingRegistry: ISettingRegistry,
trans: TranslationBundle,
id: string
): void {
commands.addCommand(CommandIDs.changeTabs, {
label: args => {
if (args.insertSpaces) {
return trans._n(
'Spaces: %1',
'Spaces: %1',
(args.size as number) ?? 0
);
} else {
return trans.__('Indent with Tab');
}
},
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;
}
});
}
/**
* Add the Match Brackets command
*/
export function addMatchBracketsCommand(
commands: CommandRegistry,
settingRegistry: ISettingRegistry,
trans: TranslationBundle,
id: string,
isEnabled: () => boolean
): void {
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: trans.__('Match Brackets'),
isEnabled,
isToggled: () => config.matchBrackets
});
}
/**
* Add the Auto Close Brackets for Text Editor command
*/
export function addAutoClosingBracketsCommand(
commands: CommandRegistry,
settingRegistry: ISettingRegistry,
trans: TranslationBundle,
id: string
): void {
commands.addCommand(CommandIDs.autoClosingBrackets, {
execute: args => {
config.autoClosingBrackets = !!(
args['force'] ?? !config.autoClosingBrackets
);
return settingRegistry
.set(id, 'editorConfig', (config as unknown) as JSONObject)
.catch((reason: Error) => {
console.error(`Failed to set ${id}: ${reason.message}`);
});
},
label: trans.__('Auto Close Brackets for Text Editor'),
isToggled: () => config.autoClosingBrackets
});
commands.addCommand(CommandIDs.autoClosingBracketsUniversal, {
execute: () => {
const anyToggled =
commands.isToggled(CommandIDs.autoClosingBrackets) ||
commands.isToggled(autoClosingBracketsNotebook) ||
commands.isToggled(autoClosingBracketsConsole);
// if any auto closing brackets options is toggled, toggle both off
if (anyToggled) {
void commands.execute(CommandIDs.autoClosingBrackets, {
force: false
});
void commands.execute(autoClosingBracketsNotebook, { force: false });
void commands.execute(autoClosingBracketsConsole, { force: false });
} else {
// both are off, turn them on
void commands.execute(CommandIDs.autoClosingBrackets, {
force: true
});
void commands.execute(autoClosingBracketsNotebook, { force: true });
void commands.execute(autoClosingBracketsConsole, { force: true });
}
},
label: trans.__('Auto Close Brackets'),
isToggled: () =>
commands.isToggled(CommandIDs.autoClosingBrackets) ||
commands.isToggled(autoClosingBracketsNotebook) ||
commands.isToggled(autoClosingBracketsConsole)
});
}
/**
* Add the replace selection for text editor command
*/
export function addReplaceSelectionCommand(
commands: CommandRegistry,
tracker: WidgetTracker<IDocumentWidget<FileEditor>>,
trans: TranslationBundle,
isEnabled: () => boolean
): void {
commands.addCommand(CommandIDs.replaceSelection, {
execute: args => {
const text: string = (args['text'] as string) || '';
const widget = tracker.currentWidget;
if (!widget) {
return;
}
widget.content.editor.replaceSelection?.(text);
},
isEnabled,
label: trans.__('Replace Selection in Editor')
});
}
/**
* Add the Create Console for Editor command
*/
export function addCreateConsoleCommand(
commands: CommandRegistry,
tracker: WidgetTracker<IDocumentWidget<FileEditor>>,
trans: TranslationBundle,
isEnabled: () => boolean
): void {
commands.addCommand(CommandIDs.createConsole, {
execute: args => {
const widget = tracker.currentWidget;
if (!widget) {
return;
}
return getCreateConsoleFunction(commands)(widget, args);
},
isEnabled,
icon: consoleIcon,
label: trans.__('Create Console for Editor')
});
}
/**
* Add the Run Code command
*/
export function addRunCodeCommand(
commands: CommandRegistry,
tracker: WidgetTracker<IDocumentWidget<FileEditor>>,
trans: TranslationBundle,
isEnabled: () => boolean
): void {
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: string | undefined = '';
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 (const 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) {
const 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: trans.__('Run Code')
});
}
/**
* Add the Run All Code command
*/
export function addRunAllCodeCommand(
commands: CommandRegistry,
tracker: WidgetTracker<IDocumentWidget<FileEditor>>,
trans: TranslationBundle,
isEnabled: () => boolean
): void {
commands.addCommand(CommandIDs.runAllCode, {
execute: () => {
const widget = tracker.currentWidget?.content;
if (!widget) {
return;
}
let code = '';
const editor = widget.editor;
const text = editor.model.value.text;
const path = widget.context.path;
const extension = PathExt.extname(path);
if (MarkdownCodeBlocks.isMarkdown(extension)) {
// For Markdown files, run only code blocks.
const blocks = MarkdownCodeBlocks.findMarkdownCodeBlocks(text);
for (const 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: trans.__('Run All Code')
});
}
/**
* Add markdown preview command
*/
export function addMarkdownPreviewCommand(
commands: CommandRegistry,
tracker: WidgetTracker<IDocumentWidget<FileEditor>>,
trans: TranslationBundle
): void {
commands.addCommand(CommandIDs.markdownPreview, {
execute: () => {
const widget = tracker.currentWidget;
if (!widget) {
return;
}
const path = widget.context.path;
return commands.execute('markdownviewer:open', {
path,
options: {
mode: 'split-right'
}
});
},
isVisible: () => {
const widget = tracker.currentWidget;
return (
(widget && PathExt.extname(widget.context.path) === '.md') || false
);
},
icon: markdownIcon,
label: trans.__('Show Markdown Preview')
});
}
/**
* Add undo command
*/
export function addUndoCommand(
commands: CommandRegistry,
tracker: WidgetTracker<IDocumentWidget<FileEditor>>,
trans: TranslationBundle,
isEnabled: () => boolean
): void {
commands.addCommand(CommandIDs.undo, {
execute: () => {
const widget = tracker.currentWidget?.content;
if (!widget) {
return;
}
widget.editor.undo();
},
isEnabled: () => {
if (!isEnabled()) {
return false;
}
const widget = tracker.currentWidget?.content;
if (!widget) {
return false;
}
// Ideally enable it when there are undo events stored
// Reference issue #8590: Code mirror editor could expose the history of undo/redo events
return true;
},
icon: undoIcon.bindprops({ stylesheet: 'menuItem' }),
label: trans.__('Undo')
});
}
/**
* Add redo command
*/
export function addRedoCommand(
commands: CommandRegistry,
tracker: WidgetTracker<IDocumentWidget<FileEditor>>,
trans: TranslationBundle,
isEnabled: () => boolean
): void {
commands.addCommand(CommandIDs.redo, {
execute: () => {
const widget = tracker.currentWidget?.content;
if (!widget) {
return;
}
widget.editor.redo();
},
isEnabled: () => {
if (!isEnabled()) {
return false;
}
const widget = tracker.currentWidget?.content;
if (!widget) {
return false;
}
// Ideally enable it when there are redo events stored
// Reference issue #8590: Code mirror editor could expose the history of undo/redo events
return true;
},
icon: redoIcon.bindprops({ stylesheet: 'menuItem' }),
label: trans.__('Redo')
});
}
/**
* Add cut command
*/
export function addCutCommand(
commands: CommandRegistry,
tracker: WidgetTracker<IDocumentWidget<FileEditor>>,
trans: TranslationBundle,
isEnabled: () => boolean
): void {
commands.addCommand(CommandIDs.cut, {
execute: () => {
const widget = tracker.currentWidget?.content;
if (!widget) {
return;
}
const editor = widget.editor as CodeMirrorEditor;
const text = getTextSelection(editor);
Clipboard.copyToSystem(text);
editor.replaceSelection && editor.replaceSelection('');
},
isEnabled: () => {
if (!isEnabled()) {
return false;
}
const widget = tracker.currentWidget?.content;
if (!widget) {
return false;
}
// Enable command if there is a text selection in the editor
return isSelected(widget.editor as CodeMirrorEditor);
},
icon: cutIcon.bindprops({ stylesheet: 'menuItem' }),
label: trans.__('Cut')
});
}
/**
* Add copy command
*/
export function addCopyCommand(
commands: CommandRegistry,
tracker: WidgetTracker<IDocumentWidget<FileEditor>>,
trans: TranslationBundle,
isEnabled: () => boolean
): void {
commands.addCommand(CommandIDs.copy, {
execute: () => {
const widget = tracker.currentWidget?.content;
if (!widget) {
return;
}
const editor = widget.editor as CodeMirrorEditor;
const text = getTextSelection(editor);
Clipboard.copyToSystem(text);
},
isEnabled: () => {
if (!isEnabled()) {
return false;
}
const widget = tracker.currentWidget?.content;
if (!widget) {
return false;
}
// Enable command if there is a text selection in the editor
return isSelected(widget.editor as CodeMirrorEditor);
},
icon: copyIcon.bindprops({ stylesheet: 'menuItem' }),
label: trans.__('Copy')
});
}
/**
* Add paste command
*/
export function addPasteCommand(
commands: CommandRegistry,
tracker: WidgetTracker<IDocumentWidget<FileEditor>>,
trans: TranslationBundle,
isEnabled: () => boolean
): void {
commands.addCommand(CommandIDs.paste, {
execute: async () => {
const widget = tracker.currentWidget?.content;
if (!widget) {
return;
}
const editor: CodeEditor.IEditor = widget.editor;
// Get data from clipboard
const clipboard = window.navigator.clipboard;
const clipboardData: string = await clipboard.readText();
if (clipboardData) {
// Paste data to the editor
editor.replaceSelection && editor.replaceSelection(clipboardData);
}
},
isEnabled: () => Boolean(isEnabled() && tracker.currentWidget?.content),
icon: pasteIcon.bindprops({ stylesheet: 'menuItem' }),
label: trans.__('Paste')
});
}
/**
* Add select all command
*/
export function addSelectAllCommand(
commands: CommandRegistry,
tracker: WidgetTracker<IDocumentWidget<FileEditor>>,
trans: TranslationBundle,
isEnabled: () => boolean
): void {
commands.addCommand(CommandIDs.selectAll, {
execute: () => {
const widget = tracker.currentWidget?.content;
if (!widget) {
return;
}
const editor = widget.editor as CodeMirrorEditor;
editor.execCommand('selectAll');
},
isEnabled: () => Boolean(isEnabled() && tracker.currentWidget?.content),
label: trans.__('Select All')
});
}
/**
* Helper function to check if there is a text selection in the editor
*/
function isSelected(editor: CodeMirrorEditor) {
const selectionObj = editor.getSelection();
const { start, end } = selectionObj;
const selected = start.column !== end.column || start.line !== end.line;
return selected;
}
/**
* Helper function to get text selection from the editor
*/
function getTextSelection(editor: CodeMirrorEditor) {
const selectionObj = editor.getSelection();
const start = editor.getOffsetAt(selectionObj.start);
const end = editor.getOffsetAt(selectionObj.end);
const text = editor.model.value.text.substring(start, end);
return text;
}
/**
* Function to create a new untitled text file, given the current working directory.
*/
async function createNew(
commands: CommandRegistry,
cwd: string,
ext: string = 'txt'
) {
const model = await commands.execute('docmanager:new-untitled', {
path: cwd,
type: 'file',
ext
});
if (model != undefined) {
const widget = ((await commands.execute('docmanager:open', {
path: model.path,
factory: FACTORY
})) as unknown) as IDocumentWidget;
widget.isUntitled = true;
return widget;
}
}
/**
* Add the New File command
*
* Defaults to Text/.txt if file type data is not specified
*/
export function addCreateNewCommand(
commands: CommandRegistry,
browserFactory: IFileBrowserFactory,
trans: TranslationBundle
): void {
commands.addCommand(CommandIDs.createNew, {
label: args => {
if (args.isPalette) {
return (args.paletteLabel as string) ?? trans.__('New Text File');
}
return (args.launcherLabel as string) ?? trans.__('Text File');
},
caption: args =>
(args.caption as string) ?? trans.__('Create a new text file'),
icon: args =>
args.isPalette
? undefined
: LabIcon.resolve({
icon: (args.iconName as string) ?? textEditorIcon
}),
execute: args => {
const cwd = args.cwd || browserFactory.defaultBrowser.model.path;
return createNew(
commands,
cwd as string,
(args.fileExt as string) ?? 'txt'
);
}
});
}
/**
* Add the New Markdown File command
*/
export function addCreateNewMarkdownCommand(
commands: CommandRegistry,
browserFactory: IFileBrowserFactory,
trans: TranslationBundle
): void {
commands.addCommand(CommandIDs.createNewMarkdown, {
label: args =>
args['isPalette']
? trans.__('New Markdown File')
: trans.__('Markdown File'),
caption: trans.__('Create a new markdown file'),
icon: args => (args['isPalette'] ? undefined : markdownIcon),
execute: args => {
const cwd = args['cwd'] || browserFactory.defaultBrowser.model.path;
return createNew(commands, cwd as string, 'md');
}
});
}
/**
* Wrapper function for adding the default launcher items for File Editor