-
-
Notifications
You must be signed in to change notification settings - Fork 3.3k
/
index.ts
424 lines (387 loc) · 11.1 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
// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
/**
* @packageDocumentation
* @module codemirror-extension
*/
import {
ILabShell,
JupyterFrontEnd,
JupyterFrontEndPlugin
} from '@jupyterlab/application';
import { IEditorServices } from '@jupyterlab/codeeditor';
import {
CodeMirrorEditor,
editorServices,
EditorSyntaxStatus,
ICodeMirror,
Mode
} from '@jupyterlab/codemirror';
import { IDocumentWidget } from '@jupyterlab/docregistry';
import { FileEditor, IEditorTracker } from '@jupyterlab/fileeditor';
import { IEditMenu, IMainMenu } from '@jupyterlab/mainmenu';
import { ISettingRegistry } from '@jupyterlab/settingregistry';
import { IStatusBar } from '@jupyterlab/statusbar';
import { ITranslator } from '@jupyterlab/translation';
import CodeMirror from 'codemirror';
/**
* The command IDs used by the codemirror plugin.
*/
namespace CommandIDs {
export const changeKeyMap = 'codemirror:change-keymap';
export const changeTheme = 'codemirror:change-theme';
export const changeMode = 'codemirror:change-mode';
export const find = 'codemirror:find';
export const goToLine = 'codemirror:go-to-line';
}
/** The CodeMirror singleton. */
const codemirrorSingleton: JupyterFrontEndPlugin<ICodeMirror> = {
id: '@jupyterlab/codemirror-extension:codemirror',
provides: ICodeMirror,
activate: activateCodeMirror
};
/**
* The editor services.
*/
const services: JupyterFrontEndPlugin<IEditorServices> = {
id: '@jupyterlab/codemirror-extension:services',
provides: IEditorServices,
activate: activateEditorServices
};
/**
* The editor commands.
*/
const commands: JupyterFrontEndPlugin<void> = {
id: '@jupyterlab/codemirror-extension:commands',
requires: [IEditorTracker, ISettingRegistry, ITranslator, ICodeMirror],
optional: [IMainMenu],
activate: activateEditorCommands,
autoStart: true
};
/**
* The JupyterLab plugin for the EditorSyntax status item.
*/
export const editorSyntaxStatus: JupyterFrontEndPlugin<void> = {
id: '@jupyterlab/codemirror-extension:editor-syntax-status',
autoStart: true,
requires: [IEditorTracker, ILabShell, ITranslator],
optional: [IStatusBar],
activate: (
app: JupyterFrontEnd,
tracker: IEditorTracker,
labShell: ILabShell,
translator: ITranslator,
statusBar: IStatusBar | null
) => {
if (!statusBar) {
// Automatically disable if statusbar missing
return;
}
const item = new EditorSyntaxStatus({ commands: app.commands, translator });
labShell.currentChanged.connect(() => {
const current = labShell.currentWidget;
if (current && tracker.has(current) && item.model) {
item.model.editor = (current as IDocumentWidget<
FileEditor
>).content.editor;
}
});
statusBar.registerStatusItem(
'@jupyterlab/codemirror-extension:editor-syntax-status',
{
item,
align: 'left',
rank: 0,
isActive: () =>
!!labShell.currentWidget &&
!!tracker.currentWidget &&
labShell.currentWidget === tracker.currentWidget
}
);
}
};
/**
* Export the plugins as default.
*/
const plugins: JupyterFrontEndPlugin<any>[] = [
commands,
services,
editorSyntaxStatus,
codemirrorSingleton
];
export default plugins;
/**
* The plugin ID used as the key in the setting registry.
*/
const id = commands.id;
/**
* Set up the editor services.
*/
function activateEditorServices(app: JupyterFrontEnd): IEditorServices {
CodeMirror.prototype.save = () => {
void app.commands.execute('docmanager:save');
};
return editorServices;
}
/**
* Simplest implementation of the CodeMirror singleton provider.
*/
class CodeMirrorSingleton implements ICodeMirror {
get CodeMirror() {
return CodeMirror;
}
async ensureVimKeymap() {
if (!('Vim' in (CodeMirror as any))) {
// @ts-expect-error
await import('codemirror/keymap/vim.js');
}
}
}
/**
* Set up the CodeMirror singleton.
*/
function activateCodeMirror(app: JupyterFrontEnd): ICodeMirror {
return new CodeMirrorSingleton();
}
/**
* Set up the editor widget menu and commands.
*/
function activateEditorCommands(
app: JupyterFrontEnd,
tracker: IEditorTracker,
settingRegistry: ISettingRegistry,
translator: ITranslator,
codeMirror: ICodeMirror,
mainMenu: IMainMenu | null
): void {
const trans = translator.load('jupyterlab');
const { commands, restored } = app;
let {
theme,
keyMap,
scrollPastEnd,
styleActiveLine,
styleSelectedText,
selectionPointer,
lineWiseCopyCut
} = CodeMirrorEditor.defaultConfig;
/**
* Update the setting values.
*/
async function updateSettings(
settings: ISettingRegistry.ISettings
): Promise<void> {
keyMap = (settings.get('keyMap').composite as string | null) || keyMap;
// Lazy loading of vim mode
if (keyMap === 'vim') {
await codeMirror.ensureVimKeymap();
}
theme = (settings.get('theme').composite as string | null) || theme;
// Lazy loading of theme stylesheets
if (theme !== 'jupyter' && theme !== 'default') {
const filename =
theme === 'solarized light' || theme === 'solarized dark'
? 'solarized'
: theme;
await import(`codemirror/theme/${filename}.css`);
}
scrollPastEnd =
(settings.get('scrollPastEnd').composite as boolean | null) ??
scrollPastEnd;
styleActiveLine =
(settings.get('styleActiveLine').composite as
| boolean
| CodeMirror.StyleActiveLine) ?? styleActiveLine;
styleSelectedText =
(settings.get('styleSelectedText').composite as boolean) ??
styleSelectedText;
selectionPointer =
(settings.get('selectionPointer').composite as boolean | string) ??
selectionPointer;
lineWiseCopyCut =
(settings.get('lineWiseCopyCut').composite as boolean) ?? lineWiseCopyCut;
}
/**
* Update the settings of the current tracker instances.
*/
function updateTracker(): void {
const editorOptions: any = {
keyMap,
theme,
scrollPastEnd,
styleActiveLine,
styleSelectedText,
selectionPointer,
lineWiseCopyCut
};
tracker.forEach(widget => {
if (widget.content.editor instanceof CodeMirrorEditor) {
widget.content.editor.setOptions(editorOptions);
}
});
}
// Fetch the initial state of the settings.
Promise.all([settingRegistry.load(id), restored])
.then(async ([settings]) => {
await updateSettings(settings);
updateTracker();
settings.changed.connect(async () => {
await updateSettings(settings);
updateTracker();
});
})
.catch((reason: Error) => {
console.error(reason.message);
updateTracker();
});
/**
* Handle the settings of new widgets.
*/
tracker.widgetAdded.connect((sender, widget) => {
const editorOptions: any = {
keyMap,
theme,
scrollPastEnd,
styleActiveLine,
styleSelectedText,
selectionPointer,
lineWiseCopyCut
};
if (widget.content.editor instanceof CodeMirrorEditor) {
widget.content.editor.setOptions(editorOptions);
}
});
/**
* A test for whether the tracker has an active widget.
*/
function isEnabled(): boolean {
return (
tracker.currentWidget !== null &&
tracker.currentWidget === app.shell.currentWidget
);
}
/**
* Create a menu for the editor.
*/
commands.addCommand(CommandIDs.changeTheme, {
label: args =>
args.theme === 'default'
? trans.__('codemirror')
: trans.__((args.theme as string) ?? theme),
execute: args => {
const key = 'theme';
const value = (theme = (args['theme'] as string) ?? theme);
return settingRegistry.set(id, key, value).catch((reason: Error) => {
console.error(`Failed to set ${id}:${key} - ${reason.message}`);
});
},
isToggled: args => args['theme'] === theme
});
commands.addCommand(CommandIDs.changeKeyMap, {
label: args => {
const theKeyMap = (args['keyMap'] as string) ?? keyMap;
return theKeyMap === 'sublime'
? trans.__('Sublime Text')
: trans.__(theKeyMap);
},
execute: args => {
const key = 'keyMap';
const value = (keyMap = (args['keyMap'] as string) ?? keyMap);
return settingRegistry.set(id, key, value).catch((reason: Error) => {
console.error(`Failed to set ${id}:${key} - ${reason.message}`);
});
},
isToggled: args => args['keyMap'] === keyMap
});
commands.addCommand(CommandIDs.find, {
label: trans.__('Find…'),
execute: () => {
const widget = tracker.currentWidget;
if (!widget) {
return;
}
const editor = widget.content.editor as CodeMirrorEditor;
editor.execCommand('find');
},
isEnabled
});
commands.addCommand(CommandIDs.goToLine, {
label: trans.__('Go to Line…'),
execute: args => {
const widget = tracker.currentWidget;
if (!widget) {
return;
}
const line = args['line'] as number | undefined;
const column = args['column'] as number | undefined;
const editor = widget.content.editor as CodeMirrorEditor;
if (line !== undefined || column !== undefined) {
editor.setCursorPosition({
line: (line ?? 1) - 1,
column: (column ?? 1) - 1
});
} else {
editor.execCommand('jumpToLine');
}
editor.focus();
},
isEnabled
});
commands.addCommand(CommandIDs.changeMode, {
label: args => args['name'] as string,
execute: args => {
const name = args['name'] as string;
const widget = tracker.currentWidget;
if (name && widget) {
const spec = Mode.findByName(name);
if (spec) {
widget.content.model.mimeType = spec.mime;
}
}
},
isEnabled,
isToggled: args => {
const widget = tracker.currentWidget;
if (!widget) {
return false;
}
const mime = widget.content.model.mimeType;
const spec = Mode.findByMIME(mime);
const name = spec && spec.name;
return args['name'] === name;
}
});
if (mainMenu) {
const modeMenu = mainMenu.viewMenu.items.find(
item =>
item.type === 'submenu' &&
item.submenu?.id === 'jp-mainmenu-view-codemirror-theme'
)?.submenu;
if (modeMenu) {
Mode.getModeInfo()
.sort((a, b) => {
const aName = a.name || '';
const bName = b.name || '';
return aName.localeCompare(bName);
})
.forEach(spec => {
// Avoid mode name with a curse word.
if (spec.mode.indexOf('brainf') === 0) {
return;
}
modeMenu.addItem({
command: CommandIDs.changeMode,
args: { ...spec } as any // TODO: Casting to `any` until lumino typings are fixed
});
});
}
// Add go to line capabilities to the edit menu.
mainMenu.editMenu.goToLiners.add({
tracker,
goToLine: (widget: IDocumentWidget<FileEditor>) => {
const editor = widget.content.editor as CodeMirrorEditor;
editor.execCommand('jumpToLine');
}
} as IEditMenu.IGoToLiner<IDocumentWidget<FileEditor>>);
}
}