@@ -2,16 +2,71 @@ import {
22 JupyterFrontEnd ,
33 JupyterFrontEndPlugin
44} from '@jupyterlab/application' ;
5+ import { INotebookTracker } from '@jupyterlab/notebook' ;
56
67/**
78 * Initialization data for the nbname extension.
89 */
910const plugin : JupyterFrontEndPlugin < void > = {
1011 id : 'nbname:plugin' ,
11- description : 'A JupyterLab extension to retrieve the currently openend notebook filename.' ,
12+ description :
13+ 'A JupyterLab extension to retrieve the currently openend notebook filename.' ,
1214 autoStart : true ,
13- activate : ( app : JupyterFrontEnd ) => {
14- console . log ( 'JupyterLab extension nbname is activated!' ) ;
15+ requires : [ INotebookTracker ] ,
16+ activate : ( app : JupyterFrontEnd , tracker : INotebookTracker ) => {
17+ // Function to inject the notebook name
18+ const injectNotebookName = ( notebookPanel : any ) => {
19+ if ( ! notebookPanel ) {
20+ return ;
21+ }
22+ const fullPath = notebookPanel . context . path ;
23+ const filename = fullPath . split ( '/' ) . pop ( ) ;
24+ console . log ( `Current notebook filename: ${ filename } ` ) ;
25+
26+ // Get Kernel
27+ const sessionContext = notebookPanel . sessionContext ;
28+ if ( ! sessionContext ?. session ?. kernel ) {
29+ console . warn ( 'No kernel available!' ) ;
30+ return ;
31+ }
32+
33+ const kernel = sessionContext . session . kernel ;
34+
35+ // Inject the filename
36+ const code = `__NOTEBOOK_FILE__ = "${ filename } "` ;
37+ const future = kernel . requestExecute ( { code, silent : true } ) ;
38+ future . done
39+ . then ( ( ) => {
40+ console . log (
41+ `Successfully injected __NOTEBOOK_FILE__ = "${ filename } "`
42+ ) ;
43+ } )
44+ . catch ( ( error : Error ) => {
45+ console . error ( 'Failed to inject code:' , error ) ;
46+ } ) ;
47+ } ;
48+
49+ // Inject notebook name
50+ tracker . currentChanged . connect ( ( tracker , notebookPanel ) => {
51+ if ( notebookPanel ) {
52+ notebookPanel . sessionContext . ready . then ( ( ) => {
53+ injectNotebookName ( notebookPanel ) ;
54+ } ) ;
55+
56+ notebookPanel . context . pathChanged . connect ( ( ) => {
57+ injectNotebookName ( notebookPanel ) ;
58+ } ) ;
59+ }
60+ } ) ;
61+
62+ // Inject filename for currently opened notebook
63+ if ( tracker . currentWidget ) {
64+ tracker . currentWidget . sessionContext . ready . then ( ( ) => {
65+ injectNotebookName ( tracker . currentWidget ) ;
66+ } ) ;
67+ }
68+
69+ console . log ( 'Notebook filename injection is now active' ) ;
1570 }
1671} ;
1772
0 commit comments