Friday, October 20, 2017

Running arbitrary command when using auto-completion in Zsh

Did you ever wanted to run an predefined command as auto-completion in zsh?
For example, you may have a script that accepts only predefined values as input.
Actually it's possible and quite easy.

First, you will need a file that will be invoked to auto-complete the command.
Here's an example:

You can replace the HERE_COMES_SHELL_COMMAND with any command. For example it can be "cat ~/myfile" to read options from a file.
#compdef defines the list of commands this file will auto-complete. In the above example it's going to be mycommand, change it to your actual command.
As I already mentioned, it can be also a list: #compdef mycommand myscript myprogram - will autocomplete any of the mycommand, myscript, myprogram.

Now, you need to tell zsh about your file:
1. Place your file to some directory. For example: ~/.myautocomplete
2. In your ~/.zshrc add the following line: fpath=(~/.myautocomplete $fpath)
3. After this line add the following lines:
autoload -U compinit

On MAC I used the following instead:
autoload -U compaudit compinit

4. You may need to delete files that start with .zcompdump in your home directory.
5. Start a new shell, and it should work.

If you are using oh-my-zsh, it's a bit easier:
1. Create your directory under ~/.oh-my-zsh/plugins
For example ~/.oh-my-zsh/plugins/myautocomplete
2. Place this file in this directory.
3. Edit ~/.zshrc, find "plugins" and add "myautocomplete" to the list.
4. Start a new shell.

No comments: