0
# Autocomplete and Path Input
1
2
Intelligent text input with completion support including word completion for predefined choices and file system path completion with filtering options.
3
4
## Capabilities
5
6
### Autocomplete Input
7
8
Text input with intelligent completion from a predefined list of choices, supporting fuzzy matching and metadata display.
9
10
```python { .api }
11
def autocomplete(message: str, choices: List[str], default: str = "",
12
qmark: str = "?", completer: Optional[Completer] = None,
13
meta_information: Optional[Dict[str, Any]] = None,
14
ignore_case: bool = True, match_middle: bool = True,
15
complete_style: CompleteStyle = CompleteStyle.COLUMN,
16
validate: Any = None, style: Optional[Style] = None,
17
**kwargs) -> Question:
18
"""
19
Create an autocomplete text input prompt.
20
21
Args:
22
message: The question/prompt text to display
23
choices: List of possible completion choices
24
default: Default value pre-filled in input
25
qmark: Question prefix symbol (default "?")
26
completer: Custom completer instance (overrides choices)
27
meta_information: Dict mapping choices to metadata descriptions
28
ignore_case: Case-insensitive matching
29
match_middle: Allow matching anywhere in choice text
30
complete_style: Completion display style (COLUMN, MULTI_COLUMN, READLINE)
31
validate: Validator function or Validator instance
32
style: Custom styling configuration
33
**kwargs: Additional prompt_toolkit arguments
34
35
Returns:
36
Question instance ready for execution
37
"""
38
```
39
40
### Path Input
41
42
File and directory path input with intelligent filesystem completion, filtering, and validation.
43
44
```python { .api }
45
def path(message: str, default: Union[Path, str] = "", qmark: str = "?",
46
validate: Any = None, completer: Optional[Completer] = None,
47
style: Optional[Style] = None, only_directories: bool = False,
48
get_paths: Optional[Callable[[], List[str]]] = None,
49
file_filter: Optional[Callable[[str], bool]] = None,
50
complete_style: CompleteStyle = CompleteStyle.MULTI_COLUMN,
51
**kwargs) -> Question:
52
"""
53
Create a file/directory path input prompt with completion.
54
55
Args:
56
message: The question/prompt text to display
57
default: Default path value
58
qmark: Question prefix symbol (default "?")
59
validate: Validator function or Validator instance
60
completer: Custom path completer (overrides built-in)
61
style: Custom styling configuration
62
only_directories: Restrict completion to directories only
63
get_paths: Custom function to provide path suggestions
64
file_filter: Function to filter displayed files/directories
65
complete_style: Completion display style
66
**kwargs: Additional prompt_toolkit arguments
67
68
Returns:
69
Question instance ready for execution
70
"""
71
```
72
73
## Completer Classes
74
75
### Word Completer
76
77
Customizable word completion for autocomplete prompts.
78
79
```python { .api }
80
class WordCompleter(Completer):
81
def __init__(self, choices: Union[List[str], Callable[[], List[str]]],
82
ignore_case: bool = True,
83
meta_information: Optional[Dict[str, Any]] = None,
84
match_middle: bool = True) -> None:
85
"""
86
Word completion from a list of choices.
87
88
Args:
89
choices: Static list or function returning list of choices
90
ignore_case: Case-insensitive matching
91
meta_information: Dict mapping choices to metadata
92
match_middle: Allow matching anywhere in choice text
93
"""
94
95
def get_completions(self, document: Document,
96
complete_event: CompleteEvent) -> Iterable[Completion]:
97
"""
98
Generate completions for the current document state.
99
100
Args:
101
document: Current input document
102
complete_event: Completion event details
103
104
Yields:
105
Completion objects with matched text and metadata
106
"""
107
```
108
109
### Enhanced Path Completer
110
111
Advanced path completion with better user experience and filtering options.
112
113
```python { .api }
114
class GreatUXPathCompleter(PathCompleter):
115
def __init__(self, only_directories: bool = False,
116
get_paths: Optional[Callable[[], List[str]]] = None,
117
file_filter: Optional[Callable[[str], bool]] = None,
118
min_input_len: int = 0, expanduser: bool = False) -> None:
119
"""
120
Enhanced path completion with filtering and UX improvements.
121
122
Args:
123
only_directories: Show only directories in completion
124
get_paths: Custom function to provide additional paths
125
file_filter: Function to filter displayed files
126
min_input_len: Minimum input length to trigger completion
127
expanduser: Expand ~ to user home directory
128
"""
129
130
def get_completions(self, document: Document,
131
complete_event: CompleteEvent) -> Iterable[Completion]:
132
"""
133
Generate path completions with enhanced filtering.
134
135
Args:
136
document: Current input document
137
complete_event: Completion event details
138
139
Yields:
140
Completion objects for matching paths
141
"""
142
```
143
144
## Usage Examples
145
146
### Basic Autocomplete
147
148
```python
149
import questionary
150
151
# Simple word completion
152
language = questionary.autocomplete(
153
"Choose programming language:",
154
choices=["Python", "JavaScript", "TypeScript", "Java", "C++", "Go", "Rust"]
155
).ask()
156
157
# With default value
158
framework = questionary.autocomplete(
159
"Select framework:",
160
choices=["Django", "Flask", "FastAPI", "Tornado"],
161
default="Django"
162
).ask()
163
```
164
165
### Autocomplete with Metadata
166
167
```python
168
import questionary
169
170
# Choices with descriptions
171
database = questionary.autocomplete(
172
"Select database:",
173
choices=["postgresql", "mysql", "sqlite", "mongodb"],
174
meta_information={
175
"postgresql": "Advanced open-source relational database",
176
"mysql": "Popular open-source relational database",
177
"sqlite": "Lightweight embedded database",
178
"mongodb": "Document-oriented NoSQL database"
179
}
180
).ask()
181
```
182
183
### Dynamic Autocomplete
184
185
```python
186
import questionary
187
188
# Dynamic choices from function
189
def get_available_ports():
190
# Could query system for available ports
191
return ["8000", "8080", "3000", "5000", "9000"]
192
193
port = questionary.autocomplete(
194
"Choose port:",
195
choices=get_available_ports()
196
).ask()
197
198
# Custom completer
199
from questionary.prompts.autocomplete import WordCompleter
200
201
custom_completer = WordCompleter(
202
choices=["option1", "option2", "option3"],
203
ignore_case=True,
204
match_middle=False
205
)
206
207
result = questionary.autocomplete(
208
"Enter option:",
209
choices=[], # Not used when completer is provided
210
completer=custom_completer
211
).ask()
212
```
213
214
### Basic Path Input
215
216
```python
217
import questionary
218
219
# File path input
220
config_file = questionary.path("Enter config file path:").ask()
221
222
# Directory path only
223
output_dir = questionary.path(
224
"Select output directory:",
225
only_directories=True
226
).ask()
227
228
# With default path
229
log_file = questionary.path(
230
"Log file location:",
231
default="/var/log/app.log"
232
).ask()
233
```
234
235
### Advanced Path Configuration
236
237
```python
238
import questionary
239
from pathlib import Path
240
241
# Directory-only with validation
242
def validate_directory(path):
243
p = Path(path)
244
if not p.exists():
245
return f"Directory {path} does not exist"
246
if not p.is_dir():
247
return f"{path} is not a directory"
248
return True
249
250
project_dir = questionary.path(
251
"Select project directory:",
252
only_directories=True,
253
validate=validate_directory
254
).ask()
255
256
# File filtering
257
def python_files_only(filename):
258
return filename.endswith('.py') or Path(filename).is_dir()
259
260
python_file = questionary.path(
261
"Select Python file:",
262
file_filter=python_files_only
263
).ask()
264
265
# Custom path suggestions
266
def get_common_paths():
267
return ["/home/user/projects", "/opt", "/usr/local"]
268
269
path = questionary.path(
270
"Enter path:",
271
get_paths=get_common_paths
272
).ask()
273
```
274
275
### Completion Styles
276
277
```python
278
import questionary
279
from prompt_toolkit.completion import CompleteStyle
280
281
# Different completion display styles
282
result = questionary.autocomplete(
283
"Choose option:",
284
choices=["very_long_option_name_1", "very_long_option_name_2", "short"],
285
complete_style=CompleteStyle.MULTI_COLUMN # or COLUMN, READLINE
286
).ask()
287
```
288
289
### Custom Validation
290
291
```python
292
import questionary
293
from questionary import Validator, ValidationError
294
295
class EmailValidator(Validator):
296
def validate(self, document):
297
text = document.text
298
if '@' not in text:
299
raise ValidationError(
300
message="Please enter a valid email address",
301
cursor_position=len(text)
302
)
303
304
email = questionary.autocomplete(
305
"Enter email:",
306
choices=["user@domain.com", "admin@site.org"],
307
validate=EmailValidator()
308
).ask()
309
```