index.ts 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245
  1. // Copyright (c) Jupyter Development Team.
  2. // Distributed under the terms of the Modified BSD License.
  3. import {
  4. ILabShell,
  5. ILayoutRestorer,
  6. JupyterFrontEnd,
  7. JupyterFrontEndPlugin
  8. } from '@jupyterlab/application';
  9. import {
  10. Dialog,
  11. ICommandPalette,
  12. InstanceTracker,
  13. MainAreaWidget,
  14. showDialog
  15. } from '@jupyterlab/apputils';
  16. import { CodeCell } from '@jupyterlab/cells';
  17. import { CodeEditor, IEditorServices } from '@jupyterlab/codeeditor';
  18. import {
  19. ISettingRegistry,
  20. IStateDB,
  21. PageConfig,
  22. URLExt
  23. } from '@jupyterlab/coreutils';
  24. import { IDocumentManager } from '@jupyterlab/docmanager';
  25. import { ArrayExt } from '@phosphor/algorithm';
  26. import { UUID } from '@phosphor/coreutils';
  27. import { DisposableSet } from '@phosphor/disposable';
  28. import { IFileBrowserFactory } from '@jupyterlab/filebrowser';
  29. import { ILauncher } from '@jupyterlab/launcher';
  30. import {
  31. IMainMenu,
  32. IEditMenu,
  33. IFileMenu,
  34. IHelpMenu,
  35. IKernelMenu,
  36. IRunMenu,
  37. IViewMenu
  38. } from '@jupyterlab/mainmenu';
  39. import {
  40. NotebookTools,
  41. INotebookTools,
  42. INotebookTracker,
  43. NotebookActions,
  44. NotebookModelFactory,
  45. NotebookPanel,
  46. NotebookTracker,
  47. NotebookWidgetFactory,
  48. StaticNotebook,
  49. CommandEditStatus,
  50. NotebookTrustStatus
  51. } from '@jupyterlab/notebook';
  52. import { IRenderMimeRegistry } from '@jupyterlab/rendermime';
  53. import { ServiceManager } from '@jupyterlab/services';
  54. import { IStatusBar } from '@jupyterlab/statusbar';
  55. import { ReadonlyJSONObject, JSONValue } from '@phosphor/coreutils';
  56. import { Message, MessageLoop } from '@phosphor/messaging';
  57. import { Panel, Menu } from '@phosphor/widgets';
  58. /**
  59. * The command IDs used by the notebook plugin.
  60. */
  61. namespace CommandIDs {
  62. export const createNew = 'notebook:create-new';
  63. export const interrupt = 'notebook:interrupt-kernel';
  64. export const restart = 'notebook:restart-kernel';
  65. export const restartClear = 'notebook:restart-clear-output';
  66. export const restartRunAll = 'notebook:restart-run-all';
  67. export const reconnectToKernel = 'notebook:reconnect-to-kernel';
  68. export const changeKernel = 'notebook:change-kernel';
  69. export const createConsole = 'notebook:create-console';
  70. export const createOutputView = 'notebook:create-output-view';
  71. export const clearAllOutputs = 'notebook:clear-all-cell-outputs';
  72. export const closeAndShutdown = 'notebook:close-and-shutdown';
  73. export const trust = 'notebook:trust';
  74. export const exportToFormat = 'notebook:export-to-format';
  75. export const run = 'notebook:run-cell';
  76. export const runAndAdvance = 'notebook:run-cell-and-select-next';
  77. export const runAndInsert = 'notebook:run-cell-and-insert-below';
  78. export const runInConsole = 'notebook:run-in-console';
  79. export const runAll = 'notebook:run-all-cells';
  80. export const runAllAbove = 'notebook:run-all-above';
  81. export const runAllBelow = 'notebook:run-all-below';
  82. export const renderAllMarkdown = 'notebook:render-all-markdown';
  83. export const toCode = 'notebook:change-cell-to-code';
  84. export const toMarkdown = 'notebook:change-cell-to-markdown';
  85. export const toRaw = 'notebook:change-cell-to-raw';
  86. export const cut = 'notebook:cut-cell';
  87. export const copy = 'notebook:copy-cell';
  88. export const pasteAbove = 'notebook:paste-cell-above';
  89. export const pasteBelow = 'notebook:paste-cell-below';
  90. export const pasteAndReplace = 'notebook:paste-and-replace-cell';
  91. export const moveUp = 'notebook:move-cell-up';
  92. export const moveDown = 'notebook:move-cell-down';
  93. export const clearOutputs = 'notebook:clear-cell-output';
  94. export const deleteCell = 'notebook:delete-cell';
  95. export const insertAbove = 'notebook:insert-cell-above';
  96. export const insertBelow = 'notebook:insert-cell-below';
  97. export const selectAbove = 'notebook:move-cursor-up';
  98. export const selectBelow = 'notebook:move-cursor-down';
  99. export const extendAbove = 'notebook:extend-marked-cells-above';
  100. export const extendBelow = 'notebook:extend-marked-cells-below';
  101. export const selectAll = 'notebook:select-all';
  102. export const deselectAll = 'notebook:deselect-all';
  103. export const editMode = 'notebook:enter-edit-mode';
  104. export const merge = 'notebook:merge-cells';
  105. export const split = 'notebook:split-cell-at-cursor';
  106. export const commandMode = 'notebook:enter-command-mode';
  107. export const toggleAllLines = 'notebook:toggle-all-cell-line-numbers';
  108. export const undoCellAction = 'notebook:undo-cell-action';
  109. export const redoCellAction = 'notebook:redo-cell-action';
  110. export const markdown1 = 'notebook:change-cell-to-heading-1';
  111. export const markdown2 = 'notebook:change-cell-to-heading-2';
  112. export const markdown3 = 'notebook:change-cell-to-heading-3';
  113. export const markdown4 = 'notebook:change-cell-to-heading-4';
  114. export const markdown5 = 'notebook:change-cell-to-heading-5';
  115. export const markdown6 = 'notebook:change-cell-to-heading-6';
  116. export const hideCode = 'notebook:hide-cell-code';
  117. export const showCode = 'notebook:show-cell-code';
  118. export const hideAllCode = 'notebook:hide-all-cell-code';
  119. export const showAllCode = 'notebook:show-all-cell-code';
  120. export const hideOutput = 'notebook:hide-cell-outputs';
  121. export const showOutput = 'notebook:show-cell-outputs';
  122. export const hideAllOutputs = 'notebook:hide-all-cell-outputs';
  123. export const showAllOutputs = 'notebook:show-all-cell-outputs';
  124. export const enableOutputScrolling = 'notebook:enable-output-scrolling';
  125. export const disableOutputScrolling = 'notebook:disable-output-scrolling';
  126. }
  127. /**
  128. * The class name for the notebook icon from the default theme.
  129. */
  130. const NOTEBOOK_ICON_CLASS = 'jp-NotebookIcon';
  131. /**
  132. * The name of the factory that creates notebooks.
  133. */
  134. const FACTORY = 'Notebook';
  135. /**
  136. * The rank of the notebook tools tab in the sidebar
  137. */
  138. const NOTEBOOK_TOOLS_RANK = 400;
  139. /**
  140. * The exluded Export To ...
  141. * (returned from nbconvert's export list)
  142. */
  143. const FORMAT_EXCLUDE = ['notebook', 'python', 'custom'];
  144. /**
  145. * The exluded Cell Inspector Raw NbConvert Formats
  146. * (returned from nbconvert's export list)
  147. */
  148. const RAW_FORMAT_EXCLUDE = ['pdf', 'slides', 'script', 'notebook', 'custom'];
  149. /**
  150. * The default Export To ... formats and their human readable labels.
  151. */
  152. const FORMAT_LABEL: { [k: string]: string } = {
  153. html: 'HTML',
  154. latex: 'LaTeX',
  155. markdown: 'Markdown',
  156. pdf: 'PDF',
  157. rst: 'ReStructured Text',
  158. script: 'Executable Script',
  159. slides: 'Reveal.js Slides'
  160. };
  161. /**
  162. * The notebook widget tracker provider.
  163. */
  164. const trackerPlugin: JupyterFrontEndPlugin<INotebookTracker> = {
  165. id: '@jupyterlab/notebook-extension:tracker',
  166. provides: INotebookTracker,
  167. requires: [
  168. NotebookPanel.IContentFactory,
  169. IDocumentManager,
  170. IEditorServices,
  171. IRenderMimeRegistry
  172. ],
  173. optional: [
  174. ICommandPalette,
  175. IFileBrowserFactory,
  176. ILauncher,
  177. ILayoutRestorer,
  178. IMainMenu,
  179. ISettingRegistry
  180. ],
  181. activate: activateNotebookHandler,
  182. autoStart: true
  183. };
  184. /**
  185. * The notebook cell factory provider.
  186. */
  187. const factory: JupyterFrontEndPlugin<NotebookPanel.IContentFactory> = {
  188. id: '@jupyterlab/notebook-extension:factory',
  189. provides: NotebookPanel.IContentFactory,
  190. requires: [IEditorServices],
  191. autoStart: true,
  192. activate: (app: JupyterFrontEnd, editorServices: IEditorServices) => {
  193. let editorFactory = editorServices.factoryService.newInlineEditor;
  194. return new NotebookPanel.ContentFactory({ editorFactory });
  195. }
  196. };
  197. /**
  198. * The notebook tools extension.
  199. */
  200. const tools: JupyterFrontEndPlugin<INotebookTools> = {
  201. activate: activateNotebookTools,
  202. provides: INotebookTools,
  203. id: '@jupyterlab/notebook-extension:tools',
  204. autoStart: true,
  205. requires: [INotebookTracker, IEditorServices, IStateDB],
  206. optional: [ILabShell]
  207. };
  208. /**
  209. * A plugin providing a CommandEdit status item.
  210. */
  211. export const commandEditItem: JupyterFrontEndPlugin<void> = {
  212. id: '@jupyterlab/notebook-extension:mode-status',
  213. autoStart: true,
  214. requires: [IStatusBar, INotebookTracker],
  215. activate: (
  216. app: JupyterFrontEnd,
  217. statusBar: IStatusBar,
  218. tracker: INotebookTracker
  219. ) => {
  220. const { shell } = app;
  221. const item = new CommandEditStatus();
  222. // Keep the status item up-to-date with the current notebook.
  223. tracker.currentChanged.connect(() => {
  224. const current = tracker.currentWidget;
  225. item.model.notebook = current && current.content;
  226. });
  227. statusBar.registerStatusItem('@jupyterlab/notebook-extension:mode-status', {
  228. item,
  229. align: 'right',
  230. rank: 4,
  231. isActive: () =>
  232. shell.currentWidget &&
  233. tracker.currentWidget &&
  234. shell.currentWidget === tracker.currentWidget
  235. });
  236. }
  237. };
  238. /**
  239. * A plugin that adds a notebook trust status item to the status bar.
  240. */
  241. export const notebookTrustItem: JupyterFrontEndPlugin<void> = {
  242. id: '@jupyterlab/notebook-extension:trust-status',
  243. autoStart: true,
  244. requires: [IStatusBar, INotebookTracker, ILabShell],
  245. activate: (
  246. app: JupyterFrontEnd,
  247. statusBar: IStatusBar,
  248. tracker: INotebookTracker
  249. ) => {
  250. const { shell } = app;
  251. const item = new NotebookTrustStatus();
  252. // Keep the status item up-to-date with the current notebook.
  253. tracker.currentChanged.connect(() => {
  254. const current = tracker.currentWidget;
  255. item.model.notebook = current && current.content;
  256. });
  257. statusBar.registerStatusItem(
  258. '@jupyterlab/notebook-extension:trust-status',
  259. {
  260. item,
  261. align: 'right',
  262. rank: 3,
  263. isActive: () =>
  264. shell.currentWidget &&
  265. tracker.currentWidget &&
  266. shell.currentWidget === tracker.currentWidget
  267. }
  268. );
  269. }
  270. };
  271. /**
  272. * Export the plugins as default.
  273. */
  274. const plugins: JupyterFrontEndPlugin<any>[] = [
  275. factory,
  276. trackerPlugin,
  277. tools,
  278. commandEditItem,
  279. notebookTrustItem
  280. ];
  281. export default plugins;
  282. /**
  283. * Activate the notebook tools extension.
  284. */
  285. function activateNotebookTools(
  286. app: JupyterFrontEnd,
  287. tracker: INotebookTracker,
  288. editorServices: IEditorServices,
  289. state: IStateDB,
  290. labShell: ILabShell | null
  291. ): INotebookTools {
  292. const id = 'notebook-tools';
  293. const notebookTools = new NotebookTools({ tracker });
  294. const activeCellTool = new NotebookTools.ActiveCellTool();
  295. const slideShow = NotebookTools.createSlideShowSelector();
  296. const editorFactory = editorServices.factoryService.newInlineEditor;
  297. const cellMetadataEditor = new NotebookTools.CellMetadataEditorTool({
  298. editorFactory,
  299. collapsed: false
  300. });
  301. const notebookMetadataEditor = new NotebookTools.NotebookMetadataEditorTool({
  302. editorFactory
  303. });
  304. const services = app.serviceManager;
  305. // Create message hook for triggers to save to the database.
  306. const hook = (sender: any, message: Message): boolean => {
  307. switch (message.type) {
  308. case 'activate-request':
  309. void state.save(id, { open: true });
  310. break;
  311. case 'after-hide':
  312. case 'close-request':
  313. void state.remove(id);
  314. break;
  315. default:
  316. break;
  317. }
  318. return true;
  319. };
  320. let optionsMap: { [key: string]: JSONValue } = {};
  321. optionsMap.None = null;
  322. void services.nbconvert.getExportFormats().then(response => {
  323. if (response) {
  324. // convert exportList to palette and menu items
  325. const formatList = Object.keys(response);
  326. formatList.forEach(function(key) {
  327. if (RAW_FORMAT_EXCLUDE.indexOf(key) === -1) {
  328. let capCaseKey = key[0].toUpperCase() + key.substr(1);
  329. let labelStr = FORMAT_LABEL[key] ? FORMAT_LABEL[key] : capCaseKey;
  330. let mimeType = response[key].output_mimetype;
  331. optionsMap[labelStr] = mimeType;
  332. }
  333. });
  334. const nbConvert = NotebookTools.createNBConvertSelector(optionsMap);
  335. notebookTools.addItem({ tool: nbConvert, section: 'common', rank: 3 });
  336. }
  337. });
  338. notebookTools.title.iconClass = 'jp-BuildIcon jp-SideBar-tabIcon';
  339. notebookTools.title.caption = 'Notebook Tools';
  340. notebookTools.id = id;
  341. notebookTools.addItem({ tool: activeCellTool, section: 'common', rank: 1 });
  342. notebookTools.addItem({ tool: slideShow, section: 'common', rank: 2 });
  343. notebookTools.addItem({
  344. tool: cellMetadataEditor,
  345. section: 'advanced',
  346. rank: 1
  347. });
  348. notebookTools.addItem({
  349. tool: notebookMetadataEditor,
  350. section: 'advanced',
  351. rank: 2
  352. });
  353. MessageLoop.installMessageHook(notebookTools, hook);
  354. // Wait until the application has finished restoring before rendering.
  355. void Promise.all([state.fetch(id), app.restored]).then(([value]) => {
  356. const open = !!(
  357. value && ((value as ReadonlyJSONObject)['open'] as boolean)
  358. );
  359. // After initial restoration, check if the notebook tools should render.
  360. if (tracker.size) {
  361. app.shell.add(notebookTools, 'left', { rank: NOTEBOOK_TOOLS_RANK });
  362. if (open) {
  363. app.shell.activateById(notebookTools.id);
  364. }
  365. }
  366. const updateTools = () => {
  367. // If there are any open notebooks, add notebook tools to the side panel if
  368. // it is not already there.
  369. if (tracker.size) {
  370. if (!notebookTools.isAttached) {
  371. labShell.add(notebookTools, 'left', { rank: NOTEBOOK_TOOLS_RANK });
  372. }
  373. return;
  374. }
  375. // If there are no notebooks, close notebook tools.
  376. notebookTools.close();
  377. };
  378. // For all subsequent widget changes, check if the notebook tools should render.
  379. if (labShell) {
  380. labShell.currentChanged.connect((sender, args) => {
  381. updateTools();
  382. });
  383. } else {
  384. tracker.currentChanged.connect((sender, args) => {
  385. updateTools();
  386. });
  387. }
  388. });
  389. return notebookTools;
  390. }
  391. /**
  392. * Activate the notebook handler extension.
  393. */
  394. function activateNotebookHandler(
  395. app: JupyterFrontEnd,
  396. contentFactory: NotebookPanel.IContentFactory,
  397. docManager: IDocumentManager,
  398. editorServices: IEditorServices,
  399. rendermime: IRenderMimeRegistry,
  400. palette: ICommandPalette | null,
  401. browserFactory: IFileBrowserFactory | null,
  402. launcher: ILauncher | null,
  403. restorer: ILayoutRestorer | null,
  404. mainMenu: IMainMenu | null,
  405. settingRegistry: ISettingRegistry | null
  406. ): INotebookTracker {
  407. const services = app.serviceManager;
  408. // An object for tracking the current notebook settings.
  409. let editorConfig = StaticNotebook.defaultEditorConfig;
  410. let notebookConfig = StaticNotebook.defaultNotebookConfig;
  411. const factory = new NotebookWidgetFactory({
  412. name: FACTORY,
  413. fileTypes: ['notebook'],
  414. modelName: 'notebook',
  415. defaultFor: ['notebook'],
  416. preferKernel: true,
  417. canStartKernel: true,
  418. rendermime: rendermime,
  419. contentFactory,
  420. editorConfig,
  421. notebookConfig,
  422. mimeTypeService: editorServices.mimeTypeService
  423. });
  424. const { commands } = app;
  425. const tracker = new NotebookTracker({ namespace: 'notebook' });
  426. const clonedOutputs = new InstanceTracker<
  427. MainAreaWidget<Private.ClonedOutputArea>
  428. >({
  429. namespace: 'cloned-outputs'
  430. });
  431. // Handle state restoration.
  432. if (restorer) {
  433. restorer.restore(tracker, {
  434. command: 'docmanager:open',
  435. args: panel => ({ path: panel.context.path, factory: FACTORY }),
  436. name: panel => panel.context.path,
  437. when: services.ready
  438. });
  439. restorer.restore(clonedOutputs, {
  440. command: CommandIDs.createOutputView,
  441. args: widget => ({
  442. path: widget.content.path,
  443. index: widget.content.index
  444. }),
  445. name: widget => `${widget.content.path}:${widget.content.index}`,
  446. when: tracker.restored // After the notebook widgets (but not contents).
  447. });
  448. }
  449. let registry = app.docRegistry;
  450. registry.addModelFactory(new NotebookModelFactory({}));
  451. registry.addWidgetFactory(factory);
  452. addCommands(app, docManager, services, tracker, clonedOutputs);
  453. if (palette) {
  454. populatePalette(palette, services);
  455. }
  456. let id = 0; // The ID counter for notebook panels.
  457. factory.widgetCreated.connect((sender, widget) => {
  458. // If the notebook panel does not have an ID, assign it one.
  459. widget.id = widget.id || `notebook-${++id}`;
  460. widget.title.icon = NOTEBOOK_ICON_CLASS;
  461. // Notify the instance tracker if restore data needs to update.
  462. widget.context.pathChanged.connect(() => {
  463. void tracker.save(widget);
  464. });
  465. // Add the notebook panel to the tracker.
  466. void tracker.add(widget);
  467. });
  468. /**
  469. * Update the setting values.
  470. */
  471. function updateConfig(settings: ISettingRegistry.ISettings): void {
  472. let cached = settings.get('codeCellConfig').composite as Partial<
  473. CodeEditor.IConfig
  474. >;
  475. let code = { ...StaticNotebook.defaultEditorConfig.code };
  476. Object.keys(code).forEach((key: keyof CodeEditor.IConfig) => {
  477. code[key] =
  478. cached[key] === null || cached[key] === undefined
  479. ? code[key]
  480. : cached[key];
  481. });
  482. cached = settings.get('markdownCellConfig').composite as Partial<
  483. CodeEditor.IConfig
  484. >;
  485. let markdown = { ...StaticNotebook.defaultEditorConfig.markdown };
  486. Object.keys(markdown).forEach((key: keyof CodeEditor.IConfig) => {
  487. markdown[key] =
  488. cached[key] === null || cached[key] === undefined
  489. ? markdown[key]
  490. : cached[key];
  491. });
  492. cached = settings.get('rawCellConfig').composite as Partial<
  493. CodeEditor.IConfig
  494. >;
  495. let raw = { ...StaticNotebook.defaultEditorConfig.raw };
  496. Object.keys(raw).forEach((key: keyof CodeEditor.IConfig) => {
  497. raw[key] =
  498. cached[key] === null || cached[key] === undefined
  499. ? raw[key]
  500. : cached[key];
  501. });
  502. factory.editorConfig = editorConfig = { code, markdown, raw };
  503. factory.notebookConfig = notebookConfig = {
  504. scrollPastEnd: settings.get('scrollPastEnd').composite as boolean
  505. };
  506. factory.shutdownOnClose = settings.get('kernelShutdown')
  507. .composite as boolean;
  508. }
  509. /**
  510. * Update the settings of the current tracker.
  511. */
  512. function updateTracker(settings: ISettingRegistry.ISettings | null): void {
  513. tracker.forEach(widget => {
  514. widget.content.editorConfig = editorConfig;
  515. widget.content.notebookConfig = notebookConfig;
  516. // Update kernel shutdown behavior
  517. const kernelPreference = widget.context.session.kernelPreference;
  518. widget.context.session.kernelPreference = {
  519. ...kernelPreference,
  520. shutdownOnClose: factory.shutdownOnClose
  521. };
  522. });
  523. }
  524. // Fetch settings if possible.
  525. const fetchSettings = settingRegistry
  526. ? settingRegistry.load(trackerPlugin.id)
  527. : Promise.reject(new Error(`No setting registry for ${trackerPlugin.id}`));
  528. app.restored
  529. .then(() => fetchSettings)
  530. .then(settings => {
  531. updateConfig(settings);
  532. updateTracker(settings);
  533. settings.changed.connect(() => {
  534. updateConfig(settings);
  535. updateTracker(settings);
  536. });
  537. })
  538. .catch((reason: Error) => {
  539. console.warn(reason.message);
  540. updateTracker(null);
  541. });
  542. // Add main menu notebook menu.
  543. if (mainMenu) {
  544. populateMenus(app, mainMenu, tracker, services, palette);
  545. }
  546. // Utility function to create a new notebook.
  547. const createNew = (cwd: string, kernelName?: string) => {
  548. return commands
  549. .execute('docmanager:new-untitled', { path: cwd, type: 'notebook' })
  550. .then(model => {
  551. return commands.execute('docmanager:open', {
  552. path: model.path,
  553. factory: FACTORY,
  554. kernel: { name: kernelName }
  555. });
  556. });
  557. };
  558. // Add a command for creating a new notebook.
  559. commands.addCommand(CommandIDs.createNew, {
  560. label: args => {
  561. const kernelName = (args['kernelName'] as string) || '';
  562. if (args['isLauncher'] && args['kernelName']) {
  563. return services.specs.kernelspecs[kernelName].display_name;
  564. }
  565. if (args['isPalette']) {
  566. return 'New Notebook';
  567. }
  568. return 'Notebook';
  569. },
  570. caption: 'Create a new notebook',
  571. iconClass: args => (args['isPalette'] ? '' : 'jp-NotebookIcon'),
  572. execute: args => {
  573. const cwd =
  574. (args['cwd'] as string) ||
  575. (browserFactory ? browserFactory.defaultBrowser.model.path : '');
  576. const kernelName = (args['kernelName'] as string) || '';
  577. return createNew(cwd, kernelName);
  578. }
  579. });
  580. // Add a launcher item if the launcher is available.
  581. if (launcher) {
  582. void services.ready.then(() => {
  583. let disposables: DisposableSet | null = null;
  584. const onSpecsChanged = () => {
  585. if (disposables) {
  586. disposables.dispose();
  587. disposables = null;
  588. }
  589. const specs = services.specs;
  590. if (!specs) {
  591. return;
  592. }
  593. disposables = new DisposableSet();
  594. const baseUrl = PageConfig.getBaseUrl();
  595. for (let name in specs.kernelspecs) {
  596. let rank = name === specs.default ? 0 : Infinity;
  597. let kernelIconUrl = specs.kernelspecs[name].resources['logo-64x64'];
  598. if (kernelIconUrl) {
  599. let index = kernelIconUrl.indexOf('kernelspecs');
  600. kernelIconUrl = baseUrl + kernelIconUrl.slice(index);
  601. }
  602. disposables.add(
  603. launcher.add({
  604. command: CommandIDs.createNew,
  605. args: { isLauncher: true, kernelName: name },
  606. category: 'Notebook',
  607. rank,
  608. kernelIconUrl
  609. })
  610. );
  611. }
  612. };
  613. onSpecsChanged();
  614. services.specsChanged.connect(onSpecsChanged);
  615. });
  616. }
  617. // Cell context menu groups
  618. app.contextMenu.addItem({
  619. type: 'separator',
  620. selector: '.jp-Notebook .jp-Cell',
  621. rank: 0
  622. });
  623. app.contextMenu.addItem({
  624. command: CommandIDs.cut,
  625. selector: '.jp-Notebook .jp-Cell',
  626. rank: 1
  627. });
  628. app.contextMenu.addItem({
  629. command: CommandIDs.copy,
  630. selector: '.jp-Notebook .jp-Cell',
  631. rank: 2
  632. });
  633. app.contextMenu.addItem({
  634. command: CommandIDs.pasteBelow,
  635. selector: '.jp-Notebook .jp-Cell',
  636. rank: 3
  637. });
  638. app.contextMenu.addItem({
  639. type: 'separator',
  640. selector: '.jp-Notebook .jp-Cell',
  641. rank: 4
  642. });
  643. app.contextMenu.addItem({
  644. command: CommandIDs.deleteCell,
  645. selector: '.jp-Notebook .jp-Cell',
  646. rank: 5
  647. });
  648. app.contextMenu.addItem({
  649. type: 'separator',
  650. selector: '.jp-Notebook .jp-Cell',
  651. rank: 6
  652. });
  653. app.contextMenu.addItem({
  654. command: CommandIDs.split,
  655. selector: '.jp-Notebook .jp-Cell',
  656. rank: 7
  657. });
  658. app.contextMenu.addItem({
  659. type: 'separator',
  660. selector: '.jp-Notebook .jp-Cell',
  661. rank: 8
  662. });
  663. // CodeCell context menu groups
  664. app.contextMenu.addItem({
  665. command: CommandIDs.createOutputView,
  666. selector: '.jp-Notebook .jp-CodeCell',
  667. rank: 9
  668. });
  669. app.contextMenu.addItem({
  670. type: 'separator',
  671. selector: '.jp-Notebook .jp-CodeCell',
  672. rank: 10
  673. });
  674. app.contextMenu.addItem({
  675. command: CommandIDs.clearOutputs,
  676. selector: '.jp-Notebook .jp-CodeCell',
  677. rank: 11
  678. });
  679. // Notebook context menu groups
  680. app.contextMenu.addItem({
  681. command: CommandIDs.clearAllOutputs,
  682. selector: '.jp-Notebook',
  683. rank: 0
  684. });
  685. app.contextMenu.addItem({
  686. type: 'separator',
  687. selector: '.jp-Notebook',
  688. rank: 1
  689. });
  690. app.contextMenu.addItem({
  691. command: CommandIDs.enableOutputScrolling,
  692. selector: '.jp-Notebook',
  693. rank: 2
  694. });
  695. app.contextMenu.addItem({
  696. command: CommandIDs.disableOutputScrolling,
  697. selector: '.jp-Notebook',
  698. rank: 3
  699. });
  700. app.contextMenu.addItem({
  701. type: 'separator',
  702. selector: '.jp-Notebook',
  703. rank: 4
  704. });
  705. app.contextMenu.addItem({
  706. command: CommandIDs.undoCellAction,
  707. selector: '.jp-Notebook',
  708. rank: 5
  709. });
  710. app.contextMenu.addItem({
  711. command: CommandIDs.redoCellAction,
  712. selector: '.jp-Notebook',
  713. rank: 6
  714. });
  715. app.contextMenu.addItem({
  716. command: CommandIDs.restart,
  717. selector: '.jp-Notebook',
  718. rank: 7
  719. });
  720. app.contextMenu.addItem({
  721. type: 'separator',
  722. selector: '.jp-Notebook',
  723. rank: 8
  724. });
  725. app.contextMenu.addItem({
  726. command: CommandIDs.createConsole,
  727. selector: '.jp-Notebook',
  728. rank: 9
  729. });
  730. return tracker;
  731. }
  732. /**
  733. * Add the notebook commands to the application's command registry.
  734. */
  735. function addCommands(
  736. app: JupyterFrontEnd,
  737. docManager: IDocumentManager,
  738. services: ServiceManager,
  739. tracker: NotebookTracker,
  740. clonedOutputs: InstanceTracker<MainAreaWidget>
  741. ): void {
  742. const { commands, shell } = app;
  743. // Get the current widget and activate unless the args specify otherwise.
  744. function getCurrent(args: ReadonlyJSONObject): NotebookPanel | null {
  745. const widget = tracker.currentWidget;
  746. const activate = args['activate'] !== false;
  747. if (activate && widget) {
  748. shell.activateById(widget.id);
  749. }
  750. return widget;
  751. }
  752. /**
  753. * Whether there is an active notebook.
  754. */
  755. function isEnabled(): boolean {
  756. return (
  757. tracker.currentWidget !== null &&
  758. tracker.currentWidget === shell.currentWidget
  759. );
  760. }
  761. /**
  762. * Whether there is an notebook active, with a single selected cell.
  763. */
  764. function isEnabledAndSingleSelected(): boolean {
  765. if (!isEnabled()) {
  766. return false;
  767. }
  768. const { content } = tracker.currentWidget;
  769. const index = content.activeCellIndex;
  770. // If there are selections that are not the active cell,
  771. // this command is confusing, so disable it.
  772. for (let i = 0; i < content.widgets.length; ++i) {
  773. if (content.isSelected(content.widgets[i]) && i !== index) {
  774. return false;
  775. }
  776. }
  777. return true;
  778. }
  779. commands.addCommand(CommandIDs.runAndAdvance, {
  780. label: 'Run Selected Cells',
  781. execute: args => {
  782. const current = getCurrent(args);
  783. if (current) {
  784. const { context, content } = current;
  785. return NotebookActions.runAndAdvance(content, context.session);
  786. }
  787. },
  788. isEnabled
  789. });
  790. commands.addCommand(CommandIDs.run, {
  791. label: "Run Selected Cells and Don't Advance",
  792. execute: args => {
  793. const current = getCurrent(args);
  794. if (current) {
  795. const { context, content } = current;
  796. return NotebookActions.run(content, context.session);
  797. }
  798. },
  799. isEnabled
  800. });
  801. commands.addCommand(CommandIDs.runAndInsert, {
  802. label: 'Run Selected Cells and Insert Below',
  803. execute: args => {
  804. const current = getCurrent(args);
  805. if (current) {
  806. const { context, content } = current;
  807. return NotebookActions.runAndInsert(content, context.session);
  808. }
  809. },
  810. isEnabled
  811. });
  812. commands.addCommand(CommandIDs.runInConsole, {
  813. label: 'Run Selected Text or Current Line in Console',
  814. execute: async args => {
  815. // Default to not activating the notebook (thereby putting the notebook
  816. // into command mode)
  817. const current = getCurrent({ activate: false, ...args });
  818. if (!current) {
  819. return;
  820. }
  821. const { context, content } = current;
  822. let cell = content.activeCell;
  823. let metadata = cell.model.metadata.toJSON();
  824. let path = context.path;
  825. // ignore action in non-code cell
  826. if (!cell || cell.model.type !== 'code') {
  827. return;
  828. }
  829. let code: string;
  830. const editor = cell.editor;
  831. const selection = editor.getSelection();
  832. const { start, end } = selection;
  833. let selected = start.column !== end.column || start.line !== end.line;
  834. if (selected) {
  835. // Get the selected code from the editor.
  836. const start = editor.getOffsetAt(selection.start);
  837. const end = editor.getOffsetAt(selection.end);
  838. code = editor.model.value.text.substring(start, end);
  839. } else {
  840. // no selection, submit whole line and advance
  841. code = editor.getLine(selection.start.line);
  842. const cursor = editor.getCursorPosition();
  843. if (cursor.line + 1 !== editor.lineCount) {
  844. editor.setCursorPosition({
  845. line: cursor.line + 1,
  846. column: cursor.column
  847. });
  848. }
  849. }
  850. if (!code) {
  851. return;
  852. }
  853. await commands.execute('console:open', {
  854. activate: false,
  855. insertMode: 'split-bottom',
  856. path
  857. });
  858. await commands.execute('console:inject', {
  859. activate: false,
  860. code,
  861. path,
  862. metadata
  863. });
  864. },
  865. isEnabled
  866. });
  867. commands.addCommand(CommandIDs.runAll, {
  868. label: 'Run All Cells',
  869. execute: args => {
  870. const current = getCurrent(args);
  871. if (current) {
  872. const { context, content } = current;
  873. return NotebookActions.runAll(content, context.session);
  874. }
  875. },
  876. isEnabled
  877. });
  878. commands.addCommand(CommandIDs.runAllAbove, {
  879. label: 'Run All Above Selected Cell',
  880. execute: args => {
  881. const current = getCurrent(args);
  882. if (current) {
  883. const { context, content } = current;
  884. return NotebookActions.runAllAbove(content, context.session);
  885. }
  886. },
  887. isEnabled: () => {
  888. // Can't run above if there are multiple cells selected,
  889. // or if we are at the top of the notebook.
  890. return (
  891. isEnabledAndSingleSelected() &&
  892. tracker.currentWidget.content.activeCellIndex !== 0
  893. );
  894. }
  895. });
  896. commands.addCommand(CommandIDs.runAllBelow, {
  897. label: 'Run Selected Cell and All Below',
  898. execute: args => {
  899. const current = getCurrent(args);
  900. if (current) {
  901. const { context, content } = current;
  902. return NotebookActions.runAllBelow(content, context.session);
  903. }
  904. },
  905. isEnabled: () => {
  906. // Can't run below if there are multiple cells selected,
  907. // or if we are at the bottom of the notebook.
  908. return (
  909. isEnabledAndSingleSelected() &&
  910. tracker.currentWidget.content.activeCellIndex !==
  911. tracker.currentWidget.content.widgets.length - 1
  912. );
  913. }
  914. });
  915. commands.addCommand(CommandIDs.renderAllMarkdown, {
  916. label: 'Render All Markdown Cells',
  917. execute: args => {
  918. const current = getCurrent(args);
  919. if (current) {
  920. const { context, content } = current;
  921. return NotebookActions.renderAllMarkdown(content, context.session);
  922. }
  923. },
  924. isEnabled
  925. });
  926. commands.addCommand(CommandIDs.restart, {
  927. label: 'Restart Kernel…',
  928. execute: args => {
  929. const current = getCurrent(args);
  930. if (current) {
  931. return current.session.restart();
  932. }
  933. },
  934. isEnabled
  935. });
  936. commands.addCommand(CommandIDs.closeAndShutdown, {
  937. label: 'Close and Shutdown',
  938. execute: args => {
  939. const current = getCurrent(args);
  940. if (!current) {
  941. return;
  942. }
  943. const fileName = current.title.label;
  944. return showDialog({
  945. title: 'Shutdown the notebook?',
  946. body: `Are you sure you want to close "${fileName}"?`,
  947. buttons: [Dialog.cancelButton(), Dialog.warnButton()]
  948. }).then(result => {
  949. if (result.button.accept) {
  950. return current.context.session.shutdown().then(() => {
  951. current.dispose();
  952. });
  953. }
  954. });
  955. },
  956. isEnabled
  957. });
  958. commands.addCommand(CommandIDs.trust, {
  959. label: () => 'Trust Notebook',
  960. execute: args => {
  961. const current = getCurrent(args);
  962. if (current) {
  963. const { context, content } = current;
  964. return NotebookActions.trust(content).then(() => context.save());
  965. }
  966. },
  967. isEnabled
  968. });
  969. commands.addCommand(CommandIDs.exportToFormat, {
  970. label: args => {
  971. const formatLabel = args['label'] as string;
  972. return (args['isPalette'] ? 'Export Notebook to ' : '') + formatLabel;
  973. },
  974. execute: args => {
  975. const current = getCurrent(args);
  976. if (!current) {
  977. return;
  978. }
  979. const notebookPath = URLExt.encodeParts(current.context.path);
  980. const url =
  981. URLExt.join(
  982. services.serverSettings.baseUrl,
  983. 'nbconvert',
  984. args['format'] as string,
  985. notebookPath
  986. ) + '?download=true';
  987. const child = window.open('', '_blank');
  988. const { context } = current;
  989. child.opener = null;
  990. if (context.model.dirty && !context.model.readOnly) {
  991. return context.save().then(() => {
  992. child.location.assign(url);
  993. });
  994. }
  995. return new Promise<void>(resolve => {
  996. child.location.assign(url);
  997. resolve(undefined);
  998. });
  999. },
  1000. isEnabled
  1001. });
  1002. commands.addCommand(CommandIDs.restartClear, {
  1003. label: 'Restart Kernel and Clear All Outputs…',
  1004. execute: args => {
  1005. const current = getCurrent(args);
  1006. if (current) {
  1007. const { content, session } = current;
  1008. return session.restart().then(() => {
  1009. NotebookActions.clearAllOutputs(content);
  1010. });
  1011. }
  1012. },
  1013. isEnabled
  1014. });
  1015. commands.addCommand(CommandIDs.restartRunAll, {
  1016. label: 'Restart Kernel and Run All Cells…',
  1017. execute: args => {
  1018. const current = getCurrent(args);
  1019. if (current) {
  1020. const { context, content, session } = current;
  1021. return session.restart().then(restarted => {
  1022. if (restarted) {
  1023. void NotebookActions.runAll(content, context.session);
  1024. }
  1025. return restarted;
  1026. });
  1027. }
  1028. },
  1029. isEnabled
  1030. });
  1031. commands.addCommand(CommandIDs.clearAllOutputs, {
  1032. label: 'Clear All Outputs',
  1033. execute: args => {
  1034. const current = getCurrent(args);
  1035. if (current) {
  1036. return NotebookActions.clearAllOutputs(current.content);
  1037. }
  1038. },
  1039. isEnabled
  1040. });
  1041. commands.addCommand(CommandIDs.clearOutputs, {
  1042. label: 'Clear Outputs',
  1043. execute: args => {
  1044. const current = getCurrent(args);
  1045. if (current) {
  1046. return NotebookActions.clearOutputs(current.content);
  1047. }
  1048. },
  1049. isEnabled
  1050. });
  1051. commands.addCommand(CommandIDs.interrupt, {
  1052. label: 'Interrupt Kernel',
  1053. execute: args => {
  1054. const current = getCurrent(args);
  1055. if (!current) {
  1056. return;
  1057. }
  1058. const kernel = current.context.session.kernel;
  1059. if (kernel) {
  1060. return kernel.interrupt();
  1061. }
  1062. },
  1063. isEnabled
  1064. });
  1065. commands.addCommand(CommandIDs.toCode, {
  1066. label: 'Change to Code Cell Type',
  1067. execute: args => {
  1068. const current = getCurrent(args);
  1069. if (current) {
  1070. return NotebookActions.changeCellType(current.content, 'code');
  1071. }
  1072. },
  1073. isEnabled
  1074. });
  1075. commands.addCommand(CommandIDs.toMarkdown, {
  1076. label: 'Change to Markdown Cell Type',
  1077. execute: args => {
  1078. const current = getCurrent(args);
  1079. if (current) {
  1080. return NotebookActions.changeCellType(current.content, 'markdown');
  1081. }
  1082. },
  1083. isEnabled
  1084. });
  1085. commands.addCommand(CommandIDs.toRaw, {
  1086. label: 'Change to Raw Cell Type',
  1087. execute: args => {
  1088. const current = getCurrent(args);
  1089. if (current) {
  1090. return NotebookActions.changeCellType(current.content, 'raw');
  1091. }
  1092. },
  1093. isEnabled
  1094. });
  1095. commands.addCommand(CommandIDs.cut, {
  1096. label: 'Cut Cells',
  1097. execute: args => {
  1098. const current = getCurrent(args);
  1099. if (current) {
  1100. return NotebookActions.cut(current.content);
  1101. }
  1102. },
  1103. isEnabled
  1104. });
  1105. commands.addCommand(CommandIDs.copy, {
  1106. label: 'Copy Cells',
  1107. execute: args => {
  1108. const current = getCurrent(args);
  1109. if (current) {
  1110. return NotebookActions.copy(current.content);
  1111. }
  1112. },
  1113. isEnabled
  1114. });
  1115. commands.addCommand(CommandIDs.pasteBelow, {
  1116. label: 'Paste Cells Below',
  1117. execute: args => {
  1118. const current = getCurrent(args);
  1119. if (current) {
  1120. return NotebookActions.paste(current.content, 'below');
  1121. }
  1122. },
  1123. isEnabled
  1124. });
  1125. commands.addCommand(CommandIDs.pasteAbove, {
  1126. label: 'Paste Cells Above',
  1127. execute: args => {
  1128. const current = getCurrent(args);
  1129. if (current) {
  1130. return NotebookActions.paste(current.content, 'above');
  1131. }
  1132. },
  1133. isEnabled
  1134. });
  1135. commands.addCommand(CommandIDs.pasteAndReplace, {
  1136. label: 'Paste Cells and Replace',
  1137. execute: args => {
  1138. const current = getCurrent(args);
  1139. if (current) {
  1140. return NotebookActions.paste(current.content, 'replace');
  1141. }
  1142. },
  1143. isEnabled
  1144. });
  1145. commands.addCommand(CommandIDs.deleteCell, {
  1146. label: 'Delete Cells',
  1147. execute: args => {
  1148. const current = getCurrent(args);
  1149. if (current) {
  1150. return NotebookActions.deleteCells(current.content);
  1151. }
  1152. },
  1153. isEnabled
  1154. });
  1155. commands.addCommand(CommandIDs.split, {
  1156. label: 'Split Cell',
  1157. execute: args => {
  1158. const current = getCurrent(args);
  1159. if (current) {
  1160. return NotebookActions.splitCell(current.content);
  1161. }
  1162. },
  1163. isEnabled
  1164. });
  1165. commands.addCommand(CommandIDs.merge, {
  1166. label: 'Merge Selected Cells',
  1167. execute: args => {
  1168. const current = getCurrent(args);
  1169. if (current) {
  1170. return NotebookActions.mergeCells(current.content);
  1171. }
  1172. },
  1173. isEnabled
  1174. });
  1175. commands.addCommand(CommandIDs.insertAbove, {
  1176. label: 'Insert Cell Above',
  1177. execute: args => {
  1178. const current = getCurrent(args);
  1179. if (current) {
  1180. return NotebookActions.insertAbove(current.content);
  1181. }
  1182. },
  1183. isEnabled
  1184. });
  1185. commands.addCommand(CommandIDs.insertBelow, {
  1186. label: 'Insert Cell Below',
  1187. execute: args => {
  1188. const current = getCurrent(args);
  1189. if (current) {
  1190. return NotebookActions.insertBelow(current.content);
  1191. }
  1192. },
  1193. isEnabled
  1194. });
  1195. commands.addCommand(CommandIDs.selectAbove, {
  1196. label: 'Select Cell Above',
  1197. execute: args => {
  1198. const current = getCurrent(args);
  1199. if (current) {
  1200. return NotebookActions.selectAbove(current.content);
  1201. }
  1202. },
  1203. isEnabled
  1204. });
  1205. commands.addCommand(CommandIDs.selectBelow, {
  1206. label: 'Select Cell Below',
  1207. execute: args => {
  1208. const current = getCurrent(args);
  1209. if (current) {
  1210. return NotebookActions.selectBelow(current.content);
  1211. }
  1212. },
  1213. isEnabled
  1214. });
  1215. commands.addCommand(CommandIDs.extendAbove, {
  1216. label: 'Extend Selection Above',
  1217. execute: args => {
  1218. const current = getCurrent(args);
  1219. if (current) {
  1220. return NotebookActions.extendSelectionAbove(current.content);
  1221. }
  1222. },
  1223. isEnabled
  1224. });
  1225. commands.addCommand(CommandIDs.extendBelow, {
  1226. label: 'Extend Selection Below',
  1227. execute: args => {
  1228. const current = getCurrent(args);
  1229. if (current) {
  1230. return NotebookActions.extendSelectionBelow(current.content);
  1231. }
  1232. },
  1233. isEnabled
  1234. });
  1235. commands.addCommand(CommandIDs.selectAll, {
  1236. label: 'Select All Cells',
  1237. execute: args => {
  1238. const current = getCurrent(args);
  1239. if (current) {
  1240. return NotebookActions.selectAll(current.content);
  1241. }
  1242. },
  1243. isEnabled
  1244. });
  1245. commands.addCommand(CommandIDs.deselectAll, {
  1246. label: 'Deselect All Cells',
  1247. execute: args => {
  1248. const current = getCurrent(args);
  1249. if (current) {
  1250. return NotebookActions.deselectAll(current.content);
  1251. }
  1252. },
  1253. isEnabled
  1254. });
  1255. commands.addCommand(CommandIDs.moveUp, {
  1256. label: 'Move Cells Up',
  1257. execute: args => {
  1258. const current = getCurrent(args);
  1259. if (current) {
  1260. return NotebookActions.moveUp(current.content);
  1261. }
  1262. },
  1263. isEnabled
  1264. });
  1265. commands.addCommand(CommandIDs.moveDown, {
  1266. label: 'Move Cells Down',
  1267. execute: args => {
  1268. const current = getCurrent(args);
  1269. if (current) {
  1270. return NotebookActions.moveDown(current.content);
  1271. }
  1272. },
  1273. isEnabled
  1274. });
  1275. commands.addCommand(CommandIDs.toggleAllLines, {
  1276. label: 'Toggle All Line Numbers',
  1277. execute: args => {
  1278. const current = getCurrent(args);
  1279. if (current) {
  1280. return NotebookActions.toggleAllLineNumbers(current.content);
  1281. }
  1282. },
  1283. isEnabled
  1284. });
  1285. commands.addCommand(CommandIDs.commandMode, {
  1286. label: 'Enter Command Mode',
  1287. execute: args => {
  1288. const current = getCurrent(args);
  1289. if (current) {
  1290. current.content.mode = 'command';
  1291. }
  1292. },
  1293. isEnabled
  1294. });
  1295. commands.addCommand(CommandIDs.editMode, {
  1296. label: 'Enter Edit Mode',
  1297. execute: args => {
  1298. const current = getCurrent(args);
  1299. if (current) {
  1300. current.content.mode = 'edit';
  1301. }
  1302. },
  1303. isEnabled
  1304. });
  1305. commands.addCommand(CommandIDs.undoCellAction, {
  1306. label: 'Undo Cell Operation',
  1307. execute: args => {
  1308. const current = getCurrent(args);
  1309. if (current) {
  1310. return NotebookActions.undo(current.content);
  1311. }
  1312. },
  1313. isEnabled
  1314. });
  1315. commands.addCommand(CommandIDs.redoCellAction, {
  1316. label: 'Redo Cell Operation',
  1317. execute: args => {
  1318. const current = getCurrent(args);
  1319. if (current) {
  1320. return NotebookActions.redo(current.content);
  1321. }
  1322. },
  1323. isEnabled
  1324. });
  1325. commands.addCommand(CommandIDs.changeKernel, {
  1326. label: 'Change Kernel…',
  1327. execute: args => {
  1328. const current = getCurrent(args);
  1329. if (current) {
  1330. return current.context.session.selectKernel();
  1331. }
  1332. },
  1333. isEnabled
  1334. });
  1335. commands.addCommand(CommandIDs.reconnectToKernel, {
  1336. label: 'Reconnect To Kernel',
  1337. execute: args => {
  1338. const current = getCurrent(args);
  1339. if (!current) {
  1340. return;
  1341. }
  1342. const kernel = current.context.session.kernel;
  1343. if (kernel) {
  1344. return kernel.reconnect();
  1345. }
  1346. },
  1347. isEnabled
  1348. });
  1349. commands.addCommand(CommandIDs.createOutputView, {
  1350. label: 'Create New View for Output',
  1351. execute: async args => {
  1352. let cell: CodeCell | undefined;
  1353. let current: NotebookPanel | undefined;
  1354. // If we are given a notebook path and cell index, then
  1355. // use that, otherwise use the current active cell.
  1356. let path = args.path as string | undefined | null;
  1357. let index = args.index as number | undefined | null;
  1358. if (path && index !== undefined && index !== null) {
  1359. current = docManager.findWidget(path, FACTORY) as NotebookPanel;
  1360. if (!current) {
  1361. return;
  1362. }
  1363. } else {
  1364. current = getCurrent({ ...args, activate: false });
  1365. if (!current) {
  1366. return;
  1367. }
  1368. cell = current.content.activeCell as CodeCell;
  1369. index = current.content.activeCellIndex;
  1370. }
  1371. // Create a MainAreaWidget
  1372. const content = new Private.ClonedOutputArea({
  1373. notebook: current,
  1374. cell,
  1375. index
  1376. });
  1377. const widget = new MainAreaWidget({ content });
  1378. current.context.addSibling(widget, {
  1379. ref: current.id,
  1380. mode: 'split-bottom'
  1381. });
  1382. const updateCloned = () => {
  1383. void clonedOutputs.save(widget);
  1384. };
  1385. current.context.pathChanged.connect(updateCloned);
  1386. current.content.model.cells.changed.connect(updateCloned);
  1387. // Add the cloned output to the output instance tracker.
  1388. void clonedOutputs.add(widget);
  1389. // Remove the output view if the parent notebook is closed.
  1390. current.content.disposed.connect(() => {
  1391. current.context.pathChanged.disconnect(updateCloned);
  1392. current.content.model.cells.changed.disconnect(updateCloned);
  1393. widget.dispose();
  1394. });
  1395. },
  1396. isEnabled: isEnabledAndSingleSelected
  1397. });
  1398. commands.addCommand(CommandIDs.createConsole, {
  1399. label: 'New Console for Notebook',
  1400. execute: args => {
  1401. const current = getCurrent({ ...args, activate: false });
  1402. const widget = tracker.currentWidget;
  1403. if (!current || !widget) {
  1404. return;
  1405. }
  1406. const options: ReadonlyJSONObject = {
  1407. path: widget.context.path,
  1408. preferredLanguage: widget.context.model.defaultKernelLanguage,
  1409. activate: args['activate'],
  1410. ref: current.id,
  1411. insertMode: 'split-bottom'
  1412. };
  1413. return commands.execute('console:create', options);
  1414. },
  1415. isEnabled
  1416. });
  1417. commands.addCommand(CommandIDs.markdown1, {
  1418. label: 'Change to Heading 1',
  1419. execute: args => {
  1420. const current = getCurrent(args);
  1421. if (current) {
  1422. return NotebookActions.setMarkdownHeader(current.content, 1);
  1423. }
  1424. },
  1425. isEnabled
  1426. });
  1427. commands.addCommand(CommandIDs.markdown2, {
  1428. label: 'Change to Heading 2',
  1429. execute: args => {
  1430. const current = getCurrent(args);
  1431. if (current) {
  1432. return NotebookActions.setMarkdownHeader(current.content, 2);
  1433. }
  1434. },
  1435. isEnabled
  1436. });
  1437. commands.addCommand(CommandIDs.markdown3, {
  1438. label: 'Change to Heading 3',
  1439. execute: args => {
  1440. const current = getCurrent(args);
  1441. if (current) {
  1442. return NotebookActions.setMarkdownHeader(current.content, 3);
  1443. }
  1444. },
  1445. isEnabled
  1446. });
  1447. commands.addCommand(CommandIDs.markdown4, {
  1448. label: 'Change to Heading 4',
  1449. execute: args => {
  1450. const current = getCurrent(args);
  1451. if (current) {
  1452. return NotebookActions.setMarkdownHeader(current.content, 4);
  1453. }
  1454. },
  1455. isEnabled
  1456. });
  1457. commands.addCommand(CommandIDs.markdown5, {
  1458. label: 'Change to Heading 5',
  1459. execute: args => {
  1460. const current = getCurrent(args);
  1461. if (current) {
  1462. return NotebookActions.setMarkdownHeader(current.content, 5);
  1463. }
  1464. },
  1465. isEnabled
  1466. });
  1467. commands.addCommand(CommandIDs.markdown6, {
  1468. label: 'Change to Heading 6',
  1469. execute: args => {
  1470. const current = getCurrent(args);
  1471. if (current) {
  1472. return NotebookActions.setMarkdownHeader(current.content, 6);
  1473. }
  1474. },
  1475. isEnabled
  1476. });
  1477. commands.addCommand(CommandIDs.hideCode, {
  1478. label: 'Collapse Selected Code',
  1479. execute: args => {
  1480. const current = getCurrent(args);
  1481. if (current) {
  1482. return NotebookActions.hideCode(current.content);
  1483. }
  1484. },
  1485. isEnabled
  1486. });
  1487. commands.addCommand(CommandIDs.showCode, {
  1488. label: 'Expand Selected Code',
  1489. execute: args => {
  1490. const current = getCurrent(args);
  1491. if (current) {
  1492. return NotebookActions.showCode(current.content);
  1493. }
  1494. },
  1495. isEnabled
  1496. });
  1497. commands.addCommand(CommandIDs.hideAllCode, {
  1498. label: 'Collapse All Code',
  1499. execute: args => {
  1500. const current = getCurrent(args);
  1501. if (current) {
  1502. return NotebookActions.hideAllCode(current.content);
  1503. }
  1504. },
  1505. isEnabled
  1506. });
  1507. commands.addCommand(CommandIDs.showAllCode, {
  1508. label: 'Expand All Code',
  1509. execute: args => {
  1510. const current = getCurrent(args);
  1511. if (current) {
  1512. return NotebookActions.showAllCode(current.content);
  1513. }
  1514. },
  1515. isEnabled
  1516. });
  1517. commands.addCommand(CommandIDs.hideOutput, {
  1518. label: 'Collapse Selected Outputs',
  1519. execute: args => {
  1520. const current = getCurrent(args);
  1521. if (current) {
  1522. return NotebookActions.hideOutput(current.content);
  1523. }
  1524. },
  1525. isEnabled
  1526. });
  1527. commands.addCommand(CommandIDs.showOutput, {
  1528. label: 'Expand Selected Outputs',
  1529. execute: args => {
  1530. const current = getCurrent(args);
  1531. if (current) {
  1532. return NotebookActions.showOutput(current.content);
  1533. }
  1534. },
  1535. isEnabled
  1536. });
  1537. commands.addCommand(CommandIDs.hideAllOutputs, {
  1538. label: 'Collapse All Outputs',
  1539. execute: args => {
  1540. const current = getCurrent(args);
  1541. if (current) {
  1542. return NotebookActions.hideAllOutputs(current.content);
  1543. }
  1544. },
  1545. isEnabled
  1546. });
  1547. commands.addCommand(CommandIDs.showAllOutputs, {
  1548. label: 'Expand All Outputs',
  1549. execute: args => {
  1550. const current = getCurrent(args);
  1551. if (current) {
  1552. return NotebookActions.showAllOutputs(current.content);
  1553. }
  1554. },
  1555. isEnabled
  1556. });
  1557. commands.addCommand(CommandIDs.enableOutputScrolling, {
  1558. label: 'Enable Scrolling for Outputs',
  1559. execute: args => {
  1560. const current = getCurrent(args);
  1561. if (current) {
  1562. return NotebookActions.enableOutputScrolling(current.content);
  1563. }
  1564. },
  1565. isEnabled
  1566. });
  1567. commands.addCommand(CommandIDs.disableOutputScrolling, {
  1568. label: 'Disable Scrolling for Outputs',
  1569. execute: args => {
  1570. const current = getCurrent(args);
  1571. if (current) {
  1572. return NotebookActions.disableOutputScrolling(current.content);
  1573. }
  1574. },
  1575. isEnabled
  1576. });
  1577. }
  1578. /**
  1579. * Populate the application's command palette with notebook commands.
  1580. */
  1581. function populatePalette(
  1582. palette: ICommandPalette,
  1583. services: ServiceManager
  1584. ): void {
  1585. let category = 'Notebook Operations';
  1586. [
  1587. CommandIDs.interrupt,
  1588. CommandIDs.restart,
  1589. CommandIDs.restartClear,
  1590. CommandIDs.restartRunAll,
  1591. CommandIDs.runAll,
  1592. CommandIDs.renderAllMarkdown,
  1593. CommandIDs.runAllAbove,
  1594. CommandIDs.runAllBelow,
  1595. CommandIDs.selectAll,
  1596. CommandIDs.deselectAll,
  1597. CommandIDs.clearAllOutputs,
  1598. CommandIDs.toggleAllLines,
  1599. CommandIDs.editMode,
  1600. CommandIDs.commandMode,
  1601. CommandIDs.changeKernel,
  1602. CommandIDs.reconnectToKernel,
  1603. CommandIDs.createConsole,
  1604. CommandIDs.closeAndShutdown,
  1605. CommandIDs.trust
  1606. ].forEach(command => {
  1607. palette.addItem({ command, category });
  1608. });
  1609. palette.addItem({
  1610. command: CommandIDs.createNew,
  1611. category,
  1612. args: { isPalette: true }
  1613. });
  1614. category = 'Notebook Cell Operations';
  1615. [
  1616. CommandIDs.run,
  1617. CommandIDs.runAndAdvance,
  1618. CommandIDs.runAndInsert,
  1619. CommandIDs.runInConsole,
  1620. CommandIDs.clearOutputs,
  1621. CommandIDs.toCode,
  1622. CommandIDs.toMarkdown,
  1623. CommandIDs.toRaw,
  1624. CommandIDs.cut,
  1625. CommandIDs.copy,
  1626. CommandIDs.pasteBelow,
  1627. CommandIDs.pasteAbove,
  1628. CommandIDs.pasteAndReplace,
  1629. CommandIDs.deleteCell,
  1630. CommandIDs.split,
  1631. CommandIDs.merge,
  1632. CommandIDs.insertAbove,
  1633. CommandIDs.insertBelow,
  1634. CommandIDs.selectAbove,
  1635. CommandIDs.selectBelow,
  1636. CommandIDs.extendAbove,
  1637. CommandIDs.extendBelow,
  1638. CommandIDs.moveDown,
  1639. CommandIDs.moveUp,
  1640. CommandIDs.undoCellAction,
  1641. CommandIDs.redoCellAction,
  1642. CommandIDs.markdown1,
  1643. CommandIDs.markdown2,
  1644. CommandIDs.markdown3,
  1645. CommandIDs.markdown4,
  1646. CommandIDs.markdown5,
  1647. CommandIDs.markdown6,
  1648. CommandIDs.hideCode,
  1649. CommandIDs.showCode,
  1650. CommandIDs.hideAllCode,
  1651. CommandIDs.showAllCode,
  1652. CommandIDs.hideOutput,
  1653. CommandIDs.showOutput,
  1654. CommandIDs.hideAllOutputs,
  1655. CommandIDs.showAllOutputs,
  1656. CommandIDs.enableOutputScrolling,
  1657. CommandIDs.disableOutputScrolling
  1658. ].forEach(command => {
  1659. palette.addItem({ command, category });
  1660. });
  1661. }
  1662. /**
  1663. * Populates the application menus for the notebook.
  1664. */
  1665. function populateMenus(
  1666. app: JupyterFrontEnd,
  1667. mainMenu: IMainMenu,
  1668. tracker: INotebookTracker,
  1669. services: ServiceManager,
  1670. palette: ICommandPalette | null
  1671. ): void {
  1672. let { commands } = app;
  1673. // Add undo/redo hooks to the edit menu.
  1674. mainMenu.editMenu.undoers.add({
  1675. tracker,
  1676. undo: widget => {
  1677. widget.content.activeCell.editor.undo();
  1678. },
  1679. redo: widget => {
  1680. widget.content.activeCell.editor.redo();
  1681. }
  1682. } as IEditMenu.IUndoer<NotebookPanel>);
  1683. // Add a clearer to the edit menu
  1684. mainMenu.editMenu.clearers.add({
  1685. tracker,
  1686. noun: 'Outputs',
  1687. pluralNoun: 'Outputs',
  1688. clearCurrent: (current: NotebookPanel) => {
  1689. return NotebookActions.clearOutputs(current.content);
  1690. },
  1691. clearAll: (current: NotebookPanel) => {
  1692. return NotebookActions.clearAllOutputs(current.content);
  1693. }
  1694. } as IEditMenu.IClearer<NotebookPanel>);
  1695. // Add new notebook creation to the file menu.
  1696. mainMenu.fileMenu.newMenu.addGroup([{ command: CommandIDs.createNew }], 10);
  1697. // Add a close and shutdown command to the file menu.
  1698. mainMenu.fileMenu.closeAndCleaners.add({
  1699. tracker,
  1700. action: 'Shutdown',
  1701. name: 'Notebook',
  1702. closeAndCleanup: (current: NotebookPanel) => {
  1703. const fileName = current.title.label;
  1704. return showDialog({
  1705. title: 'Shutdown the notebook?',
  1706. body: `Are you sure you want to close "${fileName}"?`,
  1707. buttons: [Dialog.cancelButton(), Dialog.warnButton()]
  1708. }).then(result => {
  1709. if (result.button.accept) {
  1710. return current.context.session.shutdown().then(() => {
  1711. current.dispose();
  1712. });
  1713. }
  1714. });
  1715. }
  1716. } as IFileMenu.ICloseAndCleaner<NotebookPanel>);
  1717. // Add a notebook group to the File menu.
  1718. let exportTo = new Menu({ commands });
  1719. exportTo.title.label = 'Export Notebook As…';
  1720. void services.nbconvert.getExportFormats().then(response => {
  1721. if (response) {
  1722. // Convert export list to palette and menu items.
  1723. const formatList = Object.keys(response);
  1724. formatList.forEach(function(key) {
  1725. let capCaseKey = key[0].toUpperCase() + key.substr(1);
  1726. let labelStr = FORMAT_LABEL[key] ? FORMAT_LABEL[key] : capCaseKey;
  1727. let args = {
  1728. format: key,
  1729. label: labelStr,
  1730. isPalette: true
  1731. };
  1732. if (FORMAT_EXCLUDE.indexOf(key) === -1) {
  1733. exportTo.addItem({
  1734. command: CommandIDs.exportToFormat,
  1735. args: args
  1736. });
  1737. if (palette) {
  1738. const category = 'Notebook Operations';
  1739. palette.addItem({
  1740. command: CommandIDs.exportToFormat,
  1741. category,
  1742. args
  1743. });
  1744. }
  1745. }
  1746. });
  1747. const fileGroup = [
  1748. { type: 'submenu', submenu: exportTo } as Menu.IItemOptions
  1749. ];
  1750. mainMenu.fileMenu.addGroup(fileGroup, 10);
  1751. }
  1752. });
  1753. // Add a kernel user to the Kernel menu
  1754. mainMenu.kernelMenu.kernelUsers.add({
  1755. tracker,
  1756. interruptKernel: current => {
  1757. let kernel = current.session.kernel;
  1758. if (kernel) {
  1759. return kernel.interrupt();
  1760. }
  1761. return Promise.resolve(void 0);
  1762. },
  1763. noun: 'All Outputs',
  1764. restartKernel: current => current.session.restart(),
  1765. restartKernelAndClear: current => {
  1766. return current.session.restart().then(restarted => {
  1767. if (restarted) {
  1768. NotebookActions.clearAllOutputs(current.content);
  1769. }
  1770. return restarted;
  1771. });
  1772. },
  1773. changeKernel: current => current.session.selectKernel(),
  1774. shutdownKernel: current => current.session.shutdown()
  1775. } as IKernelMenu.IKernelUser<NotebookPanel>);
  1776. // Add a console creator the the Kernel menu
  1777. mainMenu.fileMenu.consoleCreators.add({
  1778. tracker,
  1779. name: 'Notebook',
  1780. createConsole: current => {
  1781. const options: ReadonlyJSONObject = {
  1782. path: current.context.path,
  1783. preferredLanguage: current.context.model.defaultKernelLanguage,
  1784. activate: true,
  1785. ref: current.id,
  1786. insertMode: 'split-bottom'
  1787. };
  1788. return commands.execute('console:create', options);
  1789. }
  1790. } as IFileMenu.IConsoleCreator<NotebookPanel>);
  1791. // Add some commands to the application view menu.
  1792. const collapseGroup = [
  1793. CommandIDs.hideCode,
  1794. CommandIDs.hideOutput,
  1795. CommandIDs.hideAllCode,
  1796. CommandIDs.hideAllOutputs
  1797. ].map(command => {
  1798. return { command };
  1799. });
  1800. mainMenu.viewMenu.addGroup(collapseGroup, 10);
  1801. const expandGroup = [
  1802. CommandIDs.showCode,
  1803. CommandIDs.showOutput,
  1804. CommandIDs.showAllCode,
  1805. CommandIDs.showAllOutputs
  1806. ].map(command => {
  1807. return { command };
  1808. });
  1809. mainMenu.viewMenu.addGroup(expandGroup, 11);
  1810. // Add an IEditorViewer to the application view menu
  1811. mainMenu.viewMenu.editorViewers.add({
  1812. tracker,
  1813. toggleLineNumbers: widget => {
  1814. NotebookActions.toggleAllLineNumbers(widget.content);
  1815. },
  1816. lineNumbersToggled: widget => {
  1817. const config = widget.content.editorConfig;
  1818. return !!(
  1819. config.code.lineNumbers &&
  1820. config.markdown.lineNumbers &&
  1821. config.raw.lineNumbers
  1822. );
  1823. }
  1824. } as IViewMenu.IEditorViewer<NotebookPanel>);
  1825. // Add an ICodeRunner to the application run menu
  1826. mainMenu.runMenu.codeRunners.add({
  1827. tracker,
  1828. noun: 'Cells',
  1829. run: current => {
  1830. const { context, content } = current;
  1831. return NotebookActions.runAndAdvance(content, context.session).then(
  1832. () => void 0
  1833. );
  1834. },
  1835. runAll: current => {
  1836. const { context, content } = current;
  1837. return NotebookActions.runAll(content, context.session).then(
  1838. () => void 0
  1839. );
  1840. },
  1841. restartAndRunAll: current => {
  1842. const { context, content } = current;
  1843. return context.session.restart().then(restarted => {
  1844. if (restarted) {
  1845. void NotebookActions.runAll(content, context.session);
  1846. }
  1847. return restarted;
  1848. });
  1849. }
  1850. } as IRunMenu.ICodeRunner<NotebookPanel>);
  1851. // Add a renderAllMarkdown group to the run menu.
  1852. const renderAllMarkdown = [CommandIDs.renderAllMarkdown].map(command => {
  1853. return { command };
  1854. });
  1855. // Add a run+insert and run+don't advance group to the run menu.
  1856. const runExtras = [
  1857. CommandIDs.runAndInsert,
  1858. CommandIDs.run,
  1859. CommandIDs.runInConsole
  1860. ].map(command => {
  1861. return { command };
  1862. });
  1863. // Add a run all above/below group to the run menu.
  1864. const runAboveBelowGroup = [
  1865. CommandIDs.runAllAbove,
  1866. CommandIDs.runAllBelow
  1867. ].map(command => {
  1868. return { command };
  1869. });
  1870. // Add commands to the application edit menu.
  1871. const undoCellActionGroup = [
  1872. CommandIDs.undoCellAction,
  1873. CommandIDs.redoCellAction
  1874. ].map(command => {
  1875. return { command };
  1876. });
  1877. const copyGroup = [
  1878. CommandIDs.cut,
  1879. CommandIDs.copy,
  1880. CommandIDs.pasteBelow,
  1881. CommandIDs.pasteAbove,
  1882. CommandIDs.pasteAndReplace
  1883. ].map(command => {
  1884. return { command };
  1885. });
  1886. const selectGroup = [CommandIDs.selectAll, CommandIDs.deselectAll].map(
  1887. command => {
  1888. return { command };
  1889. }
  1890. );
  1891. const splitMergeGroup = [CommandIDs.split, CommandIDs.merge].map(command => {
  1892. return { command };
  1893. });
  1894. const moveCellsGroup = [CommandIDs.moveUp, CommandIDs.moveDown].map(
  1895. command => {
  1896. return { command };
  1897. }
  1898. );
  1899. mainMenu.editMenu.addGroup(undoCellActionGroup, 4);
  1900. mainMenu.editMenu.addGroup(copyGroup, 5);
  1901. mainMenu.editMenu.addGroup([{ command: CommandIDs.deleteCell }], 6);
  1902. mainMenu.editMenu.addGroup(selectGroup, 7);
  1903. mainMenu.editMenu.addGroup(moveCellsGroup, 8);
  1904. mainMenu.editMenu.addGroup(splitMergeGroup, 9);
  1905. mainMenu.runMenu.addGroup(runExtras, 10);
  1906. mainMenu.runMenu.addGroup(runAboveBelowGroup, 11);
  1907. mainMenu.runMenu.addGroup(renderAllMarkdown, 12);
  1908. // Add kernel information to the application help menu.
  1909. mainMenu.helpMenu.kernelUsers.add({
  1910. tracker,
  1911. getKernel: current => current.session.kernel
  1912. } as IHelpMenu.IKernelUser<NotebookPanel>);
  1913. }
  1914. /**
  1915. * A namespace for module private functionality.
  1916. */
  1917. namespace Private {
  1918. /**
  1919. * A widget hosting a cloned output area.
  1920. */
  1921. export class ClonedOutputArea extends Panel {
  1922. constructor(options: ClonedOutputArea.IOptions) {
  1923. super();
  1924. this._notebook = options.notebook;
  1925. this._index = options.index !== undefined ? options.index : -1;
  1926. this._cell = options.cell || null;
  1927. this.id = `LinkedOutputView-${UUID.uuid4()}`;
  1928. this.title.label = 'Output View';
  1929. this.title.icon = NOTEBOOK_ICON_CLASS;
  1930. this.title.caption = this._notebook.title.label
  1931. ? `For Notebook: ${this._notebook.title.label}`
  1932. : 'For Notebook:';
  1933. this.addClass('jp-LinkedOutputView');
  1934. // Wait for the notebook to be loaded before
  1935. // cloning the output area.
  1936. void this._notebook.context.ready.then(() => {
  1937. if (!this._cell) {
  1938. this._cell = this._notebook.content.widgets[this._index] as CodeCell;
  1939. }
  1940. if (!this._cell || this._cell.model.type !== 'code') {
  1941. this.dispose();
  1942. return;
  1943. }
  1944. const clone = this._cell.cloneOutputArea();
  1945. this.addWidget(clone);
  1946. });
  1947. }
  1948. /**
  1949. * The index of the cell in the notebook.
  1950. */
  1951. get index(): number {
  1952. return this._cell
  1953. ? ArrayExt.findFirstIndex(
  1954. this._notebook.content.widgets,
  1955. c => c === this._cell
  1956. )
  1957. : this._index;
  1958. }
  1959. /**
  1960. * The path of the notebook for the cloned output area.
  1961. */
  1962. get path(): string {
  1963. return this._notebook.context.path;
  1964. }
  1965. private _notebook: NotebookPanel;
  1966. private _index: number;
  1967. private _cell: CodeCell | null = null;
  1968. }
  1969. /**
  1970. * ClonedOutputArea statics.
  1971. */
  1972. export namespace ClonedOutputArea {
  1973. export interface IOptions {
  1974. /**
  1975. * The notebook associated with the cloned output area.
  1976. */
  1977. notebook: NotebookPanel;
  1978. /**
  1979. * The cell for which to clone the output area.
  1980. */
  1981. cell?: CodeCell;
  1982. /**
  1983. * If the cell is not available, provide the index
  1984. * of the cell for when the notebook is loaded.
  1985. */
  1986. index?: number;
  1987. }
  1988. }
  1989. }