change extension to .md
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by denuoweb · committed by denuoweb · parent fbbcc96 · Browse files · 4 files·+297 added−297 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+297 added−297 removed
- other:+297 added−297 removed
Provenance
- Commit
1838a0b- Tree
7e7c95e- Author
denuoweb <jaron@rosenau.info>- Committer
denuoweb <jaron@rosenau.info>- Parent
fbbcc96
4 files changed+297 added−297 removed
added:docs/setuptools.md+6 added
123456:orphan:
Setuptools Integration======================
Moved to :doc:`entry-points`.deleted:docs/setuptools.rst-6 removed
1-:orphan:2-3-Setuptools Integration4-======================5-6-Moved to :doc:`entry-points`.added:docs/shell-completion.md+291 added
1+.. currentmodule:: click.shell_completion2+3+Shell Completion4+================5+6+Click provides tab completion support for Bash (version 4.4 and up),7+Zsh, and Fish. It is possible to add support for other shells too, and8+suggestions can be customized at multiple levels.9+10+Shell completion suggests command names, option names, and values for11+choice, file, and path parameter types. Options are only listed if at12+least a dash has been entered. Hidden commands and options are not13+shown.14+15+.. code-block:: text16+17+ $ repo <TAB><TAB>18+ clone commit copy delete setuser19+ $ repo clone -<TAB><TAB>20+ --deep --help --rev --shallow -r21+22+23+Enabling Completion24+-------------------25+26+Completion is only available if a script is installed and invoked27+through an entry point, not through the ``python`` command. See28+:doc:`entry-points`. Once the executable is installed, calling it with29+a special environment variable will put Click in completion mode.30+31+To enable shell completion, the user needs to register a special32+function with their shell. The exact script varies depending on the33+shell you are using. Click will output it when called with34+``_{FOO_BAR}_COMPLETE`` set to ``{shell}_source``. ``{FOO_BAR}`` is35+the executable name in uppercase with dashes replaced by underscores.36+It is conventional but not strictly required for environment variable37+names to be in upper case. This convention helps distinguish environment38+variables from regular shell variables and commands, making scripts39+and configuration files more readable and easier to maintain. The40+built-in shells are ``bash``, ``zsh``, and ``fish``.41+42+Provide your users with the following instructions customized to your43+program name. This uses ``foo-bar`` as an example.44+45+.. tabs::46+47+ .. group-tab:: Bash48+49+ Add this to ``~/.bashrc``:50+51+ .. code-block:: bash52+53+ eval "$(_FOO_BAR_COMPLETE=bash_source foo-bar)"54+55+ .. group-tab:: Zsh56+57+ Add this to ``~/.zshrc``:58+59+ .. code-block:: zsh60+61+ eval "$(_FOO_BAR_COMPLETE=zsh_source foo-bar)"62+63+ .. group-tab:: Fish64+65+ Add this to ``~/.config/fish/completions/foo-bar.fish``:66+67+ .. code-block:: fish68+69+ _FOO_BAR_COMPLETE=fish_source foo-bar | source70+71+ This is the same file used for the activation script method72+ below. For Fish it's probably always easier to use that method.73+74+Using ``eval`` means that the command is invoked and evaluated every75+time a shell is started, which can delay shell responsiveness. To speed76+it up, write the generated script to a file, then source that. You can77+generate the files ahead of time and distribute them with your program78+to save your users a step.79+80+.. tabs::81+82+ .. group-tab:: Bash83+84+ Save the script somewhere.85+86+ .. code-block:: bash87+88+ _FOO_BAR_COMPLETE=bash_source foo-bar > ~/.foo-bar-complete.bash89+90+ Source the file in ``~/.bashrc``.91+92+ .. code-block:: bash93+94+ . ~/.foo-bar-complete.bash95+96+ .. group-tab:: Zsh97+98+ Save the script somewhere.99+100+ .. code-block:: bash101+102+ _FOO_BAR_COMPLETE=zsh_source foo-bar > ~/.foo-bar-complete.zsh103+104+ Source the file in ``~/.zshrc``.105+106+ .. code-block:: bash107+108+ . ~/.foo-bar-complete.zsh109+110+ .. group-tab:: Fish111+112+ Save the script to ``~/.config/fish/completions/foo-bar.fish``:113+114+ .. code-block:: fish115+116+ _FOO_BAR_COMPLETE=fish_source foo-bar > ~/.config/fish/completions/foo-bar.fish117+118+After modifying the shell config, you need to start a new shell in order119+for the changes to be loaded.120+121+122+Custom Type Completion123+----------------------124+125+When creating a custom :class:`~click.ParamType`, override its126+:meth:`~click.ParamType.shell_complete` method to provide shell127+completion for parameters with the type. The method must return a list128+of :class:`~CompletionItem` objects. Besides the value, these objects129+hold metadata that shell support might use. The built-in implementations130+use ``type`` to indicate special handling for paths, and ``help`` for131+shells that support showing a help string next to a suggestion.132+133+In this example, the type will suggest environment variables that start134+with the incomplete value.135+136+.. code-block:: python137+138+ class EnvVarType(ParamType):139+ name = "envvar"140+141+ def shell_complete(self, ctx, param, incomplete):142+ return [143+ CompletionItem(name)144+ for name in os.environ if name.startswith(incomplete)145+ ]146+147+ @click.command()148+ @click.option("--ev", type=EnvVarType())149+ def cli(ev):150+ click.echo(os.environ[ev])151+152+153+Overriding Value Completion154+---------------------------155+156+Value completions for a parameter can be customized without a custom157+type by providing a ``shell_complete`` function. The function is used158+instead of any completion provided by the type. It is passed 3 keyword159+arguments:160+161+- ``ctx`` - The current command context.162+- ``param`` - The current parameter requesting completion.163+- ``incomplete`` - The partial word that is being completed. May164+ be an empty string if no characters have been entered yet.165+166+It must return a list of :class:`CompletionItem` objects, or as a167+shortcut it can return a list of strings.168+169+In this example, the command will suggest environment variables that170+start with the incomplete value.171+172+.. code-block:: python173+174+ def complete_env_vars(ctx, param, incomplete):175+ return [k for k in os.environ if k.startswith(incomplete)]176+177+ @click.command()178+ @click.argument("name", shell_complete=complete_env_vars)179+ def cli(name):180+ click.echo(f"Name: {name}")181+ click.echo(f"Value: {os.environ[name]}")182+183+184+Adding Support for a Shell185+--------------------------186+187+Support can be added for shells that do not come built in. Be sure to188+check PyPI to see if there's already a package that adds support for189+your shell. This topic is very technical, you'll want to look at Click's190+source to study the built-in implementations.191+192+Shell support is provided by subclasses of :class:`ShellComplete`193+registered with :func:`add_completion_class`. When Click is invoked in194+completion mode, it calls :meth:`~ShellComplete.source` to output the195+completion script, or :meth:`~ShellComplete.complete` to output196+completions. The base class provides default implementations that197+require implementing some smaller parts.198+199+First, you'll need to figure out how your shell's completion system200+works and write a script to integrate it with Click. It must invoke your201+program with the environment variable ``_{FOO_BAR}_COMPLETE`` set to202+``{shell}_complete`` and pass the complete args and incomplete value.203+How it passes those values, and the format of the completion response204+from Click is up to you.205+206+In your subclass, set :attr:`~ShellComplete.source_template` to the207+completion script. The default implementation will perform ``%``208+formatting with the following variables:209+210+- ``complete_func`` - A safe name for the completion function defined211+ in the script.212+- ``complete_var`` - The environment variable name for passing the213+ ``{shell}_complete`` instruction.214+- ``foo_bar`` - The name of the executable being completed.215+216+The example code is for a made up shell "My Shell" or "mysh" for short.217+218+.. code-block:: python219+220+ from click.shell_completion import add_completion_class221+ from click.shell_completion import ShellComplete222+223+ _mysh_source = """\224+ %(complete_func)s {225+ response=$(%(complete_var)s=mysh_complete %(foo_bar)s)226+ # parse response and set completions somehow227+ }228+ call-on-complete %(foo_bar)s %(complete_func)s229+ """230+231+ @add_completion_class232+ class MyshComplete(ShellComplete):233+ name = "mysh"234+ source_template = _mysh_source235+236+Next, implement :meth:`~ShellComplete.get_completion_args`. This must237+get, parse, and return the complete args and incomplete value from the238+completion script. For example, for the Bash implementation the239+``COMP_WORDS`` env var contains the command line args as a string, and240+the ``COMP_CWORD`` env var contains the index of the incomplete arg. The241+method must return a ``(args, incomplete)`` tuple.242+243+.. code-block:: python244+245+ import os246+ from click.parser import split_arg_string247+248+ class MyshComplete(ShellComplete):249+ ...250+251+ def get_completion_args(self):252+ args = split_arg_string(os.environ["COMP_WORDS"])253+254+ if os.environ["COMP_PARTIAL"] == "1":255+ incomplete = args.pop()256+ return args, incomplete257+258+ return args, ""259+260+Finally, implement :meth:`~ShellComplete.format_completion`. This is261+called to format each :class:`CompletionItem` into a string. For262+example, the Bash implementation returns ``f"{item.type},{item.value}``263+(it doesn't support help strings), and the Zsh implementation returns264+each part separated by a newline, replacing empty help with a ``_``265+placeholder. This format is entirely up to what you parse with your266+completion script.267+268+The ``type`` value is usually ``plain``, but it can be another value269+that the completion script can switch on. For example, ``file`` or270+``dir`` can tell the shell to handle path completion, since the shell is271+better at that than Click.272+273+.. code-block:: python274+275+ class MyshComplete(ShellComplete):276+ ...277+278+ def format_completion(self, item):279+ return f"{item.type}\t{item.value}"280+281+With those three things implemented, the new shell support is ready. In282+case those weren't sufficient, there are more parts that can be283+overridden, but that probably isn't necessary.284+285+The activation instructions will again depend on how your shell works.286+Use the following to generate the completion script, then load it into287+the shell somehow.288+289+.. code-block:: text290+291+ _FOO_BAR_COMPLETE=mysh_source foo-bardeleted:docs/shell-completion.rst-291 removed
1-.. currentmodule:: click.shell_completion2-3-Shell Completion4-================5-6-Click provides tab completion support for Bash (version 4.4 and up),7-Zsh, and Fish. It is possible to add support for other shells too, and8-suggestions can be customized at multiple levels.9-10-Shell completion suggests command names, option names, and values for11-choice, file, and path parameter types. Options are only listed if at12-least a dash has been entered. Hidden commands and options are not13-shown.14-15-.. code-block:: text16-17- $ repo <TAB><TAB>18- clone commit copy delete setuser19- $ repo clone -<TAB><TAB>20- --deep --help --rev --shallow -r21-22-23-Enabling Completion24--------------------25-26-Completion is only available if a script is installed and invoked27-through an entry point, not through the ``python`` command. See28-:doc:`entry-points`. Once the executable is installed, calling it with29-a special environment variable will put Click in completion mode.30-31-To enable shell completion, the user needs to register a special32-function with their shell. The exact script varies depending on the33-shell you are using. Click will output it when called with34-``_{FOO_BAR}_COMPLETE`` set to ``{shell}_source``. ``{FOO_BAR}`` is35-the executable name in uppercase with dashes replaced by underscores.36-It is conventional but not strictly required for environment variable37-names to be in upper case. This convention helps distinguish environment38-variables from regular shell variables and commands, making scripts39-and configuration files more readable and easier to maintain. The40-built-in shells are ``bash``, ``zsh``, and ``fish``.41-42-Provide your users with the following instructions customized to your43-program name. This uses ``foo-bar`` as an example.44-45-.. tabs::46-47- .. group-tab:: Bash48-49- Add this to ``~/.bashrc``:50-51- .. code-block:: bash52-53- eval "$(_FOO_BAR_COMPLETE=bash_source foo-bar)"54-55- .. group-tab:: Zsh56-57- Add this to ``~/.zshrc``:58-59- .. code-block:: zsh60-61- eval "$(_FOO_BAR_COMPLETE=zsh_source foo-bar)"62-63- .. group-tab:: Fish64-65- Add this to ``~/.config/fish/completions/foo-bar.fish``:66-67- .. code-block:: fish68-69- _FOO_BAR_COMPLETE=fish_source foo-bar | source70-71- This is the same file used for the activation script method72- below. For Fish it's probably always easier to use that method.73-74-Using ``eval`` means that the command is invoked and evaluated every75-time a shell is started, which can delay shell responsiveness. To speed76-it up, write the generated script to a file, then source that. You can77-generate the files ahead of time and distribute them with your program78-to save your users a step.79-80-.. tabs::81-82- .. group-tab:: Bash83-84- Save the script somewhere.85-86- .. code-block:: bash87-88- _FOO_BAR_COMPLETE=bash_source foo-bar > ~/.foo-bar-complete.bash89-90- Source the file in ``~/.bashrc``.91-92- .. code-block:: bash93-94- . ~/.foo-bar-complete.bash95-96- .. group-tab:: Zsh97-98- Save the script somewhere.99-100- .. code-block:: bash101-102- _FOO_BAR_COMPLETE=zsh_source foo-bar > ~/.foo-bar-complete.zsh103-104- Source the file in ``~/.zshrc``.105-106- .. code-block:: bash107-108- . ~/.foo-bar-complete.zsh109-110- .. group-tab:: Fish111-112- Save the script to ``~/.config/fish/completions/foo-bar.fish``:113-114- .. code-block:: fish115-116- _FOO_BAR_COMPLETE=fish_source foo-bar > ~/.config/fish/completions/foo-bar.fish117-118-After modifying the shell config, you need to start a new shell in order119-for the changes to be loaded.120-121-122-Custom Type Completion123-----------------------124-125-When creating a custom :class:`~click.ParamType`, override its126-:meth:`~click.ParamType.shell_complete` method to provide shell127-completion for parameters with the type. The method must return a list128-of :class:`~CompletionItem` objects. Besides the value, these objects129-hold metadata that shell support might use. The built-in implementations130-use ``type`` to indicate special handling for paths, and ``help`` for131-shells that support showing a help string next to a suggestion.132-133-In this example, the type will suggest environment variables that start134-with the incomplete value.135-136-.. code-block:: python137-138- class EnvVarType(ParamType):139- name = "envvar"140-141- def shell_complete(self, ctx, param, incomplete):142- return [143- CompletionItem(name)144- for name in os.environ if name.startswith(incomplete)145- ]146-147- @click.command()148- @click.option("--ev", type=EnvVarType())149- def cli(ev):150- click.echo(os.environ[ev])151-152-153-Overriding Value Completion154----------------------------155-156-Value completions for a parameter can be customized without a custom157-type by providing a ``shell_complete`` function. The function is used158-instead of any completion provided by the type. It is passed 3 keyword159-arguments:160-161-- ``ctx`` - The current command context.162-- ``param`` - The current parameter requesting completion.163-- ``incomplete`` - The partial word that is being completed. May164- be an empty string if no characters have been entered yet.165-166-It must return a list of :class:`CompletionItem` objects, or as a167-shortcut it can return a list of strings.168-169-In this example, the command will suggest environment variables that170-start with the incomplete value.171-172-.. code-block:: python173-174- def complete_env_vars(ctx, param, incomplete):175- return [k for k in os.environ if k.startswith(incomplete)]176-177- @click.command()178- @click.argument("name", shell_complete=complete_env_vars)179- def cli(name):180- click.echo(f"Name: {name}")181- click.echo(f"Value: {os.environ[name]}")182-183-184-Adding Support for a Shell185---------------------------186-187-Support can be added for shells that do not come built in. Be sure to188-check PyPI to see if there's already a package that adds support for189-your shell. This topic is very technical, you'll want to look at Click's190-source to study the built-in implementations.191-192-Shell support is provided by subclasses of :class:`ShellComplete`193-registered with :func:`add_completion_class`. When Click is invoked in194-completion mode, it calls :meth:`~ShellComplete.source` to output the195-completion script, or :meth:`~ShellComplete.complete` to output196-completions. The base class provides default implementations that197-require implementing some smaller parts.198-199-First, you'll need to figure out how your shell's completion system200-works and write a script to integrate it with Click. It must invoke your201-program with the environment variable ``_{FOO_BAR}_COMPLETE`` set to202-``{shell}_complete`` and pass the complete args and incomplete value.203-How it passes those values, and the format of the completion response204-from Click is up to you.205-206-In your subclass, set :attr:`~ShellComplete.source_template` to the207-completion script. The default implementation will perform ``%``208-formatting with the following variables:209-210-- ``complete_func`` - A safe name for the completion function defined211- in the script.212-- ``complete_var`` - The environment variable name for passing the213- ``{shell}_complete`` instruction.214-- ``foo_bar`` - The name of the executable being completed.215-216-The example code is for a made up shell "My Shell" or "mysh" for short.217-218-.. code-block:: python219-220- from click.shell_completion import add_completion_class221- from click.shell_completion import ShellComplete222-223- _mysh_source = """\224- %(complete_func)s {225- response=$(%(complete_var)s=mysh_complete %(foo_bar)s)226- # parse response and set completions somehow227- }228- call-on-complete %(foo_bar)s %(complete_func)s229- """230-231- @add_completion_class232- class MyshComplete(ShellComplete):233- name = "mysh"234- source_template = _mysh_source235-236-Next, implement :meth:`~ShellComplete.get_completion_args`. This must237-get, parse, and return the complete args and incomplete value from the238-completion script. For example, for the Bash implementation the239-``COMP_WORDS`` env var contains the command line args as a string, and240-the ``COMP_CWORD`` env var contains the index of the incomplete arg. The241-method must return a ``(args, incomplete)`` tuple.242-243-.. code-block:: python244-245- import os246- from click.parser import split_arg_string247-248- class MyshComplete(ShellComplete):249- ...250-251- def get_completion_args(self):252- args = split_arg_string(os.environ["COMP_WORDS"])253-254- if os.environ["COMP_PARTIAL"] == "1":255- incomplete = args.pop()256- return args, incomplete257-258- return args, ""259-260-Finally, implement :meth:`~ShellComplete.format_completion`. This is261-called to format each :class:`CompletionItem` into a string. For262-example, the Bash implementation returns ``f"{item.type},{item.value}``263-(it doesn't support help strings), and the Zsh implementation returns264-each part separated by a newline, replacing empty help with a ``_``265-placeholder. This format is entirely up to what you parse with your266-completion script.267-268-The ``type`` value is usually ``plain``, but it can be another value269-that the completion script can switch on. For example, ``file`` or270-``dir`` can tell the shell to handle path completion, since the shell is271-better at that than Click.272-273-.. code-block:: python274-275- class MyshComplete(ShellComplete):276- ...277-278- def format_completion(self, item):279- return f"{item.type}\t{item.value}"280-281-With those three things implemented, the new shell support is ready. In282-case those weren't sufficient, there are more parts that can be283-overridden, but that probably isn't necessary.284-285-The activation instructions will again depend on how your shell works.286-Use the following to generate the completion script, then load it into287-the shell somehow.288-289-.. code-block:: text290-291- _FOO_BAR_COMPLETE=mysh_source foo-bar