Skip to content

Commit

Permalink
Update the method for determining kernel language
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
shreve committed Aug 7, 2024
1 parent 55a9d04 commit f8e87c3
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 28 deletions.
36 changes: 8 additions & 28 deletions src/formatter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,34 +92,14 @@ export class JupyterlabNotebookCodeFormatter extends JupyterlabCodeFormatter {
return codeCells;
}

private getNotebookType() {
if (!this.notebookTracker.currentWidget) {
return null;
}

const metadata =
this.notebookTracker.currentWidget.content.model!.sharedModel.metadata;

if (!metadata) {
return null;
}

// prefer kernelspec language
if (
metadata.kernelspec &&
metadata.kernelspec.language &&
typeof metadata.kernelspec.language === 'string'
) {
return metadata.kernelspec.language.toLowerCase();
}

// otherwise, check language info code mirror mode
if (metadata.language_info && metadata.language_info.codemirror_mode) {
const mode = metadata.language_info.codemirror_mode;
if (typeof mode === 'string') {
return mode.toLowerCase();
} else if (typeof mode.name === 'string') {
return mode.name.toLowerCase();
private getNotebookType(): string | null {
// Get the language from the current kernel spec
const sessionContext = this.notebookTracker.currentWidget?.sessionContext;
const kernelName = sessionContext?.session?.kernel?.name;
if (kernelName) {
const specs = sessionContext.specsManager.specs?.kernelspecs;
if (specs && kernelName in specs) {
return specs[kernelName]!.language;
}
}

Expand Down
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@ class JupyterLabCodeFormatter
state: DocumentRegistry.SaveState
) {
if (state === 'started' && this.config.formatOnSave) {
await context.sessionContext.ready;
await this.notebookCodeFormatter.formatAllCodeCells(
this.config,
{ saving: true },
Expand Down

0 comments on commit f8e87c3

Please sign in to comment.