or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

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

notebook-formatting.mddocs/

0

# Notebook Formatting

1

2

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

3

4

## Capabilities

5

6

### Notebook Code Formatter

7

8

Main class for handling notebook cell formatting operations.

9

10

```typescript { .api }

11

class JupyterlabNotebookCodeFormatter extends JupyterlabCodeFormatter {

12

constructor(

13

client: JupyterlabCodeFormatterClient,

14

notebookTracker: INotebookTracker

15

);

16

17

formatAction(config: any, formatter?: string): Promise<void>;

18

formatSelectedCodeCells(config: any, formatter?: string, notebook?: Notebook): Promise<void>;

19

formatAllCodeCells(config: any, context: Context, formatter?: string, notebook?: Notebook): Promise<void>;

20

applicable(formatter: string, currentWidget: Widget): boolean;

21

}

22

```

23

24

**Constructor Parameters**:

25

- `client` - HTTP client for backend communication

26

- `notebookTracker` - JupyterLab notebook tracker

27

28

**Methods**:

29

- `formatAction()` - Formats selected cells (wrapper for formatSelectedCodeCells)

30

- `formatSelectedCodeCells()` - Formats currently selected code cells

31

- `formatAllCodeCells()` - Formats all code cells in the notebook

32

- `applicable()` - Checks if formatter is applicable to current notebook context

33

34

### Base Formatter Class

35

36

Abstract base class providing common formatting functionality.

37

38

```typescript { .api }

39

abstract class JupyterlabCodeFormatter {

40

working: boolean;

41

protected client: JupyterlabCodeFormatterClient;

42

43

constructor(client: JupyterlabCodeFormatterClient);

44

protected formatCode(

45

code: string[],

46

formatter: string,

47

options: any,

48

notebook: boolean,

49

cache: boolean

50

): Promise<any>;

51

}

52

```

53

54

**Properties**:

55

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

56

57

**Protected Methods**:

58

- `formatCode()` - Sends code to backend for formatting

59

60

### Context Interface

61

62

Defines the context for formatting operations.

63

64

```typescript { .api }

65

interface Context {

66

saving: boolean;

67

}

68

```

69

70

**Properties**:

71

- `saving` - Indicates if formatting is occurring during save operation

72

73

## Usage Examples

74

75

### Creating Notebook Formatter

76

77

```typescript

78

import JupyterlabCodeFormatterClient from './client';

79

import { JupyterlabNotebookCodeFormatter } from './formatter';

80

import { INotebookTracker } from '@jupyterlab/notebook';

81

82

// Create client and formatter

83

const client = new JupyterlabCodeFormatterClient();

84

const notebookFormatter = new JupyterlabNotebookCodeFormatter(client, notebookTracker);

85

```

86

87

### Format Selected Cells

88

89

```typescript

90

// Format selected cells with default formatter

91

await notebookFormatter.formatSelectedCodeCells(config);

92

93

// Format selected cells with specific formatter

94

await notebookFormatter.formatSelectedCodeCells(config, 'black');

95

96

// Format selected cells in specific notebook

97

await notebookFormatter.formatSelectedCodeCells(config, undefined, notebook);

98

```

99

100

### Format All Cells

101

102

```typescript

103

// Format all cells (manual operation)

104

await notebookFormatter.formatAllCodeCells(

105

config,

106

{ saving: false }

107

);

108

109

// Format all cells during save operation

110

await notebookFormatter.formatAllCodeCells(

111

config,

112

{ saving: true },

113

'black'

114

);

115

```

116

117

### Check Formatter Applicability

118

119

```typescript

120

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

121

122

const currentWidget: Widget = app.shell.currentWidget;

123

const isApplicable = notebookFormatter.applicable('black', currentWidget);

124

125

if (isApplicable) {

126

await notebookFormatter.formatAction(config, 'black');

127

}

128

```

129

130

## Formatting Behavior

131

132

### Cell Selection Logic

133

134

The formatter identifies code cells to format based on:

135

136

- **Selected Only**: When `formatSelectedCodeCells` is called, only selected/active cells are formatted

137

- **All Cells**: When `formatAllCodeCells` is called, all code cells in the notebook are formatted

138

- **Cell Type Filtering**: Only cells with `model.type === 'code'` are processed

139

- **Skip Non-Code**: Markdown, raw, and other cell types are ignored

140

141

### Language Detection

142

143

The formatter determines the programming language through:

144

145

1. **Kernel Spec Language**: Prefers `metadata.kernelspec.language`

146

2. **CodeMirror Mode**: Falls back to `metadata.language_info.codemirror_mode`

147

3. **Session Kernel**: Uses current session's kernel specification

148

4. **Default Fallback**: Uses configured default formatters if language cannot be determined

149

150

### Default Formatter Selection

151

152

```typescript

153

// Example of how default formatters are selected

154

const notebookType = getNotebookType(); // "python", "r", etc.

155

const defaultFormatters = config.preferences.default_formatter[notebookType];

156

157

// Can be a single formatter string or array of formatters

158

if (Array.isArray(defaultFormatters)) {

159

// Apply multiple formatters in sequence

160

for (const formatter of defaultFormatters) {

161

await applyFormatter(formatter);

162

}

163

} else if (defaultFormatters) {

164

// Apply single formatter

165

await applyFormatter(defaultFormatters);

166

}

167

```

168

169

### Error Handling

170

171

The formatter provides comprehensive error handling:

172

173

- **Cell Change Detection**: Skips formatting if cell content changed during operation

174

- **Formatter Errors**: Displays error dialogs with options to navigate to problematic cells

175

- **Error Suppression**: Configurable error suppression during auto-format on save

176

- **Working State**: Prevents concurrent formatting operations

177

178

### Magic Command Support

179

180

The formatter preserves Jupyter notebook magic commands and special syntax:

181

182

- **Line Magics**: `%matplotlib inline`, `%time`, etc.

183

- **Cell Magics**: `%%bash`, `%%html`, `%%javascript`, etc.

184

- **Help Commands**: `?function_name`, `??function_name`

185

- **Shell Commands**: `!ls`, `!pip install package`

186

- **Quarto Comments**: `#| label: fig-plot`

187

188

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

189

190

## Configuration Options

191

192

### Formatter-Specific Settings

193

194

Each formatter can have specific configuration options:

195

196

```typescript

197

// Example configuration

198

const config = {

199

black: {

200

line_length: 88,

201

string_normalization: true,

202

magic_trailing_comma: true

203

},

204

isort: {

205

multi_line_output: 3,

206

include_trailing_comma: true,

207

force_grid_wrap: 0

208

},

209

preferences: {

210

default_formatter: {

211

python: ['isort', 'black'],

212

r: ['formatR']

213

}

214

},

215

formatOnSave: true,

216

cacheFormatters: true,

217

suppressFormatterErrors: false,

218

suppressFormatterErrorsIFFAutoFormatOnSave: true

219

};

220

```

221

222

### Save-Related Settings

223

224

- **formatOnSave**: Enable/disable automatic formatting when saving notebooks

225

- **suppressFormatterErrorsIFFAutoFormatOnSave**: Suppress errors only during auto-format on save

226

- **cacheFormatters**: Cache formatter availability checks for better performance