Spaces:
Running
Running
File size: 2,057 Bytes
2d876d1 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
from __future__ import annotations
from prompt_toolkit.completion.filesystem import ExecutableCompleter, PathCompleter
from prompt_toolkit.contrib.regular_languages.compiler import compile
from prompt_toolkit.contrib.regular_languages.completion import GrammarCompleter
__all__ = [
"SystemCompleter",
]
class SystemCompleter(GrammarCompleter):
"""
Completer for system commands.
"""
def __init__(self) -> None:
# Compile grammar.
g = compile(
r"""
# First we have an executable.
(?P<executable>[^\s]+)
# Ignore literals in between.
(
\s+
("[^"]*" | '[^']*' | [^'"]+ )
)*
\s+
# Filename as parameters.
(
(?P<filename>[^\s]+) |
"(?P<double_quoted_filename>[^\s]+)" |
'(?P<single_quoted_filename>[^\s]+)'
)
""",
escape_funcs={
"double_quoted_filename": (lambda string: string.replace('"', '\\"')),
"single_quoted_filename": (lambda string: string.replace("'", "\\'")),
},
unescape_funcs={
"double_quoted_filename": (
lambda string: string.replace('\\"', '"')
), # XXX: not entirely correct.
"single_quoted_filename": (lambda string: string.replace("\\'", "'")),
},
)
# Create GrammarCompleter
super().__init__(
g,
{
"executable": ExecutableCompleter(),
"filename": PathCompleter(only_directories=False, expanduser=True),
"double_quoted_filename": PathCompleter(
only_directories=False, expanduser=True
),
"single_quoted_filename": PathCompleter(
only_directories=False, expanduser=True
),
},
)
|