or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

application.mdcompletion.mdindex.mdkey-bindings.mdlayout.mdprompts.mdstyling.md

index.mddocs/

0

# Prompt-Toolkit

1

2

A comprehensive Python library for building powerful interactive command-line applications. Prompt-toolkit provides advanced features including syntax highlighting, multi-line input editing, code completion, both Emacs and Vi key bindings, reverse and forward incremental search, Unicode support, text selection for copy/paste, bracketed paste support, mouse support, auto-suggestions, multiple input buffers, and cross-platform compatibility. It serves as a modern replacement for GNU readline while offering significantly more functionality.

3

4

## Package Information

5

6

- **Package Name**: prompt_toolkit

7

- **Language**: Python

8

- **Installation**: `pip install prompt_toolkit`

9

10

## Core Imports

11

12

```python

13

import prompt_toolkit

14

```

15

16

Most common imports for basic usage:

17

18

```python

19

from prompt_toolkit import prompt, PromptSession

20

from prompt_toolkit import print_formatted_text

21

from prompt_toolkit.application import Application

22

```

23

24

For advanced formatting:

25

26

```python

27

from prompt_toolkit.formatted_text import HTML, ANSI

28

from prompt_toolkit.styles import Style

29

```

30

31

## Basic Usage

32

33

### Simple Prompting

34

35

```python

36

from prompt_toolkit import prompt

37

38

# Basic input prompt

39

answer = prompt('Give me some input: ')

40

print('You said:', answer)

41

42

# Prompt with default value

43

answer = prompt('Enter name: ', default='John')

44

45

# Multi-line input

46

text = prompt('Enter multi-line text (press ESC then Enter to finish): ',

47

multiline=True)

48

```

49

50

### Formatted Text Output

51

52

```python

53

from prompt_toolkit import print_formatted_text

54

from prompt_toolkit.formatted_text import HTML, ANSI

55

from prompt_toolkit.styles import Style

56

57

# Print with HTML-like formatting

58

print_formatted_text(HTML('<b>Bold</b> and <i>italic</i> text'))

59

60

# Print with ANSI sequences

61

print_formatted_text(ANSI('\x1b[31mRed text\x1b[0m'))

62

63

# Print with custom styles

64

style = Style.from_dict({

65

'title': '#ff0066 bold',

66

'subtitle': '#44ff44 italic'

67

})

68

print_formatted_text(HTML('<title>Hello</title> <subtitle>World</subtitle>'),

69

style=style)

70

```

71

72

### Advanced Prompt Session

73

74

```python

75

from prompt_toolkit import PromptSession

76

from prompt_toolkit.history import FileHistory

77

from prompt_toolkit.completion import WordCompleter

78

79

# Create reusable prompt session

80

session = PromptSession(

81

history=FileHistory('.myhistory'),

82

auto_suggest=AutoSuggestFromHistory(),

83

completer=WordCompleter(['hello', 'world', 'python'])

84

)

85

86

while True:

87

try:

88

text = session.prompt('> ')

89

print('You entered:', text)

90

except (EOFError, KeyboardInterrupt):

91

break

92

```

93

94

## Architecture

95

96

Prompt-toolkit follows a layered, component-based architecture:

97

98

- **Application**: Top-level application class managing the event loop, layout, input/output, and key bindings

99

- **Layout**: Hierarchical container system (HSplit, VSplit, Window) for organizing UI components

100

- **Controls**: UI elements that render content (BufferControl, FormattedTextControl)

101

- **Input/Output**: Platform-specific input sources and output targets with color support

102

- **Key Bindings**: Configurable key mapping system supporting Vi and Emacs modes

103

- **Filters**: Conditional logic system for context-aware behavior

104

- **Styles**: CSS-like styling system with Pygments integration

105

106

This design provides maximum flexibility while maintaining clean separation of concerns, enabling everything from simple prompts to complex interactive applications.

107

108

## Capabilities

109

110

### Core Application Building

111

112

Framework for building full-featured interactive terminal applications with event loops, layouts, and user interfaces.

113

114

```python { .api }

115

class Application:

116

def __init__(

117

self,

118

layout=None,

119

style=None,

120

key_bindings=None,

121

clipboard=None,

122

full_screen=False,

123

mouse_support=False,

124

**kwargs

125

): ...

126

127

def run(self, pre_run=None, set_exception_handler=True): ...

128

def run_async(self, pre_run=None, set_exception_handler=True): ...

129

def exit(self, result=None, exception=None, style=""): ...

130

131

def get_app(): ...

132

def get_app_or_none(): ...

133

```

134

135

[Application Building](./application.md)

136

137

### Text Input and Prompting

138

139

Simple prompt functions and advanced prompt sessions with history, completion, and validation.

140

141

```python { .api }

142

def prompt(

143

message="",

144

default="",

145

password=False,

146

multiline=False,

147

complete_style=CompleteStyle.COLUMN,

148

history=None,

149

auto_suggest=None,

150

completer=None,

151

validator=None,

152

**kwargs

153

): ...

154

155

class PromptSession:

156

def __init__(

157

self,

158

message="",

159

multiline=False,

160

complete_style=CompleteStyle.COLUMN,

161

history=None,

162

auto_suggest=None,

163

completer=None,

164

validator=None,

165

**kwargs

166

): ...

167

168

def prompt(self, message=None, **kwargs): ...

169

```

170

171

[Text Input and Prompting](./prompts.md)

172

173

### Layout and UI Components

174

175

Comprehensive layout system with containers, windows, controls, and widgets for building complex interfaces.

176

177

```python { .api }

178

class Layout:

179

def __init__(self, container, focused_element=None): ...

180

181

class HSplit:

182

def __init__(self, children, **kwargs): ...

183

184

class VSplit:

185

def __init__(self, children, **kwargs): ...

186

187

class Window:

188

def __init__(self, content=None, **kwargs): ...

189

190

class BufferControl:

191

def __init__(self, buffer=None, **kwargs): ...

192

```

193

194

[Layout and UI Components](./layout.md)

195

196

### Styling and Formatting

197

198

Rich text formatting with HTML-like syntax, ANSI sequences, and CSS-like styling with Pygments integration.

199

200

```python { .api }

201

def print_formatted_text(

202

*values,

203

sep=" ",

204

end="\n",

205

file=None,

206

flush=False,

207

style=None,

208

output=None,

209

color_depth=None,

210

style_transformation=None,

211

include_default_pygments_style=None

212

): ...

213

214

class HTML:

215

def __init__(self, value): ...

216

217

class ANSI:

218

def __init__(self, value): ...

219

220

class Style:

221

@classmethod

222

def from_dict(cls, style_dict): ...

223

```

224

225

[Styling and Formatting](./styling.md)

226

227

### Key Bindings and Input

228

229

Configurable key binding system supporting Vi and Emacs editing modes with customizable key mappings.

230

231

```python { .api }

232

class KeyBindings:

233

def __init__(self): ...

234

def add(self, *keys, **kwargs): ...

235

236

class KeyPress:

237

def __init__(self, key, data=""): ...

238

239

def load_vi_bindings(): ...

240

def load_emacs_bindings(): ...

241

```

242

243

[Key Bindings and Input](./key-bindings.md)

244

245

### Completion and Validation

246

247

Auto-completion system with built-in completers for files, words, and custom data, plus validation framework.

248

249

```python { .api }

250

class Completer:

251

def get_completions(self, document, complete_event): ...

252

253

class Completion:

254

def __init__(

255

self,

256

text,

257

start_position=0,

258

display=None,

259

display_meta=None,

260

style="",

261

selected_style=""

262

): ...

263

264

class Validator:

265

def validate(self, document): ...

266

267

class ValidationError(Exception):

268

def __init__(self, cursor_position=0, message=""): ...

269

```

270

271

[Completion and Validation](./completion.md)

272

273

## Types

274

275

### Core Application Types

276

277

```python { .api }

278

from typing import Optional, List, Dict, Any, Callable, Union

279

from prompt_toolkit.filters import FilterOrBool

280

281

# Application result type

282

AppResult = Any

283

284

# Layout dimension type

285

AnyDimension = Union[None, int, Dimension]

286

287

# Formatted text types

288

AnyFormattedText = Union[str, List[Tuple[str, str]], HTML, ANSI, FormattedText]

289

StyleAndTextTuples = List[Tuple[str, str]]

290

291

# Filter type for conditional behavior

292

FilterOrBool = Union[bool, Filter]

293

```

294

295

### Buffer and Document Types

296

297

```python { .api }

298

class Document:

299

def __init__(self, text="", cursor_position=None): ...

300

@property

301

def text(self) -> str: ...

302

@property

303

def cursor_position(self) -> int: ...

304

@property

305

def current_line(self) -> str: ...

306

307

class Buffer:

308

def __init__(

309

self,

310

document=None,

311

multiline=True,

312

read_only=False,

313

history=None,

314

completer=None,

315

validator=None,

316

**kwargs

317

): ...

318

```

319

320

### Completion Types

321

322

```python { .api }

323

class CompleteEvent:

324

def __init__(self, text_inserted=False, completion_requested=False): ...

325

326

# Completion style enumeration

327

class CompleteStyle(Enum):

328

COLUMN = "column"

329

MULTI_COLUMN = "multi-column"

330

READLINE_LIKE = "readline-like"

331

```

332

333

### Key and Input Types

334

335

```python { .api }

336

class Keys:

337

# Common keys

338

ControlA = "c-a"

339

ControlC = "c-c"

340

ControlD = "c-d"

341

Enter = "\r"

342

Escape = "\x1b"

343

Backspace = "\x7f"

344

Delete = "\x1b[3~"

345

# Function keys

346

F1 = "\x1bOP"

347

F2 = "\x1bOQ"

348

# Arrow keys

349

Up = "\x1b[A"

350

Down = "\x1b[B"

351

Left = "\x1b[D"

352

Right = "\x1b[C"

353

354

class EditingMode(Enum):

355

EMACS = "EMACS"

356

VI = "VI"

357

```