diff --git a/functions/each b/functions/each new file mode 100644 index 0000000..d72a8c5 --- /dev/null +++ b/functions/each @@ -0,0 +1,35 @@ +#!/usr/bin/env zsh + +# Apply a function on each of the arguments +# +# $ each cmd arg1 arg2 +# equivalent to +# $ cmd arg1 +# $ cmd arg2 +# +# -- is used to mark end of options +# +# $ each cnd opt -- arg1 arg2 +# equivalent to +# $ cmd opt arg1 +# $ cmd opt arg2 +# +# For further usage, please consider zargs command +# +# Add the following line for auto-completion: +# _comps[each]=_precommand + +local -i iargs=${@[(ie)--]} ecmd=1 +local args= +if (( $iargs > $# )); then + iargs=1 +else + ecmd=iargs-1 + if (( $iargs > 2 )); then + args="${(q)${@[2,$ecmd]}}" + fi +fi + +for f in $@[$iargs+1,-1]; do + eval "$1 $args ${(q)f}" +done diff --git a/test/functions.zsh b/test/functions.zsh index 2f30879..fa381cd 100755 --- a/test/functions.zsh +++ b/test/functions.zsh @@ -102,6 +102,12 @@ check_cmd() } +if test_function each ; then + test echo a b; check_s $'a\nb' + test echo a -- b c; check_s $'a b\na c' + test echo -- a -- b; check_s $'a\n--\nb' +fi + if test_function jln-glob ; then eval "pre_$(functions xxx)" xxx() { pre_xxx $=1 ; shift ; jln-glob-pop $~@ }