Using zsh's compdef or compctl to complete a certain directory with _hosts for all commands
Asked Answered
I

1

6

I use afuse to automount other hosts to my local file system with sshfs. Like so:

afuse -o timeout=30 -o mount_template=sshfs -C %r:/ %m -o unmount_template=fusermount -u -z %m ~/remote/

This works great, but I would like to be able to autocomplete/TAB commands using my ~/remote directory. Zsh understandably thinks ~/remote is empty, since afuse is a magical virtual FUSE file system. Once I have typed the host manually the subdirectories work fine. E.g ~/remote/host/[TAB] works fine.

Most zsh compdef tutorials focus on building a custom completer for your custom command. That is not quite what I want.

I have been trying to use compdef to override the completion of that particular directory to my hosts file (using the built-in _hosts completion function), but as far as I understand, compdef works on a per-command-basis. I want my completer to work on all commands trying to do a normal file/directory-complete on that directory.

It feels like it is so basic, that it is a one-liner, if only I knew how. How can I do this?

Implicatory answered 31/8, 2012 at 12:23 Comment(0)
W
2

Add the following to your ~.zshrc file (or paste it into the command line, to try it out):

autoload -Uz compinit && compinit
bindkey '^I' complete-word
zstyle -e ':completion:*' fake-files _fake_files
_fake_files() {
  [[ $PWD/$PREFIX$SUFFIX == ~/remote/ ]] && 
      ISUFFIX=/
  reply=( 
      ~/remote:${(j: :v)${(s: :)${(ps:\t:)${${(f)~~"$(
        < /etc/hosts
      )"}%%\#*}##[:blank:]#[^[:blank:]]#}}}
  )
}

I tried this and it works. I took the long parameter expansion from _host's source code.

Walden answered 30/6, 2020 at 12:55 Comment(1)
Great answer! I wonder if @Implicatory finds it useful?Idolum

© 2022 - 2024 — McMap. All rights reserved.