auditory
auditory

Reputation: 177

Use colon as filename separator in zsh tab completion

I have programs which take filename arguments as

scp:path/to/file.ext
ark:/abs/path/to/file.ext

Is it possible make zsh complete filenames after some keywords followed by colon?

So far, I found how to do it in bash: add : to the COMP_WORDBREAKS variable.


Thanks to Gilles, I manage to work like this.

$ cat ~/.zshrc
...
function aftercolon() {
  if compset -P 1 '*:'; then
    _files "$expl[@]"
  else
    _files "$expl[@]"
  fi
}

autoload -Uz compinit
compinit
compdef aftercolon hello olleh

Now in commands hello and olleh, completion after : works as expected.

I think there might be better way since:

  1. I had to odd if/else since the commands also take filename without prefix.

  2. And since I have many commands take this kind of argument, I need to add names of every commands

Upvotes: 2

Views: 490

Answers (1)

Call compset -P 1 '*:' to remove everything up to the first colon, then _files to complete what comes after the colon. For example, if the file name completions don't depend on the part before the colon:

if compset -P 1 '*:'; then
  _files "$expl[@]"
else
  compadd "$expl[@]" -S : ark scp
fi

If the file name completions depend on the part before the colon, save that from $PREFIX first.

if [[ $PREFIX = *:* ]]; then
  local domain=${PREFIX%%:*}
  compset -P 1 '*:'
  case $domain in
    ark) _files "$expl[@]" -g "*.((tar|cpio)(|.gz|.xz|.bz2)|tgz|zip|rar|7z)";;
    *) _files "$expl[@]";;
  esac
else
  compadd "$expl[@]" -S : ark scp
fi

Upvotes: 1

Related Questions