Skip to content

Commit 62b57c3

Browse files
committed
Update the method for determining kernel language
The previous algorithm for `getNotebookType()` was based on getting the kernel spec out of the current notebook. This is a problem when format is triggered by, for example, `jupyterlab-autosave-on-focus-change`, immediately after notebook creation. In that case, the language is determined to be `null` and errors arise. Now the `onSave()` handler waits for the `sessionContext` to be ready, then `getNotebookType()` gets the same kernel spec info from the session rather than the loaded notebook.
1 parent 55a9d04 commit 62b57c3

File tree

2 files changed

+12
-1
lines changed

2 files changed

+12
-1
lines changed

src/formatter.ts

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,7 @@ export class JupyterlabNotebookCodeFormatter extends JupyterlabCodeFormatter {
9292
return codeCells;
9393
}
9494

95-
private getNotebookType() {
95+
private getNotebookType(): string | null {
9696
if (!this.notebookTracker.currentWidget) {
9797
return null;
9898
}
@@ -123,6 +123,16 @@ export class JupyterlabNotebookCodeFormatter extends JupyterlabCodeFormatter {
123123
}
124124
}
125125

126+
// finally, try to get the language from the current session's kernel spec
127+
const sessionContext = this.notebookTracker.currentWidget?.sessionContext;
128+
const kernelName = sessionContext?.session?.kernel?.name;
129+
if (kernelName) {
130+
const specs = sessionContext.specsManager.specs?.kernelspecs;
131+
if (specs && kernelName in specs) {
132+
return specs[kernelName]!.language;
133+
}
134+
}
135+
126136
return null;
127137
}
128138

src/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,7 @@ class JupyterLabCodeFormatter
108108
state: DocumentRegistry.SaveState
109109
) {
110110
if (state === 'started' && this.config.formatOnSave) {
111+
await context.sessionContext.ready;
111112
await this.notebookCodeFormatter.formatAllCodeCells(
112113
this.config,
113114
{ saving: true },

0 commit comments

Comments
 (0)