CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-jupyterlab-code-formatter

A JupyterLab extension to facilitate invocation of code formatters for multiple programming languages.

Pending
Overview
Eval results
Files

notebook-formatting.mddocs/

Notebook Formatting

Comprehensive notebook cell formatting capabilities including selected cells, all cells, and format-on-save functionality with support for magic commands and special syntax.

Capabilities

Notebook Code Formatter

Main class for handling notebook cell formatting operations.

class JupyterlabNotebookCodeFormatter extends JupyterlabCodeFormatter {
  constructor(
    client: JupyterlabCodeFormatterClient,
    notebookTracker: INotebookTracker
  );

  formatAction(config: any, formatter?: string): Promise<void>;
  formatSelectedCodeCells(config: any, formatter?: string, notebook?: Notebook): Promise<void>;
  formatAllCodeCells(config: any, context: Context, formatter?: string, notebook?: Notebook): Promise<void>;
  applicable(formatter: string, currentWidget: Widget): boolean;
}

Constructor Parameters:

  • client - HTTP client for backend communication
  • notebookTracker - JupyterLab notebook tracker

Methods:

  • formatAction() - Formats selected cells (wrapper for formatSelectedCodeCells)
  • formatSelectedCodeCells() - Formats currently selected code cells
  • formatAllCodeCells() - Formats all code cells in the notebook
  • applicable() - Checks if formatter is applicable to current notebook context

Base Formatter Class

Abstract base class providing common formatting functionality.

abstract class JupyterlabCodeFormatter {
  working: boolean;
  protected client: JupyterlabCodeFormatterClient;
  
  constructor(client: JupyterlabCodeFormatterClient);
  protected formatCode(
    code: string[],
    formatter: string,
    options: any,
    notebook: boolean,
    cache: boolean
  ): Promise<any>;
}

Properties:

  • working - Boolean flag indicating if formatting operation is in progress

Protected Methods:

  • formatCode() - Sends code to backend for formatting

Context Interface

Defines the context for formatting operations.

interface Context {
  saving: boolean;
}

Properties:

  • saving - Indicates if formatting is occurring during save operation

Usage Examples

Creating Notebook Formatter

import JupyterlabCodeFormatterClient from './client';
import { JupyterlabNotebookCodeFormatter } from './formatter';
import { INotebookTracker } from '@jupyterlab/notebook';

// Create client and formatter
const client = new JupyterlabCodeFormatterClient();
const notebookFormatter = new JupyterlabNotebookCodeFormatter(client, notebookTracker);

Format Selected Cells

// Format selected cells with default formatter
await notebookFormatter.formatSelectedCodeCells(config);

// Format selected cells with specific formatter
await notebookFormatter.formatSelectedCodeCells(config, 'black');

// Format selected cells in specific notebook
await notebookFormatter.formatSelectedCodeCells(config, undefined, notebook);

Format All Cells

// Format all cells (manual operation)
await notebookFormatter.formatAllCodeCells(
  config,
  { saving: false }
);

// Format all cells during save operation
await notebookFormatter.formatAllCodeCells(
  config,
  { saving: true },
  'black'
);

Check Formatter Applicability

import { Widget } from '@lumino/widgets';

const currentWidget: Widget = app.shell.currentWidget;
const isApplicable = notebookFormatter.applicable('black', currentWidget);

if (isApplicable) {
  await notebookFormatter.formatAction(config, 'black');
}

Formatting Behavior

Cell Selection Logic

The formatter identifies code cells to format based on:

  • Selected Only: When formatSelectedCodeCells is called, only selected/active cells are formatted
  • All Cells: When formatAllCodeCells is called, all code cells in the notebook are formatted
  • Cell Type Filtering: Only cells with model.type === 'code' are processed
  • Skip Non-Code: Markdown, raw, and other cell types are ignored

Language Detection

The formatter determines the programming language through:

  1. Kernel Spec Language: Prefers metadata.kernelspec.language
  2. CodeMirror Mode: Falls back to metadata.language_info.codemirror_mode
  3. Session Kernel: Uses current session's kernel specification
  4. Default Fallback: Uses configured default formatters if language cannot be determined

Default Formatter Selection

// Example of how default formatters are selected
const notebookType = getNotebookType(); // "python", "r", etc.
const defaultFormatters = config.preferences.default_formatter[notebookType];

// Can be a single formatter string or array of formatters
if (Array.isArray(defaultFormatters)) {
  // Apply multiple formatters in sequence
  for (const formatter of defaultFormatters) {
    await applyFormatter(formatter);
  }
} else if (defaultFormatters) {
  // Apply single formatter
  await applyFormatter(defaultFormatters);
}

Error Handling

The formatter provides comprehensive error handling:

  • Cell Change Detection: Skips formatting if cell content changed during operation
  • Formatter Errors: Displays error dialogs with options to navigate to problematic cells
  • Error Suppression: Configurable error suppression during auto-format on save
  • Working State: Prevents concurrent formatting operations

Magic Command Support

The formatter preserves Jupyter notebook magic commands and special syntax:

  • Line Magics: %matplotlib inline, %time, etc.
  • Cell Magics: %%bash, %%html, %%javascript, etc.
  • Help Commands: ?function_name, ??function_name
  • Shell Commands: !ls, !pip install package
  • Quarto Comments: #| label: fig-plot

These are temporarily escaped before formatting and restored afterward to prevent formatter corruption.

Configuration Options

Formatter-Specific Settings

Each formatter can have specific configuration options:

// Example configuration
const config = {
  black: {
    line_length: 88,
    string_normalization: true,
    magic_trailing_comma: true
  },
  isort: {
    multi_line_output: 3,
    include_trailing_comma: true,
    force_grid_wrap: 0
  },
  preferences: {
    default_formatter: {
      python: ['isort', 'black'],
      r: ['formatR']
    }
  },
  formatOnSave: true,
  cacheFormatters: true,
  suppressFormatterErrors: false,
  suppressFormatterErrorsIFFAutoFormatOnSave: true
};

Save-Related Settings

  • formatOnSave: Enable/disable automatic formatting when saving notebooks
  • suppressFormatterErrorsIFFAutoFormatOnSave: Suppress errors only during auto-format on save
  • cacheFormatters: Cache formatter availability checks for better performance

Install with Tessl CLI

npx tessl i tessl/pypi-jupyterlab-code-formatter

docs

code-formatters.md

configuration-system.md

file-editor-formatting.md

frontend-integration.md

http-api-client.md

http-api-handlers.md

index.md

notebook-formatting.md

tile.json