0
# JupyterLab Code Formatter
1
2
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.
3
4
## Package Information
5
6
- **Package Name**: jupyterlab_code_formatter
7
- **Package Type**: pip (JupyterLab Extension)
8
- **Language**: TypeScript (frontend) + Python (backend)
9
- **Installation**: `pip install jupyterlab-code-formatter`
10
11
## Core Imports
12
13
### Python Backend (Server Extension)
14
15
```python
16
from jupyterlab_code_formatter import _load_jupyter_server_extension
17
from jupyterlab_code_formatter.formatters import SERVER_FORMATTERS
18
from jupyterlab_code_formatter.handlers import setup_handlers
19
```
20
21
### TypeScript Frontend (Lab Extension)
22
23
```typescript
24
import { JupyterFrontEndPlugin } from '@jupyterlab/application';
25
import JupyterlabCodeFormatterClient from './client';
26
import { JupyterlabNotebookCodeFormatter, JupyterlabFileEditorCodeFormatter } from './formatter';
27
```
28
29
## Basic Usage
30
31
### Installation and Setup
32
33
```bash
34
# Install the extension
35
pip install jupyterlab-code-formatter
36
37
# Install formatters (example for Python)
38
pip install black isort
39
40
# Restart JupyterLab
41
```
42
43
### Using in JupyterLab
44
45
Once installed, the extension provides:
46
47
1. **Toolbar Button**: Format notebook button in notebook toolbar
48
2. **Command Palette**: Access via Command Palette (Ctrl/Cmd+Shift+C)
49
3. **Menu Items**: Format options in Edit menu
50
4. **Context Menu**: Right-click formatting options
51
5. **Keyboard Shortcuts**: Configurable shortcuts for formatting
52
6. **Format on Save**: Automatic formatting when saving files
53
54
### Basic API Usage (Backend)
55
56
```python
57
from jupyterlab_code_formatter.formatters import BlackFormatter
58
59
# Create formatter instance
60
formatter = BlackFormatter()
61
62
# Check if formatter is available
63
if formatter.importable:
64
# Format code
65
formatted_code = formatter.format_code(
66
code="def hello():pass",
67
notebook=True,
68
line_length=88
69
)
70
```
71
72
## Architecture
73
74
JupyterLab Code Formatter follows a client-server architecture:
75
76
- **Frontend Extension**: TypeScript-based JupyterLab extension providing UI components
77
- **Backend Server**: Python server extension handling formatter execution
78
- **HTTP API**: RESTful communication between frontend and backend
79
- **Formatter Registry**: Pluggable system for adding new code formatters
80
- **Settings System**: JupyterLab settings integration for configuration
81
82
Key components:
83
84
- **Client**: HTTP client for API communication
85
- **Formatters**: Notebook and file editor formatting orchestration
86
- **Handlers**: HTTP request handlers for formatter API
87
- **Base Classes**: Extensible formatter and escaper framework
88
89
## Capabilities
90
91
### Frontend Integration
92
93
JupyterLab user interface integration including toolbar buttons, menu items, command palette integration, and format-on-save functionality.
94
95
```typescript { .api }
96
class JupyterLabCodeFormatter implements DocumentRegistry.IWidgetExtension<NotebookPanel, INotebookModel> {
97
constructor(
98
app: JupyterFrontEnd,
99
tracker: INotebookTracker,
100
palette: ICommandPalette,
101
settingRegistry: ISettingRegistry,
102
menu: IMainMenu,
103
editorTracker: IEditorTracker
104
);
105
106
createNew(nb: NotebookPanel, context: DocumentRegistry.IContext<INotebookModel>): IDisposable;
107
private setupSettings(): Promise<void>;
108
private setupAllCommands(): void;
109
private onSave(context: DocumentRegistry.IContext<INotebookModel>, state: DocumentRegistry.SaveState): Promise<void>;
110
private createNewEditor(widget: DocumentWidget, context: DocumentRegistry.IContext<DocumentModel>): IDisposable;
111
private onSaveEditor(context: DocumentRegistry.IContext<DocumentModel>, state: DocumentRegistry.SaveState): Promise<void>;
112
private setupWidgetExtension(): void;
113
private setupContextMenu(): void;
114
private setupCommand(name: string, label: string, command: string): void;
115
}
116
```
117
118
[Frontend Integration](./frontend-integration.md)
119
120
### Notebook Formatting
121
122
Comprehensive notebook cell formatting capabilities including selected cells, all cells, and format-on-save functionality with support for magic commands and special syntax.
123
124
```typescript { .api }
125
class JupyterlabNotebookCodeFormatter {
126
constructor(client: JupyterlabCodeFormatterClient, notebookTracker: INotebookTracker);
127
128
formatAction(config: any, formatter?: string): Promise<void>;
129
formatSelectedCodeCells(config: any, formatter?: string, notebook?: Notebook): Promise<void>;
130
formatAllCodeCells(config: any, context: Context, formatter?: string, notebook?: Notebook): Promise<void>;
131
applicable(formatter: string, currentWidget: Widget): boolean;
132
}
133
```
134
135
[Notebook Formatting](./notebook-formatting.md)
136
137
### File Editor Formatting
138
139
File editor formatting capabilities for standalone code files with language detection and format-on-save support.
140
141
```typescript { .api }
142
class JupyterlabFileEditorCodeFormatter {
143
constructor(client: JupyterlabCodeFormatterClient, editorTracker: IEditorTracker);
144
145
formatAction(config: any, formatter: string): Promise<void>;
146
formatEditor(config: any, context: Context, formatter?: string): Promise<void>;
147
applicable(formatter: string, currentWidget: Widget): boolean;
148
}
149
```
150
151
[File Editor Formatting](./file-editor-formatting.md)
152
153
### HTTP API Client
154
155
HTTP client for communication between frontend and backend with request handling and error management.
156
157
```typescript { .api }
158
class JupyterlabCodeFormatterClient {
159
request(path: string, method: string, body: any): Promise<any>;
160
getAvailableFormatters(cache: boolean): Promise<string>;
161
}
162
```
163
164
[HTTP API Client](./http-api-client.md)
165
166
### Code Formatters
167
168
Extensible code formatter system supporting multiple programming languages and formatter tools with configurable options.
169
170
```python { .api }
171
class BaseFormatter(abc.ABC):
172
@property
173
@abc.abstractmethod
174
def label(self) -> str: ...
175
176
@property
177
@abc.abstractmethod
178
def importable(self) -> bool: ...
179
180
@abc.abstractmethod
181
def format_code(self, code: str, notebook: bool, **options) -> str: ...
182
```
183
184
[Code Formatters](./code-formatters.md)
185
186
### HTTP API Handlers
187
188
Server-side HTTP request handlers for formatter discovery and code formatting operations.
189
190
```python { .api }
191
class FormattersAPIHandler(APIHandler):
192
def get(self) -> None: ...
193
194
class FormatAPIHandler(APIHandler):
195
def post(self) -> None: ...
196
197
def setup_handlers(web_app): ...
198
```
199
200
[HTTP API Handlers](./http-api-handlers.md)
201
202
### Configuration System
203
204
JupyterLab settings integration with support for formatter-specific options, format-on-save settings, and error handling preferences.
205
206
[Configuration System](./configuration-system.md)
207
208
## Common Types
209
210
### Context Type
211
212
```typescript { .api }
213
interface Context {
214
saving: boolean;
215
}
216
```
217
218
### Base Formatter Classes
219
220
```typescript { .api }
221
class JupyterlabCodeFormatter {
222
protected client: JupyterlabCodeFormatterClient;
223
working: boolean;
224
225
constructor(client: JupyterlabCodeFormatterClient);
226
protected formatCode(code: string[], formatter: string, options: any, notebook: boolean, cache: boolean): Promise<any>;
227
}
228
229
### Formatter Registry
230
231
```python { .api }
232
SERVER_FORMATTERS: Dict[str, BaseFormatter]
233
```
234
235
### Constants
236
237
```typescript { .api }
238
namespace Constants {
239
const PLUGIN_NAME: string;
240
const FORMAT_COMMAND: string;
241
const FORMAT_ALL_COMMAND: string;
242
const ICON_FORMAT_ALL_SVG: string;
243
const ICON_FORMAT_ALL: string;
244
const SETTINGS_SECTION: string;
245
const COMMAND_SECTION_NAME: string;
246
const PLUGIN_VERSION: string;
247
}
248
```