Manual tab completions in zsh

autocompletezsh

I would like nm[TAB] to expand to node_modules in zsh. Is this possible? How can it be done?

Ideally, it wouldn't be triggered if there is another completion available, such as an already existing nm directory, and only trigger if there is a node_modules folder that exists, and complete if it is a part of a path, such as cd nm/mo[TAB] -> cd node_modules/moment.

Best Answer

Short & sweet answer

Try my zsh-autocomplete plugin. It configures Zsh's completion system to do what you're asking for out of the box, plus lots of other useful features.

Longer, DIY answer

To get fuzzy completion in Zsh, add this to your .zshrc:

zstyle ':completion:*' matcher-list 'r:|?=**'

What this does is tell the completion system to allow any number of characters added anywhere to the string you've typed.

Next, to get the thing you want with directories, add this:

zstyle ':completion:*' accept-exact-dirs true
zstyle ':completion:*' list-suffixes true
  • accept-exact-dirs makes it so that when you have two dirs nm and node_modules and you type nm, it will never try to complete it to the latter.
  • list-suffixes tells it to try to complete every partial directory name in the path you've entered and not just the first one.

To get the accept-exact-dirs-style behavior also for all other completions, add this:

zstyle ':completion:*' accept-exact true

More info can be found here: http://zsh.sourceforge.net/Doc/Release/Completion-System.html#Standard-Styles