Debian Codegraph @

crazy_complete/zsh_complete.py

raw
1 # SPDX-License-Identifier: GPL-3.0-or-later
2 # Copyright (C) 2025-2026 Benjamin Abendroth <[email protected]>
3
4 '''This module contains code for completing arguments in Zsh.'''
5
6 from . import shell
7 from . import utils
8 from .pattern import bash_glob_to_zsh_glob
9 from .str_utils import join_with_wrap, indent
10 from .zsh_utils import (
11 escape_colon, escape_square_brackets, make_file_extension_pattern
12 )
13 from .type_utils import is_dict_type
14
15
16 CHOICES_INLINE_THRESHOLD = 80
17 # The `choices` command can in Zsh be expressed inline in an optspec, like:
18 # (foo bar baz)
19 # or:
20 # (foo:"Foo value" bar:"Bar value" baz:"Baz value)
21 #
22 # This variable defines how big this string can get before a function
23 # is used instead.
24
25
26 class ZshCompletionBase:
27 '''Base class for Zsh completions.'''
28
29 def get_action_string(self):
30 '''Return an action string that can be used in an option spec.'''
31 raise NotImplementedError
32
33 def get_function(self):
34 '''Return a function that can be used in e.g. `_sequence`.'''
35 raise NotImplementedError
36
37
38 class ZshComplFunc(ZshCompletionBase):
39 '''Complete using a function.'''
40
41 def __init__(self, ctxt, args, needs_braces=False):
42 self.ctxt = ctxt
43 self.args = args
44 self.needs_braces = needs_braces
45
46 def get_action_string(self):
47 if len(self.args) == 1:
48 cmd = self.args[0]
49 else:
50 cmd = shell.join_quoted(self.args)
51
52 if self.needs_braces:
53 return shell.quote(f'{{{cmd}}}')
54
55 return shell.quote(cmd)
56
57 def get_function(self):
58 if len(self.args) == 1:
59 return self.args[0]
60
61 code = shell.join_quoted(self.args)
62 funcname = self.ctxt.helpers.add_dynamic_func(self.ctxt, code)
63 return funcname
64
65
66 class ZshCompleteChoices(ZshCompletionBase):
67 '''Complete from a set of words.'''
68
69 def __init__(self, ctxt, trace, choices):
70 self.ctxt = ctxt
71 self.trace = trace
72 self.choices = choices
73
74 def _list_action_string(self):
75 items = [str(item) for item in self.choices]
76 quoted = [shell.quote(item) for item in items]
77 action = shell.quote('(%s)' % ' '.join(quoted))
78 if len(action) <= CHOICES_INLINE_THRESHOLD:
79 return action
80
81 return self._list_function()
82
83 def _list_function(self):
84 metavar = shell.quote(self.ctxt.option.metavar or '')
85 quoted = [shell.quote(escape_colon(c)) for c in self.choices]
86 line_length = self.ctxt.config.line_length - 2
87
88 code = 'local items=(\n'
89 code += indent(join_with_wrap(' ', '\n', line_length, quoted), 2)
90 code += '\n)\n\n'
91 code += f'_describe -- {metavar} items'
92
93 funcname = self.ctxt.helpers.add_dynamic_func(self.ctxt, code)
94 return funcname
95
96 def _dict_action_string(self):
97 def str0(s):
98 return str(s) if s is not None else ''
99
100 items = [str0(item) for item in self.choices.keys()]
101 descriptions = [str0(value) for value in self.choices.values()]
102 colon = any(':' in s for s in items + descriptions)
103 quoted = []
104
105 for item, desc in zip(items, descriptions):
106 val = shell.quote(item)
107 if desc:
108 val += ':%s' % shell.quote(desc)
109 quoted.append(val)
110
111 action = shell.quote('((%s))' % ' '.join(quoted))
112 if not colon and len(action) <= CHOICES_INLINE_THRESHOLD:
113 return action
114
115 return self._dict_function()
116
117 def _dict_function(self):
118 metavar = shell.quote(self.ctxt.option.metavar or '')
119
120 code = 'local items=(\n'
121 for item, desc in self.choices.items():
122 item = shell.quote(escape_colon(str(item)))
123 if desc:
124 desc = shell.quote(str(desc))
125 code += f' {item}:{desc}\n'
126 else:
127 code += f' {item}\n'
128 code += ')\n\n'
129 code += f'_describe -- {metavar} items'
130
131 funcname = self.ctxt.helpers.add_dynamic_func(self.ctxt, code)
132 return funcname
133
134 def get_action_string(self):
135 if is_dict_type(self.choices):
136 return self._dict_action_string()
137
138 return self._list_action_string()
139
140 def get_function(self):
141 if is_dict_type(self.choices):
142 return self._dict_function()
143
144 return self._list_function()
145
146
147 class ZshCompleteCommand(ZshCompletionBase):
148 '''Complete a command from $PATH.'''
149
150 def __init__(self, ctxt, opts):
151 self.ctxt = ctxt
152 self.code = None
153 path = None
154 append = None
155 prepend = None
156
157 if opts:
158 path = opts.get('path', None)
159 append = opts.get('path_append', None)
160 prepend = opts.get('path_prepend', None)
161
162 if path:
163 self.code = 'local -x PATH=%s' % shell.quote(path)
164 elif append and prepend:
165 append = shell.quote(append)
166 prepend = shell.quote(prepend)
167 self.code = 'local -x PATH=%s:"$PATH":%s' % (prepend, append)
168 elif append:
169 self.code = 'local -x PATH="$PATH":%s' % shell.quote(append)
170 elif prepend:
171 self.code = 'local -x PATH=%s:"$PATH"' % shell.quote(prepend)
172
173 def get_action_string(self):
174 if not self.code:
175 return '_command_names'
176
177 code = f'{self.code}\n_command_names'
178 funcname = self.ctxt.helpers.add_dynamic_func(self.ctxt, code)
179 return funcname
180
181 def get_function(self):
182 if not self.code:
183 return '_command_names'
184
185 code = f'{self.code}\n_command_names'
186 funcname = self.ctxt.helpers.add_dynamic_func(self.ctxt, code)
187 return funcname
188
189
190 class ZshCompleteRange(ZshCompletionBase):
191 '''Complete a range of integers.'''
192
193 def __init__(self, ctxt, start, stop, step):
194 self.ctxt = ctxt
195 self.start = start
196 self.stop = stop
197 self.step = step
198
199 def get_action_string(self):
200 if self.step == 1:
201 return f"'({{{self.start}..{self.stop}}})'"
202
203 return f"'({{{self.start}..{self.stop}..{self.step}}})'"
204
205 def get_function(self):
206 if self.step == 1:
207 code = f"command seq {self.start} {self.stop}"
208 else:
209 code = f"command seq {self.start} {self.step} {self.stop}"
210
211 code = f'compadd -- $({code})'
212
213 funcname = self.ctxt.helpers.add_dynamic_func(self.ctxt, code)
214 return funcname
215
216
217 class ZshKeyValueList(ZshComplFunc):
218 '''Used for completing a comma-separated list of key-value pairs.'''
219
220 # pylint: disable=too-many-arguments
221 # pylint: disable=too-many-positional-arguments
222
223 def __init__(self, ctxt, trace, completer, pair_separator, value_separator,
224 values, condition_func):
225 trace.append('key_value_list')
226 spec = []
227
228 for definition in utils.get_key_value_list_definitions(values):
229 desc = ''
230 if definition.description:
231 desc = shell.quote('[%s]' % escape_square_brackets(definition.description))
232
233 excludes = ''
234 if definition.excludes:
235 excludes = shell.quote('(%s)' % ' '.join(definition.excludes))
236
237 repeatable = ''
238 if definition.repeatable:
239 repeatable = "'*'"
240
241 condition = ''
242 if condition_func is not None:
243 condition = '$c %s && ' % (definition.key)
244
245 key = escape_colon(definition.key)
246 if not definition.completer:
247 spec.append(f'{condition}a+=({excludes}{repeatable}{key}{desc})')
248 elif definition.completer[0] == 'none':
249 spec.append(f'{condition}a+=({excludes}{repeatable}{key}{desc}:::)')
250 else:
251 compl_obj = completer.complete_from_def(ctxt, trace, definition.completer)
252 action = compl_obj.get_action_string()
253 spec.append(f'{condition}a+=({excludes}{repeatable}{key}{desc}:::{action})')
254
255
256 code = 'local -a a=()\n'
257 if condition_func is not None:
258 code += 'local c=%s\n' % shell.quote(condition_func)
259 code += '%s\n' % '\n'.join(spec)
260 code += '_values -s %s -S %s %s "${a[@]}"' % (
261 shell.quote(pair_separator),
262 shell.quote(value_separator),
263 shell.quote(ctxt.option.metavar or ''),
264 )
265
266 func = ctxt.helpers.add_dynamic_func(ctxt, code)
267
268 super().__init__(ctxt, [func], needs_braces=True)
269
270
271 class ZshKeyValuePair(ZshComplFunc):
272 '''Used for completing a single key-value pair.'''
273
274 # pylint: disable=too-many-arguments
275 # pylint: disable=too-many-positional-arguments
276
277 def __init__(self, ctxt, trace, completer, value_separator, values,
278 condition_func):
279 trace.append('key_value_pair')
280 spec = []
281
282 for key, desc, complete in values:
283 if desc:
284 desc = shell.quote('[%s]' % escape_square_brackets(desc))
285 else:
286 desc = ''
287
288 condition = ''
289 if condition_func is not None:
290 condition = '$c %s && ' % shell.quote(key)
291
292 key = escape_colon(key)
293 if not complete:
294 spec.append(f'{condition}a+=({key}{desc})')
295 elif complete[0] == 'none':
296 spec.append(f'{condition}a+=({key}{desc}:::)')
297 else:
298 compl_obj = completer.complete_from_def(ctxt, trace, complete)
299 action = compl_obj.get_action_string()
300 spec.append(f'{condition}a+=({key}{desc}:::{action})')
301
302 code = 'local -a a=()\n'
303 if condition_func is not None:
304 code += 'local c=%s\n' % shell.quote(condition_func)
305 code += '%s\n' % '\n'.join(spec)
306 code += '_values -S %s %s "${a[@]}"' % (
307 shell.quote(value_separator),
308 shell.quote(ctxt.option.metavar or '')
309 )
310
311 func = ctxt.helpers.add_dynamic_func(ctxt, code)
312
313 super().__init__(ctxt, [func], needs_braces=True)
314
315
316 class ZshCompleteCombine(ZshCompletionBase):
317 '''Combine multiple completers into one.'''
318
319 def __init__(self, ctxt, trace, completer, commands):
320 trace.append('combine')
321
322 completions = []
323 for command_args in commands:
324 compl_obj = completer.complete_from_def(ctxt, trace, command_args)
325 action_string = compl_obj.get_action_string()
326 completions.append(f'::{action_string}')
327
328 code = '_alternative \\\n'
329 code += indent(' \\\n'.join(completions), 2)
330
331 self.func = ctxt.helpers.add_dynamic_func(ctxt, code)
332
333 def get_function(self):
334 return self.func
335
336 def get_action_string(self):
337 return shell.quote('{%s}' % self.func)
338
339
340 class ZshCompleter(shell.ShellCompleter):
341 '''Code generator for completing arguments in Zsh.'''
342
343 # pylint: disable=too-many-public-methods
344 # pylint: disable=missing-function-docstring
345 # pylint: disable=too-many-arguments
346 # pylint: disable=too-many-positional-arguments
347
348 def none(self, ctxt, _trace, *_):
349 return ZshComplFunc(ctxt, [' '])
350
351 def integer(self, ctxt, _trace, options=None):
352 args = []
353 suffixes = []
354 help_ = ctxt.option.help or ctxt.option.metavar or ''
355
356 if options:
357 if 'min' in options:
358 args += ['-l', str(options['min'])]
359 if 'max' in options:
360 args += ['-m', str(options['max'])]
361 if 'suffixes' in options:
362 for suffix, description in options['suffixes'].items():
363 suffixes.append(f'{suffix}:{description}')
364 if 'help' in options:
365 help_ = options['help']
366
367 return ZshComplFunc(ctxt, ['_numbers', *args, help_, *suffixes])
368
369 def float(self, ctxt, _trace, options=None):
370 args = ['-f']
371 suffixes = []
372 help_ = ctxt.option.help or ctxt.option.metavar or ''
373
374 if options:
375 if 'min' in options:
376 args += ['-l', str(options['min'])]
377 if 'max' in options:
378 args += ['-m', str(options['max'])]
379 if 'suffixes' in options:
380 for suffix, description in options['suffixes'].items():
381 suffixes.append(f'{suffix}:{description}')
382 if 'help' in options:
383 help_ = options['help']
384
385 return ZshComplFunc(ctxt, ['_numbers', *args, help_, *suffixes])
386
387 def choices(self, ctxt, trace, choices):
388 return ZshCompleteChoices(ctxt, trace, choices)
389
390 def command(self, ctxt, _trace, opts=None):
391 return ZshCompleteCommand(ctxt, opts)
392
393 def directory(self, ctxt, _trace, opts=None):
394 directory = None if opts is None else opts.get('directory', None)
395
396 if not directory:
397 return ZshComplFunc(ctxt, ['_directories'])
398
399 if directory.startswith('/'):
400 return ZshComplFunc(ctxt, ['_directories', '-W', directory])
401
402 func = ctxt.helpers.use_function('path_files_relative')
403 return ZshComplFunc(ctxt, [func, directory, '-/'], needs_braces=True)
404
405 def file(self, ctxt, _trace, opts=None):
406 fuzzy = False
407 directory = None
408 extensions = None
409 ignore_globs = None
410
411 if opts:
412 fuzzy = opts.get('fuzzy', False)
413 directory = opts.get('directory', None)
414 extensions = opts.get('extensions', None)
415 ignore_globs = opts.get('ignore_globs', None)
416
417 args = []
418
419 if extensions:
420 args.extend(['-g', make_file_extension_pattern(extensions, fuzzy)])
421
422 if ignore_globs:
423 patterns = map(bash_glob_to_zsh_glob, ignore_globs)
424 args.extend(['-F', '(%s)' % ' '.join(patterns)])
425
426 if not directory:
427 return ZshComplFunc(ctxt, ['_files'] + args)
428
429 if directory.startswith('/'):
430 return ZshComplFunc(ctxt, ['_files', '-W', directory, *args])
431
432 func = ctxt.helpers.use_function('path_files_relative')
433 return ZshComplFunc(ctxt, [func, directory, *args], needs_braces=True)
434
435 def mime_file(self, ctxt, _trace, pattern):
436 func = ctxt.helpers.use_function('mime_file')
437 return ZshComplFunc(ctxt, [func, pattern], needs_braces=True)
438
439 def group(self, ctxt, _trace):
440 return ZshComplFunc(ctxt, ['_groups'])
441
442 def hostname(self, ctxt, _trace):
443 return ZshComplFunc(ctxt, ['_hosts'])
444
445 def pid(self, ctxt, _trace):
446 return ZshComplFunc(ctxt, ['_pids'])
447
448 def process(self, ctxt, _trace):
449 return ZshComplFunc(ctxt, ['_process_names', '-a'])
450
451 def range(self, ctxt, _trace, start, stop, step=1):
452 return ZshCompleteRange(ctxt, start, stop, step)
453
454 def user(self, ctxt, _trace):
455 return ZshComplFunc(ctxt, ['_users'])
456
457 def variable(self, ctxt, _trace):
458 return ZshComplFunc(ctxt, ['_vars'])
459
460 def environment(self, ctxt, _trace):
461 return ZshComplFunc(ctxt, ['_parameters', '-g', '*export*'])
462
463 def exec(self, ctxt, _trace, command):
464 funcname = ctxt.helpers.use_function('exec')
465 return ZshComplFunc(ctxt, [funcname, command], needs_braces=True)
466
467 def exec_fast(self, ctxt, _trace, command):
468 funcname = ctxt.helpers.use_function('exec')
469 return ZshComplFunc(ctxt, [funcname, command], needs_braces=True)
470
471 def exec_internal(self, ctxt, _trace, command):
472 return ZshComplFunc(ctxt, [command], needs_braces=True)
473
474 def value_list(self, ctxt, _trace, opts):
475 desc = ctxt.option.metavar or ''
476 values = opts['values']
477 separator = opts.get('separator', ',')
478 duplicates = opts.get('duplicates', False)
479
480 if is_dict_type(values):
481 esc = escape_square_brackets
482 values = ['%s[%s]' % (esc(item), esc(desc)) for item, desc in values.items()]
483 else:
484 values = [escape_square_brackets(i) for i in values]
485
486 if not duplicates:
487 return ZshComplFunc(ctxt, ['_values', '-s', separator, desc] + values)
488
489 values_func = ZshComplFunc(ctxt, ['_values', desc] + values).get_function()
490
491 if separator == ',':
492 return ZshComplFunc(ctxt, ['_sequence', '-d', values_func])
493
494 return ZshComplFunc(ctxt, ['_sequence', '-s', separator, '-d', values_func])
495
496 def key_value_list(self, ctxt, trace, pair_separator, value_separator, values, condition_func=None):
497 return ZshKeyValueList(ctxt, trace, self, pair_separator, value_separator, values, condition_func)
498
499 def key_value_pair(self, ctxt, trace, value_separator, values, condition_func=None):
500 return ZshKeyValuePair(ctxt, trace, self, value_separator, values, condition_func)
501
502 def key_value_list_exec(self, ctxt, _trace, pair_separator, value_separator, command):
503 func = ctxt.helpers.use_function('key_value_list_exec')
504 return ZshComplFunc(ctxt, [func, pair_separator, value_separator, command], needs_braces=True)
505
506 def key_value_pair_exec(self, ctxt, _trace, value_separator, command):
507 func = ctxt.helpers.use_function('key_value_pair_exec')
508 return ZshComplFunc(ctxt, [func, value_separator, command], needs_braces=True)
509
510 def combine(self, ctxt, trace, commands):
511 return ZshCompleteCombine(ctxt, trace, self, commands)
512
513 def list(self, ctxt, trace, command, opts=None):
514 separator = opts.get('separator', ',') if opts else ','
515 duplicates = opts.get('duplicates', False) if opts else False
516 trace.append('list')
517
518 obj = self.complete_from_def(ctxt, trace, command)
519 func = obj.get_function()
520
521 args = []
522
523 if separator != ',':
524 args.extend(['-s', separator])
525
526 if duplicates:
527 args.append('-d')
528
529 return ZshComplFunc(ctxt, ['_sequence', *args, func])
530
531 def history(self, ctxt, _trace, pattern):
532 func = ctxt.helpers.use_function('history')
533 return ZshComplFunc(ctxt, [func, pattern], needs_braces=True)
534
535 def commandline_string(self, ctxt, _trace):
536 return ZshComplFunc(ctxt, ['_cmdstring'])
537
538 def command_arg(self, ctxt, _trace):
539 return ZshComplFunc(ctxt, ['_normal'])
540
541 def date(self, ctxt, _trace, format_):
542 return ZshComplFunc(ctxt, ['_dates', '-f', format_])
543
544 def date_format(self, ctxt, _trace):
545 return ZshComplFunc(ctxt, ['_date_formats'])
546
547 def uid(self, ctxt, _trace):
548 func = ctxt.helpers.use_function('uid_list')
549 return ZshComplFunc(ctxt, [func], needs_braces=True)
550
551 def gid(self, ctxt, _trace):
552 func = ctxt.helpers.use_function('gid_list')
553 return ZshComplFunc(ctxt, [func], needs_braces=True)
554
555 def filesystem_type(self, ctxt, _trace):
556 return ZshComplFunc(ctxt, ['_file_systems'])
557
558 def signal(self, ctxt, _trace):
559 return ZshComplFunc(ctxt, ['_signals'])
560
561 def prefix(self, ctxt, trace, prefix, command):
562 prefix_func = ctxt.helpers.use_function('prefix')
563 obj = self.complete_from_def(ctxt, trace, command)
564 func = obj.get_function()
565 return ZshComplFunc(ctxt, [prefix_func, prefix, func], needs_braces=True)
566
567 def ip_address(self, ctxt, _trace, type_='all'):
568 if type_ == 'ipv4':
569 return ZshComplFunc(ctxt, ['_bind_addresses', '-4'])
570
571 if type_ == 'ipv6':
572 return ZshComplFunc(ctxt, ['_bind_addresses', '-6'])
573
574 if type_ == 'ipv4+':
575 return ZshComplFunc(ctxt, ['_bind_addresses', '-40'])
576
577 if type_ == 'ipv6+':
578 return ZshComplFunc(ctxt, ['_bind_addresses', '-60'])
579
580 if type_ == 'all+':
581 return ZshComplFunc(ctxt, ['_bind_addresses', '-0'])
582
583 return ZshComplFunc(ctxt, ['_bind_addresses'])
584
585 # =========================================================================
586 # Bonus
587 # =========================================================================
588
589 def mountpoint(self, ctxt, _trace):
590 func = ctxt.helpers.use_function('mountpoint')
591 return ZshComplFunc(ctxt, [func], needs_braces=True)
592
593 def net_interface(self, ctxt, _trace):
594 return ZshComplFunc(ctxt, ['_net_interfaces'])
595
596 def timezone(self, ctxt, _trace):
597 return ZshComplFunc(ctxt, ['_time_zone'])
598
599 def locale(self, ctxt, _trace):
600 return ZshComplFunc(ctxt, ['_locales'])
601
602 def charset(self, ctxt, _trace):
603 func = ctxt.helpers.use_function('charset_list')
604 return ZshComplFunc(ctxt, [func], needs_braces=True)
605
606 def alsa_card(self, ctxt, _trace):
607 func = ctxt.helpers.use_function('alsa_complete_cards')
608 return ZshComplFunc(ctxt, [func], needs_braces=True)
609
610 def alsa_device(self, ctxt, _trace):
611 func = ctxt.helpers.use_function('alsa_complete_devices')
612 return ZshComplFunc(ctxt, [func], needs_braces=True)