or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

code-formatters.mdconfiguration-system.mdfile-editor-formatting.mdfrontend-integration.mdhttp-api-client.mdhttp-api-handlers.mdindex.mdnotebook-formatting.md
tile.json

tessl/pypi-jupyterlab-code-formatter

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

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/jupyterlab-code-formatter@3.0.x

To install, run

npx @tessl/cli install tessl/pypi-jupyterlab-code-formatter@3.0.0

index.mddocs/

JupyterLab Code Formatter

A comprehensive JupyterLab extension that provides code formatting capabilities for multiple programming languages including Python, R, Scala, Rust, and C/C++. The extension integrates seamlessly with JupyterLab's interface, offering both notebook cell formatting and file editor formatting with support for various formatters like Black, isort, YAPF, Autopep8, Ruff, and more.

Package Information

  • Package Name: jupyterlab_code_formatter
  • Package Type: pip (JupyterLab Extension)
  • Language: TypeScript (frontend) + Python (backend)
  • Installation: pip install jupyterlab-code-formatter

Core Imports

Python Backend (Server Extension)

from jupyterlab_code_formatter import _load_jupyter_server_extension
from jupyterlab_code_formatter.formatters import SERVER_FORMATTERS
from jupyterlab_code_formatter.handlers import setup_handlers

TypeScript Frontend (Lab Extension)

import { JupyterFrontEndPlugin } from '@jupyterlab/application';
import JupyterlabCodeFormatterClient from './client';
import { JupyterlabNotebookCodeFormatter, JupyterlabFileEditorCodeFormatter } from './formatter';

Basic Usage

Installation and Setup

# Install the extension
pip install jupyterlab-code-formatter

# Install formatters (example for Python)
pip install black isort

# Restart JupyterLab

Using in JupyterLab

Once installed, the extension provides:

  1. Toolbar Button: Format notebook button in notebook toolbar
  2. Command Palette: Access via Command Palette (Ctrl/Cmd+Shift+C)
  3. Menu Items: Format options in Edit menu
  4. Context Menu: Right-click formatting options
  5. Keyboard Shortcuts: Configurable shortcuts for formatting
  6. Format on Save: Automatic formatting when saving files

Basic API Usage (Backend)

from jupyterlab_code_formatter.formatters import BlackFormatter

# Create formatter instance
formatter = BlackFormatter()

# Check if formatter is available
if formatter.importable:
    # Format code
    formatted_code = formatter.format_code(
        code="def hello():pass",
        notebook=True,
        line_length=88
    )

Architecture

JupyterLab Code Formatter follows a client-server architecture:

  • Frontend Extension: TypeScript-based JupyterLab extension providing UI components
  • Backend Server: Python server extension handling formatter execution
  • HTTP API: RESTful communication between frontend and backend
  • Formatter Registry: Pluggable system for adding new code formatters
  • Settings System: JupyterLab settings integration for configuration

Key components:

  • Client: HTTP client for API communication
  • Formatters: Notebook and file editor formatting orchestration
  • Handlers: HTTP request handlers for formatter API
  • Base Classes: Extensible formatter and escaper framework

Capabilities

Frontend Integration

JupyterLab user interface integration including toolbar buttons, menu items, command palette integration, and format-on-save functionality.

class JupyterLabCodeFormatter implements DocumentRegistry.IWidgetExtension<NotebookPanel, INotebookModel> {
  constructor(
    app: JupyterFrontEnd,
    tracker: INotebookTracker,
    palette: ICommandPalette,
    settingRegistry: ISettingRegistry,
    menu: IMainMenu,
    editorTracker: IEditorTracker
  );
  
  createNew(nb: NotebookPanel, context: DocumentRegistry.IContext<INotebookModel>): IDisposable;
  private setupSettings(): Promise<void>;
  private setupAllCommands(): void;
  private onSave(context: DocumentRegistry.IContext<INotebookModel>, state: DocumentRegistry.SaveState): Promise<void>;
  private createNewEditor(widget: DocumentWidget, context: DocumentRegistry.IContext<DocumentModel>): IDisposable;
  private onSaveEditor(context: DocumentRegistry.IContext<DocumentModel>, state: DocumentRegistry.SaveState): Promise<void>;
  private setupWidgetExtension(): void;
  private setupContextMenu(): void;
  private setupCommand(name: string, label: string, command: string): void;
}

Frontend Integration

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.

class JupyterlabNotebookCodeFormatter {
  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;
}

Notebook Formatting

File Editor Formatting

File editor formatting capabilities for standalone code files with language detection and format-on-save support.

class JupyterlabFileEditorCodeFormatter {
  constructor(client: JupyterlabCodeFormatterClient, editorTracker: IEditorTracker);
  
  formatAction(config: any, formatter: string): Promise<void>;
  formatEditor(config: any, context: Context, formatter?: string): Promise<void>;
  applicable(formatter: string, currentWidget: Widget): boolean;
}

File Editor Formatting

HTTP API Client

HTTP client for communication between frontend and backend with request handling and error management.

class JupyterlabCodeFormatterClient {
  request(path: string, method: string, body: any): Promise<any>;
  getAvailableFormatters(cache: boolean): Promise<string>;
}

HTTP API Client

Code Formatters

Extensible code formatter system supporting multiple programming languages and formatter tools with configurable options.

class BaseFormatter(abc.ABC):
    @property
    @abc.abstractmethod
    def label(self) -> str: ...
    
    @property
    @abc.abstractmethod
    def importable(self) -> bool: ...
    
    @abc.abstractmethod
    def format_code(self, code: str, notebook: bool, **options) -> str: ...

Code Formatters

HTTP API Handlers

Server-side HTTP request handlers for formatter discovery and code formatting operations.

class FormattersAPIHandler(APIHandler):
    def get(self) -> None: ...

class FormatAPIHandler(APIHandler):
    def post(self) -> None: ...

def setup_handlers(web_app): ...

HTTP API Handlers

Configuration System

JupyterLab settings integration with support for formatter-specific options, format-on-save settings, and error handling preferences.

Configuration System

Common Types

Context Type

interface Context {
  saving: boolean;
}

Base Formatter Classes

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

### Formatter Registry

```python { .api }
SERVER_FORMATTERS: Dict[str, BaseFormatter]

Constants

namespace Constants {
  const PLUGIN_NAME: string;
  const FORMAT_COMMAND: string;
  const FORMAT_ALL_COMMAND: string;
  const ICON_FORMAT_ALL_SVG: string;
  const ICON_FORMAT_ALL: string;
  const SETTINGS_SECTION: string;
  const COMMAND_SECTION_NAME: string;
  const PLUGIN_VERSION: string;
}