0
# Text Input and Prompting
1
2
Simple prompt functions and advanced prompt sessions with history, completion, validation, and auto-suggestions. These provide the primary interface for collecting user input in command-line applications.
3
4
## Capabilities
5
6
### Simple Prompt Function
7
8
The `prompt()` function provides a simple interface for collecting user input with optional features like default values, password masking, and multi-line input.
9
10
```python { .api }
11
def prompt(
12
message="",
13
default="",
14
password=False,
15
multiline=False,
16
complete_style=CompleteStyle.COLUMN,
17
history=None,
18
auto_suggest=None,
19
completer=None,
20
validator=None,
21
bottom_toolbar=None,
22
style=None,
23
color_depth=None,
24
cursor=CursorShape.BLOCK,
25
include_default_pygments_style=True,
26
lexer=None,
27
reserve_space_for_menu=8,
28
**kwargs
29
):
30
"""
31
Prompt user for input with various options.
32
33
Parameters:
34
- message: str, prompt message to display
35
- default: str, default value if user enters nothing
36
- password: bool, mask input for password entry
37
- multiline: bool, allow multi-line input
38
- complete_style: CompleteStyle, how to display completions
39
- history: History instance for command history
40
- auto_suggest: AutoSuggest instance for suggestions
41
- completer: Completer instance for auto-completion
42
- validator: Validator instance for input validation
43
- bottom_toolbar: toolbar content for bottom of screen
44
- style: Style instance for visual formatting
45
- color_depth: ColorDepth for color support level
46
- lexer: Lexer instance for syntax highlighting
47
48
Returns:
49
str: User input text
50
51
Raises:
52
KeyboardInterrupt: On Ctrl-C
53
EOFError: On Ctrl-D or EOF
54
"""
55
```
56
57
### PromptSession Class
58
59
Advanced prompt session class that can be reused multiple times while maintaining state like history and configuration.
60
61
```python { .api }
62
class PromptSession:
63
def __init__(
64
self,
65
message="",
66
multiline=False,
67
wrap_lines=True,
68
complete_style=CompleteStyle.COLUMN,
69
history=None,
70
auto_suggest=None,
71
completer=None,
72
validator=None,
73
bottom_toolbar=None,
74
style=None,
75
color_depth=None,
76
cursor=CursorShape.BLOCK,
77
include_default_pygments_style=True,
78
lexer=None,
79
reserve_space_for_menu=8,
80
**kwargs
81
):
82
"""
83
Create a reusable prompt session.
84
85
Parameters:
86
- message: str, default prompt message
87
- multiline: bool, allow multi-line input by default
88
- wrap_lines: bool, wrap long lines in display
89
- complete_style: CompleteStyle, completion display style
90
- history: History instance for command history
91
- auto_suggest: AutoSuggest instance for suggestions
92
- completer: Completer instance for auto-completion
93
- validator: Validator instance for input validation
94
- bottom_toolbar: toolbar content for bottom of screen
95
- style: Style instance for visual formatting
96
- color_depth: ColorDepth for color support level
97
- lexer: Lexer instance for syntax highlighting
98
"""
99
100
def prompt(self, message=None, **kwargs):
101
"""
102
Show prompt and collect user input.
103
104
Parameters:
105
- message: str, override default message
106
- **kwargs: additional options to override session defaults
107
108
Returns:
109
str: User input text
110
111
Raises:
112
KeyboardInterrupt: On Ctrl-C
113
EOFError: On Ctrl-D or EOF
114
"""
115
```
116
117
### Choice Selection
118
119
Functions for presenting users with multiple choice selections.
120
121
```python { .api }
122
def choice(
123
choices,
124
message="Please choose: ",
125
default=None,
126
style=None,
127
**kwargs
128
):
129
"""
130
Present user with a list of choices to select from.
131
132
Parameters:
133
- choices: List of choice options
134
- message: str, prompt message
135
- default: default choice if any
136
- style: Style instance for formatting
137
138
Returns:
139
Selected choice value
140
"""
141
142
def confirm(message="Confirm?", default=False):
143
"""
144
Show yes/no confirmation prompt.
145
146
Parameters:
147
- message: str, confirmation message
148
- default: bool, default choice (True=Yes, False=No)
149
150
Returns:
151
bool: True for yes, False for no
152
"""
153
154
def create_confirm_session(message="Confirm?", suffix=" (y/n) "):
155
"""
156
Create a reusable confirmation prompt session.
157
158
Parameters:
159
- message: str, confirmation message
160
- suffix: str, suffix to append to message
161
162
Returns:
163
PromptSession configured for yes/no input
164
"""
165
```
166
167
### Dialog Functions
168
169
Pre-built dialog functions for common user interaction patterns.
170
171
```python { .api }
172
def input_dialog(
173
title="",
174
text="",
175
ok_text="OK",
176
cancel_text="Cancel",
177
completer=None,
178
validator=None,
179
password=False,
180
style=None,
181
**kwargs
182
):
183
"""
184
Show input dialog box.
185
186
Parameters:
187
- title: str, dialog title
188
- text: str, dialog message text
189
- ok_text: str, OK button text
190
- cancel_text: str, Cancel button text
191
- completer: Completer for input field
192
- validator: Validator for input field
193
- password: bool, mask input
194
- style: Style for dialog
195
196
Returns:
197
str or None: Input text or None if cancelled
198
"""
199
200
def message_dialog(
201
title="",
202
text="",
203
ok_text="OK",
204
style=None,
205
**kwargs
206
):
207
"""
208
Show message dialog box.
209
210
Parameters:
211
- title: str, dialog title
212
- text: str, message text to display
213
- ok_text: str, OK button text
214
- style: Style for dialog
215
216
Returns:
217
None
218
"""
219
220
def yes_no_dialog(
221
title="",
222
text="",
223
yes_text="Yes",
224
no_text="No",
225
style=None,
226
**kwargs
227
):
228
"""
229
Show yes/no confirmation dialog.
230
231
Parameters:
232
- title: str, dialog title
233
- text: str, confirmation message
234
- yes_text: str, Yes button text
235
- no_text: str, No button text
236
- style: Style for dialog
237
238
Returns:
239
bool: True for yes, False for no
240
"""
241
242
def button_dialog(
243
title="",
244
text="",
245
buttons=None,
246
style=None,
247
**kwargs
248
):
249
"""
250
Show dialog with custom buttons.
251
252
Parameters:
253
- title: str, dialog title
254
- text: str, dialog message
255
- buttons: List of button specifications
256
- style: Style for dialog
257
258
Returns:
259
Button result value
260
"""
261
262
def radiolist_dialog(
263
title="",
264
text="",
265
ok_text="OK",
266
cancel_text="Cancel",
267
values=None,
268
default=None,
269
style=None,
270
**kwargs
271
):
272
"""
273
Show radio button selection dialog.
274
275
Parameters:
276
- title: str, dialog title
277
- text: str, dialog message
278
- ok_text: str, OK button text
279
- cancel_text: str, Cancel button text
280
- values: List of (value, label) tuples
281
- default: default selected value
282
- style: Style for dialog
283
284
Returns:
285
Selected value or None if cancelled
286
"""
287
288
def checkboxlist_dialog(
289
title="",
290
text="",
291
ok_text="OK",
292
cancel_text="Cancel",
293
values=None,
294
default_values=None,
295
style=None,
296
**kwargs
297
):
298
"""
299
Show checkbox selection dialog.
300
301
Parameters:
302
- title: str, dialog title
303
- text: str, dialog message
304
- ok_text: str, OK button text
305
- cancel_text: str, Cancel button text
306
- values: List of (value, label) tuples
307
- default_values: List of initially selected values
308
- style: Style for dialog
309
310
Returns:
311
List of selected values or None if cancelled
312
"""
313
314
def progress_dialog(
315
title="",
316
text="",
317
run_callback=None,
318
style=None,
319
**kwargs
320
):
321
"""
322
Show progress dialog with progress bar.
323
324
Parameters:
325
- title: str, dialog title
326
- text: str, dialog message
327
- run_callback: Function to execute with progress updates
328
- style: Style for dialog
329
330
Returns:
331
Callback result
332
"""
333
```
334
335
## Usage Examples
336
337
### Basic Prompting
338
339
```python
340
from prompt_toolkit import prompt
341
342
# Simple input
343
name = prompt('Enter your name: ')
344
print(f'Hello {name}!')
345
346
# Prompt with default value
347
city = prompt('Enter city: ', default='New York')
348
349
# Password input (masked)
350
password = prompt('Password: ', password=True)
351
352
# Multi-line input
353
text = prompt('Enter multi-line text (press ESC then Enter to finish): ',
354
multiline=True)
355
```
356
357
### Prompt Session with History
358
359
```python
360
from prompt_toolkit import PromptSession
361
from prompt_toolkit.history import FileHistory
362
from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
363
364
# Create session with file-based history
365
session = PromptSession(
366
message='> ',
367
history=FileHistory('.myapp_history'),
368
auto_suggest=AutoSuggestFromHistory()
369
)
370
371
# Use session multiple times
372
while True:
373
try:
374
command = session.prompt()
375
if command.lower() == 'exit':
376
break
377
print(f'You entered: {command}')
378
except (EOFError, KeyboardInterrupt):
379
break
380
```
381
382
### Prompt with Validation
383
384
```python
385
from prompt_toolkit import prompt
386
from prompt_toolkit.validation import Validator, ValidationError
387
import re
388
389
class EmailValidator(Validator):
390
def validate(self, document):
391
text = document.text
392
if not re.match(r'^[^@]+@[^@]+\.[^@]+$', text):
393
raise ValidationError(
394
message='Invalid email format',
395
cursor_position=len(text)
396
)
397
398
# Prompt with email validation
399
email = prompt('Enter email: ', validator=EmailValidator())
400
print(f'Email: {email}')
401
```
402
403
### Prompt with Completion
404
405
```python
406
from prompt_toolkit import prompt
407
from prompt_toolkit.completion import WordCompleter
408
409
# Create completer with predefined words
410
completer = WordCompleter([
411
'hello', 'world', 'python', 'programming',
412
'prompt-toolkit', 'completion', 'validation'
413
])
414
415
# Prompt with tab completion
416
text = prompt('Enter command: ', completer=completer)
417
print(f'You chose: {text}')
418
```
419
420
### Dialog Examples
421
422
```python
423
from prompt_toolkit.shortcuts import (
424
input_dialog, message_dialog, yes_no_dialog,
425
radiolist_dialog, checkboxlist_dialog
426
)
427
428
# Input dialog
429
name = input_dialog(title='Name Input', text='Enter your name:')
430
if name:
431
print(f'Hello {name}!')
432
433
# Message dialog
434
message_dialog(
435
title='Information',
436
text='Operation completed successfully!'
437
)
438
439
# Yes/No confirmation
440
if yes_no_dialog(title='Confirm', text='Delete all files?'):
441
print('Files deleted')
442
else:
443
print('Operation cancelled')
444
445
# Radio button selection
446
choice = radiolist_dialog(
447
title='Select Option',
448
text='Choose your preferred editor:',
449
values=[
450
('vim', 'Vim'),
451
('emacs', 'Emacs'),
452
('vscode', 'VS Code'),
453
('atom', 'Atom')
454
]
455
)
456
if choice:
457
print(f'You selected: {choice}')
458
459
# Checkbox selection
460
selections = checkboxlist_dialog(
461
title='Features',
462
text='Select features to enable:',
463
values=[
464
('syntax', 'Syntax highlighting'),
465
('completion', 'Auto-completion'),
466
('validation', 'Input validation'),
467
('history', 'Command history')
468
]
469
)
470
if selections:
471
print(f'Selected features: {selections}')
472
```
473
474
### Advanced Styling
475
476
```python
477
from prompt_toolkit import prompt
478
from prompt_toolkit.styles import Style
479
from prompt_toolkit.formatted_text import HTML
480
481
# Create custom style
482
style = Style.from_dict({
483
'prompt': '#00aa00 bold',
484
'input': '#ffffff',
485
'bottom-toolbar': '#333333 bg:#ffff00'
486
})
487
488
# Styled prompt with toolbar
489
result = prompt(
490
HTML('<prompt>Enter command:</prompt> '),
491
style=style,
492
bottom_toolbar=HTML('<b>F1:</b> Help | <b>F2:</b> Save | <b>Ctrl-C:</b> Exit')
493
)
494
```