- Create a file called
_myfunc. - Put into this file:
#compdef myfunc # The line above means "This function generates # completions for myfunc." # The combination of that line, plus the file name # starting with an `_`, plus having this file's # parent dir in your `$fpath`, ensures this file # will be autoloaded when you call `compinit`. # `+X` makes sure `myfunc`'s definition will get # loaded immediately, even if you have not called # this function yet. autoload +X -Uz myfunc # Get the definition of `myfunc` in string form. local funcdef="$( type -f myfunc )" # Get the part that matches `case*esac`, then split # it on whitespace and put the resulting words in an # array. local -a words=( ${=funcdef[(r)case,(r)esac]} ) # Keep only the words that start with `(` and end # with `)`. # Even if you used the `case` syntax with only the # closing `)`s, `type -f` will show your cases with # both `(` and `)`. local -a required=( ${(M)words:#'('*')'} ) # `-s`: Allow options to `myfunc ` to be stacked, # that is, you are # allowed to specify `myfunc -rm`. # If not, remove the `-s` # option. # `*:`: Let this argument be completed in any # position. _arguments -s \ {-r,--readonly}'[description for "readonly"]' \ {-m,--mount}'[description for "mount"]' \ "*:required argument:( ${required//[()]/} )"- Replace
required argumentwith whatever you want to call your argument. - Fill out descriptions for the options.
- Replace
- Again, make sure the directory in which this file is located is in your
$fpath. - Make sure you do
autoload -Uz compinit; compinitin your.zshrcfile and make sure it runs after the dir above has been added to your$fpath. - Restart your shell with
exec zshor close your terminal window and open a new one.