Skip to content
Myr

Merge pull request #1423 from jle64/fish_complete

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Add support for fish completion

authored by David Lord · committed by GitHub · parents 3592995, 6bf782e · Browse files · 3 files+135 added−67 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

3 files+135 added−67 removed

  • other:+135 added−67 removed

3 files+135 added−67 removed

modified:click/_bashcomplete.py+41 added-6 removed
71 unmodified lines
7273compdef %(complete_func)s %(script_names)s74'''7576COMPLETION_SCRIPT_FISH = '''77complete --no-files --command %(script_names)s --arguments "(env %(autocomplete_var)s=complete_fish COMP_WORDS=(commandline -cp) COMP_CWORD=(commandline -t) %(script_names)s)"78'''7980_completion_scripts = {81 "bash": COMPLETION_SCRIPT_BASH,82 "zsh": COMPLETION_SCRIPT_ZSH,83 "fish": COMPLETION_SCRIPT_FISH,84}8586_invalid_ident_char_re = re.compile(r'[^a-zA-Z0-9_]')878889def get_completion_script(prog_name, complete_var, shell):90 cf_name = _invalid_ident_char_re.sub('', prog_name.replace('-', '_'))81 script = COMPLETION_SCRIPT_ZSH if shell == 'zsh' else COMPLETION_SCRIPT_BASH91 script = _completion_scripts.get(shell, COMPLETION_SCRIPT_BASH)92 return (script % {93 'complete_func': '_%s_completion' % cf_name,94 'script_names': prog_name,95 'autocomplete_var': complete_var,
196 unmodified lines
292293 for item in get_choices(cli, prog_name, args, incomplete):294 echo(item[0])295 if include_descriptions:286 # ZSH has trouble dealing with empty array parameters when returned from commands, so use a well defined character '_' to indicate no description is present.296 # ZSH has trouble dealing with empty array parameters when297 # returned from commands, use '_' to indicate no description298 # is present.299 echo(item[1] if item[1] else '_')300301 return True302303304def do_complete_fish(cli, prog_name):305 cwords = split_arg_string(os.environ["COMP_WORDS"])306 incomplete = os.environ["COMP_CWORD"]307 args = cwords[1:]308309 for item in get_choices(cli, prog_name, args, incomplete):310 if item[1]:311 echo("%(arg)s\t%(desc)s" % {"arg": item[0], "desc": item[1]})312 else:313 echo(item[0])314315 return True316317318def bashcomplete(cli, prog_name, complete_var, complete_instr):293 if complete_instr.startswith('source'):294 shell = 'zsh' if complete_instr == 'source_zsh' else 'bash'319 if "_" in complete_instr:320 command, shell = complete_instr.split("_", 1)321 else:322 command = complete_instr323 shell = "bash"324325 if command == "source":326 echo(get_completion_script(prog_name, complete_var, shell))327 return True297 elif complete_instr == 'complete' or complete_instr == 'complete_zsh':298 return do_complete(cli, prog_name, complete_instr == 'complete_zsh')328 elif command == "complete":329 if shell == "fish":330 return do_complete_fish(cli, prog_name)331 elif shell in {"bash", "zsh"}:332 return do_complete(cli, prog_name, shell == "zsh")333334 return False
modified:docs/bashcomplete.rst+92 added-60 removed
1Bash Complete2=============1Shell Completion2================34.. versionadded:: 2.056As of Click 2.0, there is built-in support for Bash completion for7any Click script. There are certain restrictions on when this completion8is available, but for the most part it should just work.6Click can provide tab completion for commands, options, and choice7values. Bash, Zsh, and Fish are supported810Limitations11-----------9Completion is only available if a script is installed and invoked10through an entry point, not through the ``python`` command. See11:ref:`setuptools-integration`.1213Bash completion is only available if a script has been installed properly,14and not executed through the ``python`` command. For information about15how to do that, see :ref:`setuptools-integration`. Click currently16only supports completion for Bash and Zsh.1314What it Completes15-----------------1621Generally, the Bash completion support will complete subcommands,17Generally, the shell completion support will complete commands,18options, and any option or argument values where the type is23:class:`click.Choice`. Subcommands and choices are always listed whereas24options are only listed if at least a dash has been provided. ::19:class:`click.Choice`. Options are only listed if at least a dash has20been entered.2122.. code-block:: text2324 $ repo <TAB><TAB>25 clone commit copy delete setuser26 $ repo clone -<TAB><TAB>27 --deep --help --rev --shallow -r2831Additionally, custom suggestions can be provided for arguments and options with32the ``autocompletion`` parameter. ``autocompletion`` should a callback function33that returns a list of strings. This is useful when the suggestions need to be34dynamically generated at bash completion time. The callback function will be35passed 3 keyword arguments:29Custom completions can be provided for argument and option values by30providing an ``autocompletion`` function that returns a list of strings.31This is useful when the suggestions need to be dynamically generated32completion time. The callback function will be passed 3 keyword33arguments:3437- ``ctx`` - The current click context.38- ``args`` - The list of arguments passed in.39- ``incomplete`` - The partial word that is being completed, as a string. May40 be an empty string ``''`` if no characters have been entered yet.35- ``ctx`` - The current command context.36- ``args`` - The list of arguments passed in.37- ``incomplete`` - The partial word that is being completed. May38 be an empty string if no characters have been entered yet.3942Here is an example of using a callback function to generate dynamic suggestions:40Here is an example of using a callback function to generate dynamic41suggestions:4244.. click:example::43.. code-block:: python4445 import os4647 def get_env_vars(ctx, args, incomplete):
5 unmodified lines
53 click.echo('Environment variable: %s' % envvar)54 click.echo('Value: %s' % os.environ[envvar])555658Completion help strings (ZSH only)59----------------------------------57Completion help strings58-----------------------5961ZSH supports showing documentation strings for completions. These are taken62from the help parameters of options and subcommands. For dynamically generated63completions a help string can be provided by returning a tuple instead of a64string. The first element of the tuple is the completion and the second is the65help string to display.60ZSH and fish support showing documentation strings for completions.61These are taken from the help parameters of options and subcommands. For62dynamically generated completions a help string can be provided by63returning a tuple instead of a string. The first element of the tuple is64the completion and the second is the help string to display.6567Here is an example of using a callback function to generate dynamic suggestions with help strings:66Here is an example of using a callback function to generate dynamic67suggestions with help strings:6869.. click:example::69.. code-block:: python7071 import os7273 def get_colors(ctx, args, incomplete):74 colors = [('red', 'help string for the color red'),75 ('blue', 'help string for the color blue'),76 ('green', 'help string for the color green')]74 colors = [('red', 'a warm color'),75 ('blue', 'a cool color'),76 ('green', 'the other starter color')]77 return [c for c in colors if incomplete in c[0]]7879 @click.command()80 @click.argument("color", type=click.STRING, autocompletion=get_colors)
3 unmodified lines
8485Activation86----------8788In order to activate Bash completion, you need to inform Bash that89completion is available for your script, and how. Any Click application90automatically provides support for that. The general way this works is91through a magic environment variable called ``_<PROG_NAME>_COMPLETE``,92where ``<PROG_NAME>`` is your application executable name in uppercase93with dashes replaced by underscores.88In order to activate shell completion, you need to inform your shell89that completion is available for your script. Any Click application90automatically provides support for that. If the program is executed with91a special ``_<PROG_NAME>_COMPLETE`` variable, the completion mechanism92is triggered instead of the normal command. ``<PROG_NAME>`` is the93executable name in uppercase with dashes replaced by underscores.9495If your tool is called ``foo-bar``, then the magic variable is called96``_FOO_BAR_COMPLETE``. By exporting it with the ``source`` value it will97spit out the activation script which can be trivially activated.95If your tool is called ``foo-bar``, then the variable is called96``_FOO_BAR_COMPLETE``. By exporting it with the ``source_{shell}``97value it will output the activation script to evaluate.9899For instance, to enable Bash completion for your ``foo-bar`` script, this100is what you would need to put into your ``.bashrc``::99Here are examples for a ``foo-bar`` script.100102 eval "$(_FOO_BAR_COMPLETE=source foo-bar)"101For Bash, add this to ``~/.bashrc``:102104For zsh users add this to your ``.zshrc``::103.. code-block:: text104105 eval "$(_FOO_BAR_COMPLETE=source_bash foo-bar)"106107For Zsh, add this to ``~/.zshrc``:108109.. code-block:: text110111 eval "$(_FOO_BAR_COMPLETE=source_zsh foo-bar)"112108From this point onwards, your script will have autocompletion enabled.113For Fish, add this to ``~/.config/fish/completions/foo-bar.fish``:114115.. code-block:: text116117 eval (env _FOO_BAR_COMPLETE=source_fish foo-bar)118119Open a new shell to enable completion. Or run the ``eval`` command120directly in your current shell to enable it temporarily.121122123Activation Script124-----------------125113The above activation example will always invoke your application on114startup. This might be slowing down the shell activation time115significantly if you have many applications. Alternatively, you could also116ship a file with the contents of that, which is what Git and other systems117are doing.126The above ``eval`` examples will invoke your application every time a127shell is started. This may slow down shell startup time significantly.128119This can be easily accomplished::129Alternatively, export the generated completion code as a static script130to be executed. You can ship this file with your builds; tools like Git131do this. At least Zsh will also cache the results of completion files,132but not ``eval`` scripts.133121 _FOO_BAR_COMPLETE=source foo-bar > foo-bar-complete.sh134For Bash:135123For zsh:136.. code-block:: text137138 _FOO_BAR_COMPLETE=source_bash foo-bar > foo-bar-complete.sh139140For Zsh:141142.. code-block:: text143144 _FOO_BAR_COMPLETE=source_zsh foo-bar > foo-bar-complete.sh145127And then you would put this into your .bashrc or .zshrc instead::146For Fish:147148.. code-block:: text149150 _FOO_BAR_COMPLETE=source_zsh foo-bar > foo-bar-complete.sh151152In ``.bashrc`` or ``.zshrc``, source the script instead of the ``eval``153command:154155.. code-block:: text156157 . /path/to/foo-bar-complete.sh158159For Fish, add the file to the completions directory:160161.. code-block:: text162163 _FOO_BAR_COMPLETE=source_fish foo-bar > ~/.config/fish/completions/foo-bar-complete.fish
modified:CHANGES.rst+2 added-1 removed
60 unmodified lines
61- Add a repr to ``Command``, ``Group``, ``Option``, and ``Argument``,62 showing the name for friendlier debugging. :issue:`1267`63- Completion doesn't consider option names if a value starts with64 ``-`` after the ``--`` separator. :issue:`1247`65- ZSH Completion escapes special characters in values. :pr:`1418`65- ZSH completion escapes special characters in values. :pr:`1418`66- Add completion support for Fish shell. :pr:`1423`676869Version 7.070-----------
540 unmodified lines