index.ts 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. // Copyright (c) Jupyter Development Team.
  2. // Distributed under the terms of the Modified BSD License.
  3. import * as CodeMirror
  4. from 'codemirror';
  5. import {
  6. Menu
  7. } from '@phosphor/widgets';
  8. import {
  9. JupyterLab, JupyterLabPlugin
  10. } from '@jupyterlab/application';
  11. import {
  12. IMainMenu, IEditMenu
  13. } from '@jupyterlab/mainmenu';
  14. import {
  15. IEditorServices
  16. } from '@jupyterlab/codeeditor';
  17. import {
  18. editorServices, CodeMirrorEditor, Mode
  19. } from '@jupyterlab/codemirror';
  20. import {
  21. ISettingRegistry, IStateDB
  22. } from '@jupyterlab/coreutils';
  23. import {
  24. IDocumentWidget
  25. } from '@jupyterlab/docregistry';
  26. import {
  27. IEditorTracker, FileEditor
  28. } from '@jupyterlab/fileeditor';
  29. /**
  30. * The command IDs used by the codemirror plugin.
  31. */
  32. namespace CommandIDs {
  33. export
  34. const changeKeyMap = 'codemirror:change-keymap';
  35. export
  36. const changeTheme = 'codemirror:change-theme';
  37. export
  38. const changeMode = 'codemirror:change-mode';
  39. export
  40. const find = 'codemirror:find';
  41. export
  42. const findAndReplace = 'codemirror:find-and-replace';
  43. }
  44. /**
  45. * The editor services.
  46. */
  47. const services: JupyterLabPlugin<IEditorServices> = {
  48. id: '@jupyterlab/codemirror-extension:services',
  49. provides: IEditorServices,
  50. activate: activateEditorServices
  51. };
  52. /**
  53. * The editor commands.
  54. */
  55. const commands: JupyterLabPlugin<void> = {
  56. id: '@jupyterlab/codemirror-extension:commands',
  57. requires: [
  58. IEditorTracker,
  59. IMainMenu,
  60. IStateDB,
  61. ISettingRegistry
  62. ],
  63. activate: activateEditorCommands,
  64. autoStart: true
  65. };
  66. /**
  67. * Export the plugins as default.
  68. */
  69. const plugins: JupyterLabPlugin<any>[] = [commands, services];
  70. export default plugins;
  71. /**
  72. * The plugin ID used as the key in the setting registry.
  73. */
  74. const id = commands.id;
  75. /**
  76. * Set up the editor services.
  77. */
  78. function activateEditorServices(app: JupyterLab): IEditorServices {
  79. CodeMirror.prototype.save = () => {
  80. app.commands.execute('docmanager:save');
  81. };
  82. return editorServices;
  83. }
  84. /**
  85. * Set up the editor widget menu and commands.
  86. */
  87. function activateEditorCommands(app: JupyterLab, tracker: IEditorTracker, mainMenu: IMainMenu, state: IStateDB, settingRegistry: ISettingRegistry): void {
  88. const { commands, restored } = app;
  89. let { theme, keyMap } = CodeMirrorEditor.defaultConfig;
  90. /**
  91. * Update the setting values.
  92. */
  93. function updateSettings(settings: ISettingRegistry.ISettings): void {
  94. keyMap = settings.get('keyMap').composite as string | null || keyMap;
  95. theme = settings.get('theme').composite as string | null || theme;
  96. }
  97. /**
  98. * Update the settings of the current tracker instances.
  99. */
  100. function updateTracker(): void {
  101. tracker.forEach(widget => {
  102. if (widget.content.editor instanceof CodeMirrorEditor) {
  103. let cm = widget.content.editor.editor;
  104. cm.setOption('keyMap', keyMap);
  105. cm.setOption('theme', theme);
  106. }
  107. });
  108. }
  109. // Fetch the initial state of the settings.
  110. Promise.all([settingRegistry.load(id), restored]).then(([settings]) => {
  111. updateSettings(settings);
  112. updateTracker();
  113. settings.changed.connect(() => {
  114. updateSettings(settings);
  115. updateTracker();
  116. });
  117. }).catch((reason: Error) => {
  118. console.error(reason.message);
  119. updateTracker();
  120. });
  121. /**
  122. * Handle the settings of new widgets.
  123. */
  124. tracker.widgetAdded.connect((sender, widget) => {
  125. if (widget.content.editor instanceof CodeMirrorEditor) {
  126. let cm = widget.content.editor.editor;
  127. cm.setOption('keyMap', keyMap);
  128. cm.setOption('theme', theme);
  129. }
  130. });
  131. /**
  132. * A test for whether the tracker has an active widget.
  133. */
  134. function isEnabled(): boolean {
  135. return tracker.currentWidget !== null &&
  136. tracker.currentWidget === app.shell.currentWidget;
  137. }
  138. /**
  139. * Create a menu for the editor.
  140. */
  141. const themeMenu = new Menu({ commands });
  142. const keyMapMenu = new Menu({ commands });
  143. const modeMenu = new Menu({ commands });
  144. themeMenu.title.label = 'Text Editor Theme';
  145. keyMapMenu.title.label = 'Text Editor Key Map';
  146. modeMenu.title.label = 'Text Editor Syntax Highlighting';
  147. commands.addCommand(CommandIDs.changeTheme, {
  148. label: args => args['theme'] as string,
  149. execute: args => {
  150. const key = 'theme';
  151. const value = theme = args['theme'] as string || theme;
  152. updateTracker();
  153. return settingRegistry.set(id, key, value).catch((reason: Error) => {
  154. console.error(`Failed to set ${id}:${key} - ${reason.message}`);
  155. });
  156. },
  157. isToggled: args => args['theme'] === theme
  158. });
  159. commands.addCommand(CommandIDs.changeKeyMap, {
  160. label: args => {
  161. let title = args['keyMap'] as string;
  162. return title === 'sublime' ? 'Sublime Text' : title;
  163. },
  164. execute: args => {
  165. const key = 'keyMap';
  166. const value = keyMap = args['keyMap'] as string || keyMap;
  167. updateTracker();
  168. return settingRegistry.set(id, key, value).catch((reason: Error) => {
  169. console.error(`Failed to set ${id}:${key} - ${reason.message}`);
  170. });
  171. },
  172. isToggled: args => args['keyMap'] === keyMap
  173. });
  174. commands.addCommand(CommandIDs.find, {
  175. label: 'Find...',
  176. execute: () => {
  177. let widget = tracker.currentWidget;
  178. if (!widget) {
  179. return;
  180. }
  181. let editor = widget.content.editor as CodeMirrorEditor;
  182. editor.execCommand('find');
  183. },
  184. isEnabled
  185. });
  186. commands.addCommand(CommandIDs.findAndReplace, {
  187. label: 'Find and Replace...',
  188. execute: () => {
  189. let widget = tracker.currentWidget;
  190. if (!widget) {
  191. return;
  192. }
  193. let editor = widget.content.editor as CodeMirrorEditor;
  194. editor.execCommand('replace');
  195. },
  196. isEnabled
  197. });
  198. commands.addCommand(CommandIDs.changeMode, {
  199. label: args => args['name'] as string,
  200. execute: args => {
  201. let name = args['name'] as string;
  202. let widget = tracker.currentWidget;
  203. if (name && widget) {
  204. let spec = Mode.findByName(name);
  205. if (spec) {
  206. widget.content.model.mimeType = spec.mime;
  207. }
  208. }
  209. },
  210. isEnabled,
  211. isToggled: args => {
  212. let widget = tracker.currentWidget;
  213. if (!widget) {
  214. return false;
  215. }
  216. let mime = widget.content.model.mimeType;
  217. let spec = Mode.findByMIME(mime);
  218. let name = spec && spec.name;
  219. return args['name'] === name;
  220. }
  221. });
  222. Mode.getModeInfo().sort((a, b) => {
  223. let aName = a.name || '';
  224. let bName = b.name || '';
  225. return aName.localeCompare(bName);
  226. }).forEach(spec => {
  227. // Avoid mode name with a curse word.
  228. if (spec.mode.indexOf('brainf') === 0) {
  229. return;
  230. }
  231. modeMenu.addItem({
  232. command: CommandIDs.changeMode,
  233. args: {...spec}
  234. });
  235. });
  236. [
  237. 'jupyter', 'default', 'abcdef', 'base16-dark', 'base16-light',
  238. 'hopscotch', 'material', 'mbo', 'mdn-like', 'seti', 'solarized dark',
  239. 'solarized light', 'the-matrix', 'xq-light', 'zenburn'
  240. ].forEach(name => themeMenu.addItem({
  241. command: CommandIDs.changeTheme,
  242. args: { theme: name }
  243. }));
  244. ['default', 'sublime', 'vim', 'emacs'].forEach(name => {
  245. keyMapMenu.addItem({
  246. command: CommandIDs.changeKeyMap,
  247. args: { keyMap: name }
  248. });
  249. });
  250. // Add some of the editor settings to the settings menu.
  251. mainMenu.settingsMenu.addGroup([
  252. { type: 'submenu' as Menu.ItemType, submenu: keyMapMenu },
  253. { type: 'submenu' as Menu.ItemType, submenu: themeMenu }
  254. ], 10);
  255. // Add the syntax highlighting submenu to the `View` menu.
  256. mainMenu.viewMenu.addGroup([{ type: 'submenu', submenu: modeMenu }], 40);
  257. // Add find-replace capabilities to the edit menu.
  258. mainMenu.editMenu.findReplacers.add({
  259. tracker,
  260. find: (widget: IDocumentWidget<FileEditor>) => {
  261. let editor = widget.content.editor as CodeMirrorEditor;
  262. editor.execCommand('find');
  263. },
  264. findAndReplace: (widget: IDocumentWidget<FileEditor>) => {
  265. let editor = widget.content.editor as CodeMirrorEditor;
  266. editor.execCommand('replace');
  267. }
  268. } as IEditMenu.IFindReplacer<IDocumentWidget<FileEditor>>);
  269. }