3

I have zsh completion for my custom script. It takes 3 optional arguments --insert, --edit, --rm and it completes files from given path:

#compdef pass

_pass() {

  local -a args

  args+=(
    '--insert[Create a new password entry]'
    '--edit[Edit a password entry]'
    '--rm[Delete a password entry]'
  )

  _arguments $args '1: :->directory'

  case $state in
  directory)
    _path_files -W $HOME/passwords -g '*(/)' -S /
    _path_files -W $HOME/passwords -g '*.gpg(:r)' -S ' '
    ;;
  esac
}

I need to add another option -P, that will also be offered for completion (when I type - and TAB), but does not offer path completion. This option should only take a string. So it should not match a path, and also it should not offer the other options if -P has been specified.

How can I add this new option to my completion script?

2

I'm presuming all of the options you mentioned are mutually exclusive with each other. If so, then your code needs very little change:

#compdef pass

_pass() {
  local -a dirargs=(
    '--insert[Create a new password entry]'
    '--edit[Edit a password entry]'
    '--rm[Delete a password entry]'
    ''
  )
  local -a args=(
    # Start a group of mutually exclusive options.
    + '(option)'
      # Specify for each option what arg should follow it.
      $^dirargs':password entry:->directory'
      '-P:string:'
  )

  _arguments $args

  case $state in
    directory)
      _path_files -W $HOME/passwords -g '*(/)' -S /
      _path_files -W $HOME/passwords -g '*.gpg(:r)' -S ' '
      ;;
  esac
}

Documentation here: http://zsh.sourceforge.net/Doc/Release/Completion-System.html#index-_005farguments

3
  • works great. Thank you. – 400 the Cat Dec 27 '20 at 5:01
  • sorry, I have discovered small problem: Now it seems the completion requires an argument, before it completes from the path $HOME/passwords. Before your change, I could also use my script without any argument, ie pass TAB would complete from the path. Now it only works when i provide an argument. – 400 the Cat Dec 29 '20 at 4:51
  • 1
    That's easily fixed: Just add ':password entry:->directory' to the (options) group. I've updated my answer with it. – Marlon Richert Dec 29 '20 at 14:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.