Compare commits

...

32 Commits

Author SHA1 Message Date
F.B. d8f4a714cd
Merge 5359bbf0e7 into fd4a16961f 2026-03-27 11:08:17 +00:00
Shohei YOSHIDA fd4a16961f
Merge pull request #1247 from zsh-users/refactor_mix
Refactor mix completion
2026-03-27 00:00:59 +09:00
Shohei YOSHIDA 012017166b
Merge pull request #1243 from zsh-users/ctest_cpack
Add ctest and cpack completions
2026-03-27 00:00:18 +09:00
Shohei YOSHIDA 109a9c809d
Merge pull request #1250 from zsh-users/refactor_mvn
Refactor mvn completion
2026-03-26 23:58:22 +09:00
Shohei YOSHIDA 64487c7f40
Merge pull request #1249 from zsh-users/refactor_golang
Use __golang prefix instead of __go prefix
2026-03-26 23:57:30 +09:00
Shohei YOSHIDA 47d0792461
Merge pull request #1251 from zsh-users/refactor_inxi
Use builtin generating sequential number instead of external commands
2026-03-26 23:55:18 +09:00
Shohei YOSHIDA 748efd8af7
Use builtin generating sequential number instead of external commands
`seq` is not installed on some BSD platforms by default.
2026-03-26 17:30:13 +09:00
Shohei YOSHIDA 519f6d6cee
Refactor mvn completion
- use local variables for cache variables
- use if for conditional executions
2026-03-26 15:14:58 +09:00
Shohei YOSHIDA 748d11083a
Use __golang prefix instead of __go prefix
Because __go_ is used in zsh old golang completions and they could
conflict with functions in _golang.
2026-03-26 14:04:23 +09:00
Shohei YOSHIDA a5d34d3aef
Improve portability 2026-03-26 13:52:05 +09:00
Shohei YOSHIDA b1ffb771c9
Merge pull request #1248 from zsh-users/cache-expiration-date
Fix cache expiration according to comment
2026-03-26 11:26:39 +09:00
Shohei YOSHIDA 77ec5ecd6b
Fix cache expiration according to comment
'mh+1' means 1 hour
2026-03-25 23:28:17 +09:00
Shohei YOSHIDA 118705c01a
implement minimum Phoenix tasks completions 2026-03-25 18:29:36 +09:00
Shohei YOSHIDA 6879291030
implement cache 2026-03-25 15:10:11 +09:00
Shohei YOSHIDA e118561a37
use dynamic completion but it seems we should use cache 2026-03-24 18:02:45 +09:00
Shohei YOSHIDA 2fdd13ab92
Refactor _mix completion 2026-03-24 17:45:58 +09:00
Shohei YOSHIDA 5993fc38e7
Add cpack completion 2026-03-22 18:22:26 +09:00
Shohei YOSHIDA e4006dea72
add ctest 2026-03-22 18:22:23 +09:00
fishBone000 5359bbf0e7
Forgot to change ToC 2024-09-18 06:07:34 +00:00
fishBone000 a3e89f7c56
Reread to make the doc more fluent 2024-09-18 06:06:48 +00:00
fishBone000 cf57a3266c
Try to fix ToC 2024-09-18 04:52:48 +00:00
fishBone000 41896a6013
Finish most TODOs 2024-09-18 04:43:01 +00:00
fishBone000 0d8667bb6a
Fix Table of Contents
I forgot to change it
2024-09-18 04:17:10 +00:00
fishBone000 79c6d1715f
Finish Other resources 2024-09-18 04:15:31 +00:00
fishBone000 f5e58a5ca7
Finish Tips 2024-09-18 04:12:15 +00:00
fishBone000 6c8cd1b111
Finish Gotchas (things to look out for) 2024-09-18 04:01:09 +00:00
fishBone000 eb711299c5
Finish Testing & debugging 2024-09-18 03:53:13 +00:00
fishBone000 d71c3c84cc
Finish Writing your own completion code 2024-09-18 03:43:52 +00:00
fishBone000 c3f1f7748d
Finish Getting started 2024-09-17 07:40:59 +00:00
fishBone000 45fd6f398a
Fix document file extension 2024-09-17 07:15:24 +00:00
fishBone000 26b538f012
Finish Intro 2024-09-17 07:13:14 +00:00
fishBone000 fd43209f3a
Beginning of zh_cn translation 2024-09-17 06:37:21 +00:00
8 changed files with 1814 additions and 255 deletions

156
src/_cpack Normal file
View File

@ -0,0 +1,156 @@
#compdef cpack
# ------------------------------------------------------------------------------
# Copyright (c) 2026 Github zsh-users - https://github.com/zsh-users
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
# ------------------------------------------------------------------------------
# Description
# -----------
#
# Completion script for cpack 4.3.0 (https://kitware.com/cmake)
#
# ------------------------------------------------------------------------------
# Authors
# -------
#
# * Shohei Yoshida (https://github.com/syohex) <syohex@gmail.com>
#
# ------------------------------------------------------------------------------
_cpack() {
local ret=1
_arguments \
'-G[Override/define CPACK_GENERATOR]:generator:_cpack_generators' \
'-C[Specify the project configurations]:configuration:(Debug Release)' \
'*-D[Set a CPack variable]:var_val' \
'--config[Specify the config file]:file:_files' \
'(-V --verbose)'{-V,--verbose}'[Enable verbose output]' \
'--trace[Put underlying cmake scripts in trace mode]' \
'--trace-expand[Put underlying cmake scripts in expanded trace mode]' \
'--debug[Enable debug output]' \
'-P[Override/define CPACK_PACKAGE_NAME]:package_name' \
'-R[Override/define CPACK_PACKAGE_VERSION]:package_version' \
'-B[Override/define CPACK_PACKAGE_DIRECTORY]:package_directory:_files -/' \
'--vendor[Override/define CPACK_PACKAGE_VENDOR]:vendor' \
'--preset[Read arguments from a package preset]' \
'--list-presets[List available package preset]' \
'(- *)'{--version,-version}=-'[Print version number and exit]::format:(json-v1)' \
'(- *)--help[Print usage information and exit]' \
'(- *)--help-full[Print all help manuals and exit]' \
'(- *)--help-manual[Print one help manual and exit]:manual:_cpack_help_manuals' \
'(- *)--help-manual-list[List help manuals available and exit]' \
'(- *)--help-command[Print help for one command and exit]:command:_cpack_help_commands' \
'(- *)--help-command-list[List commands with help available and exit]' \
'(- *)--help-commands[Print cmake-commands manual and exit]' \
'(- *)--help-module[Print help for one module and exit]:module:_cpack_help_modules' \
'(- *)--help-module-list[List modules with help available and exit]' \
'(- *)--help-modules[Print cmake-modules manual and exit]' \
'(- *)--help-policy[Print help for one policy and exit]:policy:_cpack_help_policies' \
'(- *)--help-policy-list[List policies with help available and exit]' \
'(- *)--help-policies[Print cmake-policies manual and exit]' \
'(- *)--help-property[Print help for one property and exit]:property:_cpack_help_properties' \
'(- *)--help-property-list[List properties with help available and exit]' \
'(- *)--help-properties[Print cmake-properties manual and exit]' \
'(- *)--help-variable[Print help for one variable and exit]:variable:_cpack_help_variables' \
'(- *)--help-variable-list[List variables with help available and exit]' \
'(- *)--help-variables[Print cmake-variables manual and exit]' \
&& ret=0
return ret
}
_cpack_generators() {
local -a generators=(
"7Z:[7-Zip file format with default compression algorithm]"
"7Z_BZ2:[7-Zip file format with BZip2 compression]"
"7Z_DEFLATE:[7-Zip file format with Deflate compression]"
"7Z_LZMA:[7-Zip file format with LZMA compression]"
"7Z_LZMA2:[7-Zip file format with LZMA2 compression]"
"7Z_PPMD:[7-Zip file format with PPMd compression]"
"7Z_STORE:[7-Zip file format without compression]"
"7Z_ZSTD:[7-Zip file format with Zstandard compression]"
"AppImage:[AppImage packages]"
"DEB:[Debian packages]"
"External:[CPack External packages]"
"IFW:[Qt Installer Framework]"
"INNOSETUP:[Inno Setup packages]"
"NSIS:[Null Soft Installer]"
"NSIS64:[Null Soft Installer (64-bit)]"
"NuGet:[NuGet packages]"
"RPM:[RPM packages]"
"STGZ:[Self extracting Tar GZip compression]"
"TAR:[Tar no compression]"
"TBZ2:[Tar BZip2 compression]"
"TGZ:[Tar GZip compression]"
"TXZ:[Tar XZ compression]"
"TZ:[Tar Compress compression]"
"TZST:[Tar Zstandard compression]"
"ZIP:[ZIP file format with default compression algorithm]"
"ZIP_BZ2:[ZIP file format with BZip2 compression]"
"ZIP_DEFLATE:[ZIP file format with Deflate compression]"
"ZIP_LZMA:[ZIP file format with LZMA compression]"
"ZIP_LZMA2:[ZIP file format with LZMA2 compression]"
"ZIP_STORE:[ZIP file format without compression]"
"ZIP_ZSTD:[ZIP file format with Zstandard compression]"
)
_describe -t 'generators' generator generators
}
_cpack_help_manuals() {
local -a manuals=(${(f)"$(cpack --help-manual-list 2>/dev/null | sed 's/([0-9][0-9]*)$//' )"})
_values 'manual' $manuals
}
_cpack_help_commands() {
local -a commands=(${(f)"$(cpack --help-command-list 2>/dev/null )"})
_values 'command' $commands
}
_cpack_help_modules() {
local -a modules=(${(f)"$(cpack --help-module-list 2>/dev/null )"})
_values 'module' $modules
}
_cpack_help_policies() {
local -a policies=(${(f)"$(cpack --help-policy-list 2>/dev/null )"})
_values 'policy' $policies
}
_cpack_help_properties() {
local -a properties=(${(f)"$(cpack --help-property-list 2>/dev/null )"})
_values 'property' $properties
}
_cpack_help_variables() {
local -a variables=(${(f)"$(cpack --help-variable-list 2>/dev/null )"})
_values 'variable' $variables
}
_cpack "$@"
# Local Variables:
# mode: Shell-Script
# sh-indentation: 2
# indent-tabs-mode: nil
# sh-basic-offset: 2
# End:
# vim: ft=zsh sw=2 ts=2 et

179
src/_ctest Normal file
View File

@ -0,0 +1,179 @@
#compdef ctest
# ------------------------------------------------------------------------------
# Copyright (c) 2026 Github zsh-users - https://github.com/zsh-users
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
# ------------------------------------------------------------------------------
# Description
# -----------
#
# Completion script for ctest 4.3.0 (https://kitware.com/cmake)
#
# ------------------------------------------------------------------------------
# Authors
# -------
#
# * Shohei Yoshida (https://github.com/syohex) <syohex@gmail.com>
#
# ------------------------------------------------------------------------------
_ctest() {
local ret=1
_arguments \
'--preset=[Read arguments from a test preset]:preset' \
'--list-presets[List available test presets]' \
'(-C --build-config)'{-C,--build-config}'[Choose configuration to test]:config' \
'--progress[Enable short progress output from tests]' \
'(-V --verbose -VV --extra-verbose)'{-V,--verbose}'[Enable verbose output from tests]' \
'(-V --verbose -VV --extra-verbose)'{-VV,--extra-verbose}'[Enable more verbose output from tests]' \
'--debug[Displaying more verbose internals of CTest]' \
'--output-on-failure[Output anything outputted by the test program if the test should fail]' \
'--stop-on-failure[Stop running the tests after one has failed]' \
'--test-output-size-passed[Limit the output for passed tests to <size> bytes]:size' \
'--test-output-size-failed[Limit the output for failed tests to <size> bytes]:size' \
'--test-output-truncation[Truncate mode]:mode:(tail middle head)' \
'-F[Enable failover]' \
'(-j --parallel)'{-j,--parallel}'[Run tests in parallel]::level' \
'(-Q --quiet)'{-Q,--quiet}'[Make ctest quiet]' \
'(-O --output-log)'{-O,--output-log}'[Output to log file]:file:_files' \
'--output-junit[Output test results to JUnit XML file]:file:_files' \
'(-N --show-only)'{-N,--show-only}'[Disable actual execution of tests]::format:(format human json-v1)' \
\*{-L,--label-regex}'[Run tests with labels matching regular expression]:regex' \
\*{-R,--tests-regex}'[Run tests matching regular expression]:regex' \
\*{-E,--exclude-regex}'[Exclude tests matching regular expression]:regex' \
\*{-LE,--label-exclude}'[Exclude tests with labels matching regular expression]:regex' \
\*{-FA,--fixture-exclude-any}'[Do not automatically add any tests for fixtures matching regular expression]:regex' \
\*{-FS,--fixture-exclude-setup}'[Do not automatically add setup tests for fixtures matching regular expression]:regex' \
\*{-FC,--fixture-exclude-cleanup}'[Do not automatically add cleanup tests for fixtures matching regular expression]:regex' \
'(--dashboard)'{-D,--dashboard}'[Execute dashboard test]:dashboard' \
'*-D[Define a variable for script mode]:var' \
'(-M --test-model)'{-M,--test-model}'[Set the model for a dashboard]:model' \
'(-T --test-action)'{-T,--test-action}'[Set the dashboard action to perform]' \
'--group[Specify what build group on the dashboard]:group' \
\*{-S,--script,-Sp,--script-new-process}'[Execute a dashboard for a configuration]:script:_files' \
'(-A --add-notes)'{-A,--add-notes}'[Add a notes file with submission]:file:_files' \
'(-I --test-information)'{-I,--test-information}'[Run a specific number of tests by number]:number' \
'(-U --union)'{-U,--union}'[Take the Union of -I and -R]' \
'--rerun-failed[Run only the tests that failed previously]' \
'--tests-from-file[Run the tests listed in the given file]:file:_files' \
'--exclude-from-file[Run tests except those listed in the given file]:file:_files' \
'--repeat-until-fail[Repeat each test to run <n> times without failing]:n' \
'--repeat[Repeat each test to run <n> times]:condition-n:(until-fail: until-pass: after-timeout:)' \
'--max-width[Set the max width for a test name to output]' \
'--interactive-debug-mode[Set the interactive mode to 0 or 1]:n:(0 1)' \
'--resource-spec-file[Set the resource spec file to use]:file:_files' \
'--no-label-summary[Disable timing summary information for labels]' \
'--no-subproject-summary[Disable timing summary information for subprojects]' \
'--test-dir[Specify the directory in which to look for tests]:dir:_files -/' \
'--build-and-test[Configure, build and run a test]' \
'*--build-target[Specify a specific target to build]:target' \
'--build-nocmake[Run the build without running cmake first]' \
'--build-run-dir[Specify directory to run programs from]:dir:_files -/' \
'--build-two-config[Run CMake twice]' \
'--build-exe-dir[Specify the directory for the executable]:dir:_files -/' \
'--build-generator[Specify the generator to use]:generator' \
'--build-generator-platform[Specify the generator-specific platform]:generator_platform' \
'--build-generator-toolset[Specify the generator-specific toolset]:build_toolset' \
'--build-project[Specify the name of the project to build]:project' \
'--build-makeprogram[Specify the make program to use]:make:_files' \
'--build-noclean[Skip the make clean step]' \
'--build-config-sample[A sample executable to use to determine the configuration]:sample' \
'*--build-options[Add extra options to the build step]' \
'--test-command[The test to run with the --build-and-test-option]:command' \
'--test-timeout[The time limit in seconds]:timeout' \
'--test-load[CPU load threshold for starting new parallel tests]:threshold' \
'--tomorrow-tag[starts with next day tag]' \
'--overwrite[Overwrite CTest configuration option]' \
'--extra-submit[Submit extra files to the dashboard]:file:_files' \
'*--http-header[Append HTTP header when submitting]:header' \
'--schedule-random[Use a random order for scheduling tests]' \
'--schedule-random-seed[Override seed for random order of tests]:seed' \
'--submit-index[Submit individual dashboard tests with specific index]:index' \
'--timeout[Set the default test timeout]:timeout' \
'--stop-time[Set a time at which all tests should stop running]:time' \
'--http1.0[Submit using HTTP 1.0]' \
'--no-compress-output[Do not compress test output when submitting]' \
'--print-labels[Print all available test labels]' \
'--no-tests=[Regard no tests]:type:(error ignore)' \
'(- *)'{--help,-help,-usage,-h,-H}'[Print usage information and exit]' \
'(- *)'{--version,-version}'[Print version number and exit]' \
'(- *)--help-full[Print all help manuals and exit]' \
'(- *)--help-manual[Print one help manual and exit]:manual:_ctest_help_manuals' \
'(- *)--help-manual-list[List help manuals available and exit]' \
'(- *)--help-command[Print help for one command and exit]:command:_ctest_help_commands' \
'(- *)--help-command-list[List commands with help available and exit]' \
'(- *)--help-commands[Print cmake-commands manual and exit]' \
'(- *)--help-module[Print help for one module and exit]:module:_ctest_help_modules' \
'(- *)--help-module-list[List modules with help available and exit]' \
'(- *)--help-modules[Print cmake-modules manual and exit]' \
'(- *)--help-policy[Print help for one policy and exit]:policy:_ctest_help_policies' \
'(- *)--help-policy-list[List policies with help available and exit]' \
'(- *)--help-policies[Print cmake-policies manual and exit]' \
'(- *)--help-property[Print help for one property and exit]:property:_ctest_help_properties' \
'(- *)--help-property-list[List properties with help available and exit]' \
'(- *)--help-properties[Print cmake-properties manual and exit]' \
'(- *)--help-variable[Print help for one variable and exit]:variable:_ctest_help_variables' \
'(- *)--help-variable-list[List variables with help available and exit]' \
'(- *)--help-variables[Print cmake-variables manual and exit]' \
&& ret=0
return ret
}
_ctest_help_manuals() {
local -a manuals=(${(f)"$(ctest --help-manual-list 2>/dev/null | sed 's/([0-9][0-9]*)$//' )"})
_values 'manual' $manuals
}
_ctest_help_commands() {
local -a commands=(${(f)"$(ctest --help-command-list 2>/dev/null )"})
_values 'command' $commands
}
_ctest_help_modules() {
local -a modules=(${(f)"$(ctest --help-module-list 2>/dev/null )"})
_values 'module' $modules
}
_ctest_help_policies() {
local -a policies=(${(f)"$(ctest --help-policy-list 2>/dev/null )"})
_values 'policy' $policies
}
_ctest_help_properties() {
local -a properties=(${(f)"$(ctest --help-property-list 2>/dev/null )"})
_values 'property' $properties
}
_ctest_help_variables() {
local -a variables=(${(f)"$(ctest --help-variable-list 2>/dev/null )"})
_values 'variable' $variables
}
_ctest "$@"
# Local Variables:
# mode: Shell-Script
# sh-indentation: 2
# indent-tabs-mode: nil
# sh-basic-offset: 2
# End:
# vim: ft=zsh sw=2 ts=2 et

View File

@ -72,7 +72,7 @@ _gist() {
_gist_cache_policy() {
# rebuild if cache is more than a day old
local -a oldp
oldp=( "$1"(mh+1) )
oldp=( "$1"(m+1) )
(( $#oldp ))
}

View File

@ -44,7 +44,7 @@
#
# ------------------------------------------------------------------------------
__go_buildmodes() {
__golang_buildmodes() {
local -a buildmodes=(
'archive[non-main packages into .a files]'
'c-archive[main package, plus all packages it imports, into a C archive file]'
@ -59,7 +59,7 @@ __go_buildmodes() {
_values 'mode' $buildmodes
}
__go_runtimedebug() {
__golang_runtimedebug() {
local -a vars=(
'allocfreetrace[profile allocations]:boolean:(1 0)'
'clobberfree[clobber memory after free]:boolean:(1 0)'
@ -84,7 +84,7 @@ __go_runtimedebug() {
_values -s ',' -S '=' "runtime debug behavior" $vars[@]
}
__go_gcdebugflags() {
__golang_gcdebugflags() {
_values -s , -S = 'debug flag' \
'append[print information about append compilation]' \
'checkptr[instrument unsafe pointer conversions]:pointer conversion checks:((0\:"instrumentation disabled" 1\:"conversions involving unsafe.Pointer are instrumented" 2\:"conversions to unsafe.Pointer force heap allocation"))' \
@ -109,7 +109,7 @@ __go_gcdebugflags() {
'ssa/help[print help about SSA debugging]'
}
__go_gcflags() {
__golang_gcflags() {
_arguments \
'-%[debug non-static initializers]' \
'-c=[concurrency during compilation]:int' \
@ -131,7 +131,7 @@ __go_gcflags() {
'-buildid=[record id as the build id in the export metadata]:id' \
'-complete[compiling complete package (no C or assembly)]' \
'-cpuprofile=[write cpu profile to file]:file' \
'-d=[print debug information about items in list; try -d help]:list: __go_gcdebugflags' \
'-d=[print debug information about items in list; try -d help]:list: __golang_gcdebugflags' \
'-dwarf[generate DWARF symbols (default true)]' \
'-dwarfbasentries[use base address selection entries in DWARF (default true)]' \
'-dwarflocationlists[add location lists to DWARF in optimized mode (default true)]' \
@ -173,7 +173,7 @@ __go_gcflags() {
'-wb[enable write barrier (default true)]'
}
__go_pgo() {
__golang_pgo() {
_alternative \
"name:name:(auto off)" \
"file:file:_files"
@ -203,9 +203,9 @@ local -a commands=(
'help:get more information about a command'
)
__go_envvarvals() {
# if __go_envvarvals is called for -value-, I use the function argument to
# decide which variable to go to. if $1 is not set, then __go_envvarvals is
__golang_envvarvals() {
# if __golang_envvarvals is called for -value-, I use the function argument to
# decide which variable to go to. if $1 is not set, then __golang_envvarvals is
# called from the `go env` completion and the current word (with all after
# the first '=' removed) is the current variable.
local env_variable=${1-${words[$CURRENT]%%=*}}
@ -276,7 +276,7 @@ __go_envvarvals() {
_dispatch $service -value-,${variable#CGO_},-default-
;;
(GODEBUG)
__go_runtimedebug
__golang_runtimedebug
;;
(GOFLAGS)
# not implemented, sorry
@ -294,7 +294,7 @@ __go_envvarvals() {
esac
}
__go_packages() {
__golang_packages() {
local -a gopaths=("${(s/:/)$(go env GOPATH)}")
gopaths+=("$(go env GOROOT)")
for p in $gopaths; do
@ -312,7 +312,7 @@ __go_packages() {
fi
}
__go_fix_analyzers() {
__golang_fix_analyzers() {
local -a fix_analyzers=(
"any[replace interface{} with any]"
"buildtag[check //go:build and // +build directives]"
@ -341,7 +341,7 @@ __go_fix_analyzers() {
_values 'analyzer' $fix_analyzers
}
__go_pprof_symbolize_types() {
__golang_pprof_symbolize_types() {
local -a symbolize_types=(
"none[Do not attempt symbolization]"
"local[Examine only local binaries]"
@ -360,7 +360,7 @@ if [[ "$service" = -value-* ]]; then
if (($blacklist[(I)$env_variable])); then
return
fi
__go_envvarvals $env_variable
__golang_envvarvals $env_variable
return
fi
@ -382,16 +382,16 @@ case $state in
'-work[print temporary work directory and keep it]'
'-x[print the commands]'
'-asmflags[arguments for each go tool asm invocation]:flags'
'-buildmode[build mode to use]:mode:__go_buildmodes'
'-buildmode[build mode to use]:mode:__golang_buildmodes'
'-buildvcs[stamp binaries with version control information]:mode:(internal external auto)'
'-compiler[name of compiler to use]:name'
'-gccgoflags[arguments for gccgo]:args'
'*-gcflags=[arguments for each go tool compile invocation]:args:__go_gcflags'
'*-gcflags=[arguments for each go tool compile invocation]:args:__golang_gcflags'
'-installsuffix[suffix to add to package directory]:suffix'
'-ldflags[arguments to pass on each go tool link invocation.]:flags'
'-linkshared[link against shared libraries]'
'-overlay[read a JSON config file that provides an overlay for build operations]:file:_files -g "*.json"'
'-pgo[specify the file path of a profile for profile-guided optimization]:file_or_profile:__go_pgo'
'-pgo[specify the file path of a profile for profile-guided optimization]:file_or_profile:__golang_pgo'
'-pkgdir[install and load all packages from dir]:dir'
'-tags[list of build tags to consider satisfied]:tags'
'-trimpath[remove all file system paths from the resulting executable]'
@ -425,7 +425,7 @@ case $state in
'help:get more information about a command'
)
local -a fix_flags=(
'-fixtool=[specify fix analyzer]:analyzer:__go_fix_analyzers'
'-fixtool=[specify fix analyzer]:analyzer:__golang_fix_analyzers'
'-diff[display diffs instead of rewriting files]'
'-fixtool=[select analysis tool]:analyzer:'
'(- *)-V[print version and exit]'
@ -464,7 +464,7 @@ case $state in
'-json[emit build output in JSON suitable for automated processing]' \
${build_flags[@]} \
${mod_flags[@]} \
'*:importpaths:__go_packages'
'*:importpaths:__golang_packages'
;;
(clean)
@ -477,7 +477,7 @@ case $state in
'-fuzzcache[remove files stored in the Go build cache for fuzz testing]' \
${build_flags[@]} \
${mod_flags[@]} \
'*:importpaths:__go_packages'
'*:importpaths:__golang_packages'
;;
(doc)
@ -489,7 +489,7 @@ case $state in
'-short[one-line representation for each symbol]' \
'-src[show the full source code for the symbol]' \
'-u[show docs for unexported and exported symbols and methods]' \
'*:importpaths:__go_packages'
'*:importpaths:__golang_packages'
;;
(env)
@ -569,12 +569,12 @@ case $state in
)
local -a exclude_from_w=(GOENV)
__go_list_env_vars() {
__golang_list_env_vars() {
# the parameter expansion strops off everything after the first [
_values -s ' ' -w 'environment variable' ${goenvvars[@]%%\[*}
}
# the ^ parameter expansion appends ": __go_envvarvals" to every element of goenvvars
# the ^ parameter expansion appends ": __golang_envvarvals" to every element of goenvvars
# the :# parameter expansion removes all elements matching GOENV*
[[ $words[2] != '-w' ]] && _arguments \
'-C[change to directory before running the command]: :_files -/' \
@ -582,15 +582,15 @@ case $state in
'-changed[prints only those settings whose effective value differs from the default value]' \
'-u[unset environment variables]' \
'-w[change the default setting of environment variables]' \
'*:[show environment variable]: __go_list_env_vars' || _values \
-s ' ' -S "=" -w 'environment variable' ${^goenvvars:#GOENV*}": __go_envvarvals"
'*:[show environment variable]: __golang_list_env_vars' || _values \
-s ' ' -S "=" -w 'environment variable' ${^goenvvars:#GOENV*}": __golang_envvarvals"
;;
(fix)
_arguments \
'-C[change to directory before running the command]: :_files -/' \
$fix_flags[@] \
'*:importpaths:__go_packages'
'*:importpaths:__golang_packages'
;;
(fmt)
@ -599,7 +599,7 @@ case $state in
'-n[print commands that would be executed]' \
'-x[print commands as they are executed]' \
'-mod=[set which download mode to use]:mode:(readonly vendor)' \
'*:importpaths:__go_packages'
'*:importpaths:__golang_packages'
;;
(generate)
@ -610,7 +610,7 @@ case $state in
'-n[print the commands but do not run them]' \
'-v[print the names of packages as they are compiled]' \
${build_flags[@]} \
"*:args:{ _alternative ':importpaths:__go_packages' _files }"
"*:args:{ _alternative ':importpaths:__golang_packages' _files }"
;;
(get)
@ -620,13 +620,13 @@ case $state in
'-u[use the network to update the named packages]' \
'-tool[instructs go to add a matching tool line to go.mod for each listed package]' \
${build_flags[@]} \
'*:importpaths:__go_packages'
'*:importpaths:__golang_packages'
;;
(install)
_arguments \
${build_flags[@]} \
'*:importpaths:__go_packages'
'*:importpaths:__golang_packages'
;;
(list)
@ -642,7 +642,7 @@ case $state in
'-m[list modules instead of packages]'
${build_flags[@]}
${mod_flags[@]}
'*:importpaths:__go_packages'
'*:importpaths:__golang_packages'
)
# -u and -versions are only available if -m is present on the commandline
if (($words[(I)-m])); then
@ -684,7 +684,7 @@ case $state in
(init)
# Use go packages as module name suggestion
_arguments \
'*:module:__go_packages'
'*:module:__golang_packages'
;;
(tidy)
_arguments \
@ -705,7 +705,7 @@ case $state in
_arguments \
'-m[treats the arguments as a list of modules]' \
'-vendor[exclude tests of dependencies]' \
'*:module:__go_packages'
'*:module:__golang_packages'
;;
esac
;;
@ -716,7 +716,7 @@ case $state in
_arguments \
${build_flags[@]} \
'-exec[invoke the binary using xprog]:xporg' \
'*:importpaths:__go_packages'
'*:importpaths:__golang_packages'
;;
(telemetry)
@ -803,7 +803,7 @@ case $state in
${build_flags[@]} \
'-exec[run test binary using xprog]:xprog' \
'-o[compile test binary to named file]:file:_files' \
'*:importpaths:__go_packages'
'*:importpaths:__golang_packages'
fi
;;
@ -963,7 +963,7 @@ case $state in
(fix)
if [[ $words[2] == "help" ]]; then
__go_fix_analyzers
__golang_fix_analyzers
else
_arguments \
"*:args:{ _alternative ':subcommand:(help)' _files }"
@ -1119,7 +1119,7 @@ case $state in
'-add_comment=[free-form annotation to add to the profile]:comment' \
'-diff_base=[source of base profile for comparison]:source:_files' \
'-base[show delta from this profile]:profile' \
'-symbolize=[controls source of symbol information]:source:__go_pprof_symbolize_types' \
'-symbolize=[controls source of symbol information]:source:__golang_pprof_symbolize_types' \
'-tls_cert=[TLS client certificate file for fetchign profile and symbols]:file:_files' \
'-tls_key=[TLS private key file for fetching profile and symbols]:file:_files' \
'-tls_ca=[TLS CA certs file for fetching profile and symbols]:file:_files' \
@ -1215,7 +1215,7 @@ case $state in
'-x[prints commands as they are executed]' \
'-vettool[set a different analysis tool with alternative or additional checks]:prog:_files' \
${build_flags[@]} \
'*:importpaths:__go_packages'
'*:importpaths:__golang_packages'
;;
(work)

View File

@ -21,7 +21,7 @@ _inxi() {
local curcontext="$curcontext"
local ret=1
local colors=($(seq 0 42))
local -a colors=({0..42})
_arguments -C -s \
'(-A --audio)'{-A,--audio}"[Show Audio/sound card(s) information]" \

1121
src/_mix

File diff suppressed because it is too large Load Diff

View File

@ -266,14 +266,19 @@ _mvn_groupIds() {
[[ -z "$update_policy" ]] && zstyle ":completion:${curcontext}:" cache-policy _mvn_groupIds_caching_policy
if [[ -d $repository_location ]]; then
unset _groupIds
if ( [[ ${+_groupIds} -eq 0 ]] || _cache_invalid "mvn/repositories/${repository_location}/groupIds" ) && ! _retrieve_cache "mvn/repositories/${repository_location}/groupIds"; then
_groupIds=($repository_location/**/)
_groupIds=(${${${(u)_groupIds:h:h}#"$repository_location/"}//\//.})
[[ $#_groupIds -gt 0 ]] && _store_cache "mvn/repositories/${repository_location}/groupIds" _groupIds
local -a groupIds
local cache_key="mvn/repositories/${repository_location}/groupIds"
if ( _cache_invalid $cache_key ) && ! _retrieve_cache $cache_key; then
groupIds=($repository_location/**/)
groupIds=(${${${(u)_groupIds:h:h}#"$repository_location/"}//\//.})
if (( $#groupIds > 0 )); then
_store_cache $cache_key groupIds
fi
fi
[[ $#_groupIds -gt 0 ]] && _multi_parts $@ . _groupIds && ret=0
if (( $#groupIds > 0 )); then
_multi_parts $@ . groupIds && ret=0
fi
fi
return ret
@ -310,14 +315,19 @@ _mvn_plugin_goals() {
zstyle -s ":completion:${curcontext}:" cache-policy update_policy
[[ -z "$update_policy" ]] && zstyle ":completion:${curcontext}:" cache-policy _mvn_goals_caching_policy
unset _goals
if ( [[ ${+_goals} -eq 0 ]] || _cache_invalid "mvn/plugins/${plugin}" ) && ! _retrieve_cache "mvn/plugins/${plugin}"; then
local -a goals
local cache_key="mvn/plugins/${plugin}"
if _cache_invalid $cache_key && ! _retrieve_cache $cache_key; then
setopt localoptions extendedglob
_goals=(${(s:,,,:)${${${(f)${${${(f)${${${${(F)${(S)${(f)"$(_call_program goals $words[1] -N org.apache.maven.plugins:maven-help-plugin:2.1.1:describe -Dplugin=$plugin)"}//#$(__mvn_get_plugin_prefix $plugin):/,,,}}:#*BUILD FAILURE*}#*This plugin has*goals#:}%For more information, run \'mvn help:describe*}}//:/\\:}}}// ##/ }// Description\\: /:}})
[[ $#_goals -gt 0 ]] && _store_cache "mvn/plugins/${plugin}" _goals
if (( $#goals > 0 )); then
_store_cache "mvn/plugins/${plugin}" goals
fi
fi
[[ $#_goals -gt 0 ]] && _describe -t "goals" "${plugin} goal" _goals $@[0,-2] && ret=0
if (( $#goals > 0 )); then
_describe -t "goals" "${plugin} goal" goals $@[0,-2] && ret=0
fi
return ret
}
@ -338,44 +348,52 @@ _mvn_profiles() {
# Resolve profiles from settings.xml
if [[ -f $settings_file ]]; then
unset _profiles
local -a profiles
cache_name="mvn/profiles${settings_file:A}" # FIXME Don't use A modifier, it is only available on Zsh >= 4.3.10
if ( [[ ${+_profiles} -eq 0 ]] || _cache_invalid "$cache_name" ) && ! _retrieve_cache "$cache_name"; then
_profiles=()
if _cache_invalid "$cache_name" && ! _retrieve_cache "$cache_name"; then
profiles=()
profiles_section="${(M)${(f)$(<$settings_file)}:#*<profiles>*}"
if [[ -n "$profiles_section" ]]; then
for profile in ${(s:,,,:)${${${(S)${(S)${(S)${(S)${${profiles_section#*<profile>}%</profile>*}//<repositories>*<\/repositories>}//<pluginRepositories>*<\/pluginRepositories>}//<build>*<\/build>}//<\/id>*<id>/,,,}##*<id>}%%</id>*}}; do
[[ -z ${(M)profiles:#"$profile"*} ]] && _profiles+=("$profile"'['"in settings file"']')
[[ -z ${(M)profiles:#"$profile"*} ]] && profiles+=("$profile"'['"in settings file"']')
done
fi
[[ $#_profiles -gt 0 ]] && _store_cache "$cache_name" _profiles
if (( $#profiles > 0 )); then
_store_cache "$cache_name" profiles
fi
profs+=($_profiles)
fi
profs+=($profiles)
fi
# Resolve project profiles
if [[ -f $parent_pom_file ]]; then
unset _profiles
local -a profiles
cache_name="mvn/profiles${parent_pom_file:A}" # FIXME Don't use A modifier, it is only available on Zsh >= 4.3.10
if ( [[ ${+_profiles} -eq 0 ]] || _cache_invalid "$cache_name" ) && ! _retrieve_cache "$cache_name"; then
_profiles=()
if _cache_invalid "$cache_name" && ! _retrieve_cache "$cache_name"; then
profiles=()
setopt localoptions extendedglob
for file in ${parent_pom_file:h}/**/pom.xml~*target\/*; do # FIXME project.build.directory is not always target/
profiles_section="${(M)${(f)$(<$file)}:#*<profiles>*}"
if [[ -n "$profiles_section" ]]; then
for profile in ${(s:,,,:)${${${(S)${(S)${(S)${(S)${${profiles_section#*<profile>}%</profile>*}//<repositories>*<\/repositories>}//<pluginRepositories>*<\/pluginRepositories>}//<build>*<\/build>}//<\/id>*<id>/,,,}##*<id>}%%</id>*}}; do
[[ -z ${(M)profiles:#"$profile"*} ]] && _profiles+=("$profile"'['"in ${file#${parent_pom_file:h}\/}"']')
[[ -z ${(M)profiles:#"$profile"*} ]] && profiles+=("$profile"'['"in ${file#${parent_pom_file:h}\/}"']')
done
fi
done
[[ $#_profiles -gt 0 ]] && _store_cache "$cache_name" _profiles
if (( $#profiles > 0)); then
_store_cache "$cache_name" profiles
fi
profs+=($_profiles)
fi
profs+=($profiles)
fi
compset -P '-'; compset -P '+'; compset -P '!' # FIXME Only works for the first profile
[[ $#profs -gt 0 ]] && _values $@ 'profile' "${profs[@]}" && ret=0
if (( $profs > 0 )); then
_values $@ 'profile' "${profs[@]}" && ret=0
fi
return ret
}
@ -437,16 +455,21 @@ _mvn_plugin_goal_property_names() {
zstyle -s ":completion:${curcontext}:" cache-policy update_policy
[[ -z "$update_policy" ]] && zstyle ":completion:${curcontext}:" cache-policy _mvn_properties_caching_policy
unset _properties
if ( [[ ${+_properties} -eq 0 ]] || _cache_invalid "mvn/plugins/${plugin_colon_goal}" ) && ! _retrieve_cache "mvn/plugins/${plugin_colon_goal}"; then
local -a properties
local cache_key="mvn/plugins/${plugin_colon_goal}"
if _cache_invalid $cache_key && ! _retrieve_cache $cache_key; then
# FIXME Does not work for:
# android:apk (new line before expression)
# ear:ear (unknown cause)
_properties=(${(M)${(ps:,,,:)${${${${(pj: :)${${${(f)${"$(_call_program properties $words[1] -N org.apache.maven.plugins:maven-help-plugin:2.1.1:describe -Dplugin=${plugin_colon_goal%:*} -Dgoal=${plugin_colon_goal##*:} -Ddetail)"#*Available parameters:}%%\[INFO\]*}//# [a-z]*/,,,}##*Expression: \$\{}}//\}[[:space:]]##/:}//[[:space:]]##/ }//[[:space:]]#,,,[[:space:]]#/,,,}}:#[a-zA-Z]##:*})
[[ $#_properties -gt 0 ]] && _store_cache "mvn/plugins/${plugin_colon_goal}" _properties
properties=(${(M)${(ps:,,,:)${${${${(pj: :)${${${(f)${"$(_call_program properties $words[1] -N org.apache.maven.plugins:maven-help-plugin:2.1.1:describe -Dplugin=${plugin_colon_goal%:*} -Dgoal=${plugin_colon_goal##*:} -Ddetail)"#*Available parameters:}%%\[INFO\]*}//# [a-z]*/,,,}##*Expression: \$\{}}//\}[[:space:]]##/:}//[[:space:]]##/ }//[[:space:]]#,,,[[:space:]]#/,,,}}:#[a-zA-Z]##:*})
if (( $#properties > 0 )); then
_store_cache $cache_key properties
fi
fi
[[ $#_properties -gt 0 ]] && _describe -t "${plugin_colon_goal//:/-}-property-names" "${plugin_colon_goal} property name" _properties $@[0,-2] && ret=0
if (( $#properties > 0 )); then
_describe -t "${plugin_colon_goal//:/-}-property-names" "${plugin_colon_goal} property name" properties $@[0,-2] && ret=0
fi
return ret
}

View File

@ -0,0 +1,454 @@
* 目录
- [[#介绍][介绍]]
- [[#开始][开始]]
- [[#让zsh知道用哪个函数补全命令][让zsh知道用哪个函数补全命令]]
- [[#补全gnu格式命令][补全gnu格式命令]]
- [[#从其它命令复制补全][从其它命令复制补全]]
- [[#编写你自己的补全代码][编写你自己的补全代码]]
- [[#工具函数][工具函数]]
- [[#用_describe编写简单的补全函数][用_describe编写简单的补全函数]]
- [[#用_alternative编写补全函数][用_alternative编写补全函数]]
- [[#用_arguments编写补全函数][用_arguments编写补全函数]]
- [[#用_regex_arguments和_regex_words编写补全函数][用_regex_arguments和_regex_words编写补全函数]]
- [[#用_values_sep_parts和_multi_parts实现复杂补全][用_values、_sep_parts和_multi_parts实现复杂补全]]
- [[#用compadd直接添加补全词][用compadd直接添加补全词]]
- [[#测试与debug][测试与debug]]
- [[#踩坑了吧-需要小心的东西][踩坑了吧 (需要小心的东西)]]
- [[#小贴士][小贴士]]
- [[#其它资源][其它资源]]
> 译注:本文可能有不通顺的地方,或者采用的词汇不是很正确。
> 如果你有更好的主意欢迎提交PR。
* 介绍
Zsh官方的补全函数文档令人费解而且也没提供多少示例。
写这份文档的当下我已经在网上找到了其它几份教程,但是那些教程只涉及了补全系统的一小部分。
这份文档目的在于补全网上其它地方没涵盖的部分,同时附带示例,这样读者就可以学会如何写更高级的补全函数。
我不会展开每一细节,但给你提供的内容和示例足以从零开始。
如果你需要了解更多细节,你可以自行查询[[https://zsh.sourceforge.net/Doc/Release/Completion-System.html#Completion-System][官方文档]]。
还请公开你所创作的任何脚本比如fork这个仓库然后[[id:64bcd501-b0f0-48c7-b8e2-07af708b95ec][pr]])。
此外如果你有任何更多补充内容或对此教程的改进,欢迎做贡献。
* 开始
** 让zsh知道用哪个函数补全命令
补全命令用的补全函数储存于名字以下划线“_”起始的文件这些文件应存于$fpath变量所列出的某目录中。
你可以将下面的代码写入你的~/.zshrc以在$fpath中新增目录
#+BEGIN_SRC sh
fpath=(~/newdir $fpath)
#+END_SRC
一个补全函数文件的第一行长这个样:
#+BEGIN_SRC sh
#compdef foobar
#+END_SRC
这行代码表示这个文件含有补全foobar命令的代码。
多数情况下第一行都采用这个格式,但你也可以用同一个文件补全多个不同的函数。
查阅[[https://zsh.sourceforge.net/Doc/Release/Completion-System.html#Autoloaded-files][官方文档]]以了解更多细节。
你也可以直接使用compdef命令(比如在你的~/.zshrc文件里)来告诉zsh用哪个函数补全命令
#+BEGIN_SRC sh
> compdef _function foobar
#+END_SRC
或者对多个命令使用同一种补全:
#+BEGIN_SRC sh
> compdef _function foobar goocar hoodar
#+END_SRC
如果你想提供参数的话:
#+BEGIN_SRC sh
> compdef '_function arg1 arg2' foobar
#+END_SRC
查阅[[https://zsh.sourceforge.net/Doc/Release/Completion-System.html#Functions-4][官方文档]]以了解更多细节。
** 补全gnu格式命令
很多[[https://www.gnu.org/][gnu]]命令以标准化的方式列出选项描述(使用--help选项时
对于这些命令你可以使用_gnu_generic函数自动创建补全比如这样
#+BEGIN_SRC sh
> compdef _gnu_generic foobar
#+END_SRC
或者对多个不同命令使用_gnu_generic
#+BEGIN_SRC sh
> compdef _gnu_generic foobar goocar hoodar
#+END_SRC
你可以把这行代码放进~/.zshrc文件里。
** 从其它命令复制补全
如果你想要让一个命令比如cmd1和另一个已有补全的命令比如cmd2)拥有相同的补全,你可以:
#+BEGIN_SRC sh
> compdef cmd1=cmd2
#+END_SRC
比如当你给一个命令创建了一个助记alias的时候会很有帮助。
* 编写你自己的补全代码
你可以通过阅读已有的补全函数来开始入门。
在我的Linux系统上这些补全函数在/usr/share/zsh/functions/Completion/Unix、
/usr/share/zsh/functions/Completion/Linux和一些其它子目录下。
你会注意到这些文件频繁使用_arguments函数。
该函数是一个工具函数,可用于编写简单的补全函数。
_arguments函数是一个compadd内置函数的包装函数。
compadd内置函数是一个核心函数用于向命令行加入补全词并控制其行为。
不过多数情况下你不需要使用compadd因为有很多更易于使用的工具函数如_arguments和_describe。
对于非常基础的补全_describe函数已经够用了。
** 工具函数
下面是一个工具函数列表,你或许会用到它们。
工具函数的完整列表及使用方法在[[https://zsh.sourceforge.net/Doc/Release/Completion-System.html#Completion-Functions][]]可供查阅。
这些函数的使用示例在下一节给出。
> 译注从这里开始会出现一些术语如定义specification、描述description、动作action、词汇word等。
> 初次阅读可能会觉得比较困难,尤其是下面的工具函数表格,稍后教程开始一一讲解并给出示例的时候就好懂多了。
> 定义指的是对补全规则的定义,如`_describe 定义`。
> 描述当然指的是对命令行选项和参数的用户友好描述,补全时会显示在屏幕上,如:'-o 输出文件'
> 词汇指的是如同'word'、'-o'、'--help'、'start'等连续的一小段字符串
> 动作指的是匹配成功后执行的操作,比如执行某函数生成补全,或直接补全等等。
> 选项option和参数指给命令提供的选项和参数如`cp -r src dst`中,`-r`为选项,`src`和`dst`为参数。有些选项带参,如`tar -f file ...`中`-f`选项带`file`参数。
> 候选candidate指可能的补全结果如补全`tar -f`时目录下所有文件会被作为候选,补全`systemctl`时`start`、`stop`、`list-units`等指令会被作为候选。
> 还请不要感到灰心,读下去就是了。
*** 用于大部分补全的主要工具函数
| _alternative | 从其它工具函数或shell代码生成补全候选。 |
| _arguments | 指定如何补全一命令的各选项和参数命令选项风格为unix风格。 |
| _describe | 创建由带描述的词汇但不包含动作组成的简单补全。比_arguments更简单。 |
| _gnu_generic | 为带有“--help”选项的命令补全选项。 |
| _regex_arguments | 创建一先用regex表达式匹配命令行参数再执行动作/补全的函数。 |
*** 对单个词汇进行复杂补全的工具函数
| _values | 补全任意词汇(值)及其参数,或逗号分隔的词汇与参数列表。 |
| _combination | 补全值的组合,比如域名和用户名的二元组。 |
| _multi_parts | 对词汇的由符号分隔的多个部分分别补全,比如补全路径:/u/i/sy -> /usr/include/sys |
| _sep_parts | 类似_multi_parts但在补全的不同部分中允许不同的分隔符。 |
| _sequence | 包装另一补全函数,并补全由该函数生成的匹配列表。 |
*** 用于补全特定对象种类的函数
| _path_files | 补全文件目录。用多个选项控制行为。 |
| _files | 使用所有选项调用_path_files除了-g和-/。这些选项取决于file-patterns风格设置。 |
| _net_interfaces | 补全网络接口名称。 |
| _users | 补全用户名 |
| _groups | 补全组名 |
| _options | 补全shell选项名。 |
| _parameters | 补全shell参数/变量名(可用模式匹配限制要补全的参数/变量名)。 |
*** 处理已缓存的补全的函数
如果你有大量的补全,你可以将补全保存于一个缓存文件以快速加载。
| _cache_invalid | 指明补全缓存是否需要重新构建rebuild缓存由标识符指定 |
| _retrieve_cache | 从缓存文件获取补全信息 |
| _store_cache | 储存缓存于缓存文件,缓存由标识符指定 |
*** 其它函数
| _message | 当无补全可生成时显示帮助信息。 |
| _regex_words | 为_regex_arguments命令生成参数。比手写参数更简单。 |
| _guard | 检查被补全的词汇用于_arguments和类似函数的定义的ACTION中。 |
*** 动作Actions
许多工具函数如_arguments、_regex_arguments、_alternative和_values在选项/参数末尾有一个action。
这个action指定如何补全对应的参数。
这些action可以是如下形式之一
| ( ) | 需要提供参数但未生成任何匹配 |
| (ITEM1 ITEM2) | 匹配列表 |
| ((ITEM1\:'DESC1' ITEM2\:'DESC2')) | 匹配列表,带有描述。引号必须和整个定义所使用的引号不同。 |
| ->STRING | 将$state设为STRING然后继续可在调用工具函数后用case语句检查$state的值 |
| FUNCTION | 生成匹配或完成其它操作的函数的函数名比如_files或_message |
| {EVAL-STRING} | 把字符串当作shell代码执行evaluate。可用于带参调用工具函数如_values或_describe |
| =ACTION | 在补全命令行中插入占位词汇不改变补全点。 |
并非所有的action种类都可用于使用action的工具函数。比如->STRING类不可用于_regex_arguments或_alternative函数。
** 用_describe编写简单的补全函数
_describe函数可以用于简单的补全此类补全的选项/参数的位置与顺序无关紧要。
你只需用一个数组参数储存这些选项和其描述然后将数组参数的名作为参数传入_describe。
下面的示例创建补全候选c和d注意代码文件名应为_cmd并且文件存于$fpath所列出的目录之下
#+BEGIN_SRC sh
#compdef cmd
local -a subcmds
subcmds=('c:c命令描述' 'd:d命令描述')
_describe 'command' subcmds
#+END_SRC
你可以像下面一样使用由双横杠分隔的列表,但注意实操时会混合匹配结果,所以不应该用于不同种类的补全候选:
#+BEGIN_SRC sh
local -a subcmds topics
subcmds=('c:c命令描述' 'd:d命令的描述')
topics=('e:e帮助主题的描述' 'f:f帮助主题的描述')
_describe 'command' subcmds -- topics
#+END_SRC
如果两个候选有相同的描述_describe把它们集于一行并确保描述严格按列对齐。
_describe函数可用在_alternative、_arguments或_regex_arguments的ACTION中。
在这种情况下你需要用括号将_describe和参数包起来比如'TAG:DESCRIPTION:{_describe 'values' options}'
** 用_alternative编写补全函数
如同_describe该函数进行简单补全其选项/参数的顺序和位置并不重要。
然而与_describe的固定匹配不同_alternative可进一步调用函数生成补全候选。
此外_alternative允许混合不同种类的补全候选。
关于参数该函数接受一列定义specification每项定义的形式为“TAG:DESCRIPTION:ACTION”即“标签:描述:动作”其中TAG是一个标识补全匹配种类的特殊标签。
DESCRIPTION以标题heading的形式描述补全候选组而ACTION是先前列出的动作种类之一除了->STRING和=ACTION之外
例如:
#+BEGIN_SRC sh
_alternative 'arguments:自定义参数:(a b c)' 'files:文件名:_files'
#+END_SRC
第一个定义增加了补全候选a、b和c而第二个定义调用_files函数以补全文件目录。
我们可以用反斜杠 \ 将不同定义分成几行并给每个自定义参数加入描述文字:
#+BEGIN_SRC sh
_alternative \
'args:自定义参数:((a\:"描述a" b\:"描述b" c\:"描述c"))' \
'files:文件名:_files'
#+END_SRC
如果我们想向_files传递参数我们可以直接写在_files后面
#+BEGIN_SRC sh
_alternative \
'args:自定义参数:((a\:"描述a" b\:"描述b" c\:"描述c"))' \
'files:文件名:_files -/'
#+END_SRC
如要用变量展开创建补全列表,必须用双引号将定义括起来,
如:
#+BEGIN_SRC sh
_alternative \
"dirs:用户目录:($userdirs)" \
"pids:进程ID:($(ps -A o pid=))"
#+END_SRC
在此例子中第一个定义加入$userdirs变量中的词汇第二个定义执行'ps -A o pid='并获取pid表pid表用作补全候选。
实操中我们使用已有的_pids函数而不是像上面那样手写。
我们可以在ACTION中使用_values等其它工具函数以完成更复杂的补全
#+BEGIN_SRC sh
_alternative \
"directories:用户目录:($userdirs)" \
'options:逗号分隔选项: _values -s , letter a b c'
#+END_SRC
该示例补全$userdirs里的项目以及用逗号分隔的、含有a、b和/或c的列表。
注意_values前面的空格。空格不可省略因为_values不能接受标准compadd描述选项。
和_describe一样_alternative可用作ACTION并作为_arguments或_regex_arguments的一部分。
** 用_arguments编写补全函数
只需要调用_arguments函数一次就可以创造出非常智能的补全函数。该函数本身就是用于处理这种带有带参选项的命令的。
如同_alternative函数_arguments接受一列定义字符串参数。
这些定义字符串指定选项和任何对应的选项参数(如:-f 文件名),或命令参数。
简单的选项定义用'-OPT[DESCRIPTION]'(即'-选项[描述]'),比如:
#+BEGIN_SRC sh
_arguments '-s[排序后输出]' '--l[更多输出]' '-l[更多输出]'
#+END_SRC
选项参数可在选项描述后指定,形式用'-OPT[DESCRIPTION]:MESSAGE:ACTION'(即'-选项[描述]:消息:动作',
其中MESSAGE是待显示的信息而ACTION可以是前面的动作Actions章节提到的任何形式。
比如:
#+BEGIN_SRC sh
_arguments '-f[输入文件]:文件名:_files'
#+END_SRC
命令参数定义用'N:MESSAGE:ACTION'(即'N:消息:动作'其中N指定这是第N个命令参数而MESSAGE和ACTION都和前面的一样。
如果N被省略则其仅表示这是在所有已定义的参数之后的下一个参数。如果开头在N后面用的是双冒号则参数非必需。
比如:
#+BEGIN_SRC sh
_arguments '-s[排序后输出]' '1:第一个参数:_net_interfaces' '::可选参数:_files' ':下一个参数:(a b c)'
#+END_SRC
这里第一个参数是网络接口下一个可选参数是一个文件名最后一个参数可以是a、b或c而-s选项可以在任何位置被补全。
_arguments函数允许所有ACTION形式在前面的动作(Actions)章节列出)。
这表示你可以用动作来选择case语句分支
#+BEGIN_SRC sh
_arguments '-m[音乐文件]:文件名:->files' '-f[flags]:flag:->flags'
case "$state" in
files)
local -a music_files
music_files=( Music/**/*.{mp3,wav,flac,ogg} )
_multi_parts / music_files
;;
flags)
_values -s , 'flags' a b c d e
;;
esac
#+END_SRC
在此例子中指向音乐文件的路径被_multi_parts一步步地沿目录下降补全
而flags被_values函数按照逗号分隔列表补全。
我已经介绍了_arguments定义的基础部分你还可以定义互斥选项、重复选项和参数、以+开头的选项等。有关更多细节,查阅[[https://zsh.sourceforge.net/Doc/Release/Completion-System.html#Completion-System][官方文档]]。
同时你也可以看看本文末尾列出的教程,以及[[https://github.com/vapniks/zsh-completions/tree/master/src][src目录]]下的补全函数。
** 用_regex_arguments和_regex_words编写补全函数
如果你的命令行定义比较复杂有多个可能的参数序列那你可能需要_regex_arguments函数。
该函数也适用于有一系列跟着多个参数的关键词的情况。
_regex_arguments创建名字由第一个参数给出的补全函数。
因此你需要先调用_regex_arguments来创建补全函数然后再调用该函数比如
#+BEGIN_SRC sh
_regex_arguments _cmd OTHER_ARGS..
_cmd "$@"
#+END_SRC
OTHER_ARGS即“其它参数”是一序列用于在命令行上匹配和补全词汇的定义。
这些序列可被'|'分隔来表示备选词汇序列。
你可以用任意嵌套深度的括号来指定备选序列,但括号必须带反斜杠前缀,如\( \),或用引号括起来,如'(' ')'。
比如:
#+BEGIN_SRC sh
_regex_arguments _cmd 序列1 '|' 序列2 \( 序列2a '|' 序列2b \)
_cmd "$@"
#+END_SRC
该示例定义一个匹配序列1或序列2后跟着序列2a或序列2b的命令行。这种方式和正则表达式语法类似。
一个序列中的每个定义必须在开头包含一个/ PATTERN/ (即/ 模式/)部分,后跟着可选的':TAG:DESCRIPTION:ACTION'(即':标签:描述:动作')部分。
每个PATTERN是一个匹配一命令行词汇的正则表达式。这些模式按顺序匹配直到某个模式不匹配不匹配的模式将执行对应的ACTION动作以进行补全。
注意,一定要有一个匹配命令自身的模式。
下面有对PATTERN模式更详细的解释。
':TAG:DESCRIPTION:ACTION'的使用方法和_alternative相同只是开头多了个冒号“:”并且前面列出的所有ACTION格式都可用。
例如:
#+BEGIN_SRC sh
_regex_arguments _cmd /$'[^\0]##\0'/ \( /$'word1(a|b|c)\0'/ ':word:first word:(word1a word1b word1c)' '|'\
/$'word11(a|b|c)\0'/ ':word:first word:(word11a word11b word11c)' \( /$'word2(a|b|c)\0'/ ':word:second word:(word2a word2b word2c)'\
'|' /$'word22(a|b|c)\0'/ ':word:second word:(word22a word22b word22c)' \) \)
_cmd "$@"
#+END_SRC
TODO 英文原文和例子有出入
在这个例子中第一个词可以是word1即“词1”下同或者word11后紧跟a、b或c并且如果第一个词含有11则第二个词可以是word2后紧跟a、b或c或一个文件名。
如果感觉太复杂你也可以用更简单的_regex_words函数达到相同效果。
*** 模式
你可能注意到了上个例子中的/ PATTERN/和普通的正则表达式不太一样。
通常使用的是形如$'foo\0'的字符串参数。这是为了让\0表示成null字符而zsh内部用来分隔词汇的也是null字符。
如果不在末尾包含\0的话可能会无法匹配下一个词。如果你要把一个变量的值作为模式的一部分你可以用双括号包起来
这样变量就会展开然后再在后面加个包含null字符的字符串参数比如"$somevar"$'\0'somevar即“某变量”
表示模式用的正则表达式语法和正常的正则表达式不太一样,但我也找不到有关的文档。
不过我还是试图搞清楚了这些特殊字符的意义:
| * | 通配符 - 任何数量的字符 |
| ? | 通配符 - 单个字符 |
| # | 零个或更多的上一个字符(和一般正则表达式里的*一样) |
| ## | 一个或更多的上一个字符(和一般正则表达式里的+一样) |
*** _regex_words
_regex_words函数比_regex_arguments更简单易用。
调用_regex_words后的结果可以存在变量里。
要用_regex_words创建一个定义specification你需要提供一个标签后跟一段描述后跟一个定义不同词汇的列表。
这些定义采用'WORD:DESCRIPTION:SPEC'(即'词汇:描述:定义'的格式WORD即待补全的词DESCRIPTION是对应的描述
SPEC可以是由_regex_words创建的另一个变量以指定当前词后的下一个词汇也可以留空以表示没有更多的词。
比如:
#+BEGIN_SRC sh
_regex_words firstword '第一个词' 'word1a:词a:' 'word1b:词b:' 'word1c:词c'
#+END_SRC
该函数的返回结果将被存入$replyreply即“回复”、“回应”数组里所以我们需要在$reply变化前将结果存进另一个数组里
#+BEGIN_SRC sh
local -a firstword
_regex_words word 'The first word' 'word1a:a word:' 'word1b:b word:' 'word1c:c word'
firstword="$reply[@]"
#+END_SRC
firstword即“第一个词”。
然后我们可以把结果用在_regex_arguments里
#+BEGIN_SRC sh
_regex_arguments _cmd /$'[^\0]##\0'/ "$firstword[@]"
_cmd "$@"
#+END_SRC
注意到我给命令自身也加了模式。
这里还有个更复杂的词汇我们调用_regex_words以匹配不同词汇
#+BEGIN_SRC sh
local -a firstword firstword2 secondword secondword2
_regex_words word1 '第二个词' 'woo:鄧族' 'hoo:不关我事'
secondword=("$reply[@]")
_regex_words word2 '另一个第二个词' 'yee:汝' 'haa:很搞笑!'
secondword2=("$reply[@]")
_regex_words commands '第一个词' 'foo:做foo' 'man:yeah man' 'chu:at chu' # 译注作者在自嗨at chu除了比较像at you外没什么特殊意义
firstword=("$reply[@]")
_regex_words word4 '另一个第一个词' 'boo:吓死某人:$secondword' 'ga:嘤嘤嘤:$secondword'\
'loo:上厕所:$secondword2'
firstword2=("$reply[@]")
_regex_arguments _hello /$'[^\0]##\0'/ "${firstword[@]}" "${firstword2[@]}"
_hello "$@"
#+END_SRC
在这个例子中第一个词可以是"foo"、"man"、"chu"、"boo"、"ga"或"loo"。
如果第一个词是"boo"或"ga",那下一个词可以是"woo"或"hoo"
而如果第一个词是"loo"则第二个词可以是"yee"或"haa",其它情况下没有第二个词。
_ip函数是_regex_words的一个好用例。
** 用_values、_sep_parts和_multi_parts实现复杂补全
_values、_sep_parts和_multi_parts可以单独使用也可以作为_alternative、_arguments或_regex_arguments定义里的ACTION。可以看看下面的例子。
查阅[[https://zsh.sourceforge.net/Doc/Release/Completion-System.html#Completion-System][官方文档]]以了解更多信息。
空格分隔的mp3文件列表
#+BEGIN_SRC sh
_values 'mp3文件' ~/*.mp3
#+END_SRC
逗号分隔的会话id列表
#+BEGIN_SRC sh
_values -s , '会话id' "${(uonzf)$(ps -A o sid=)}"
#+END_SRC
补全foo@news:woo、foo@news:laa或bar@news:woo等
#+BEGIN_SRC sh
_sep_parts '(foo bar)' @ '(news ftp)' : '(woo laa)'
#+END_SRC
补全MAC地址一次补全一个字节
#+BEGIN_SRC sh
_multi_parts : '(00:11:22:33:44:55 00:23:34:45:56:67 00:23:45:56:67:78)'
#+END_SRC
** 用compadd直接添加补全词
你可以使用内置的compadd函数增加补全词以获得更细致的控制。
这个函数有各种选项控制如何显示补全以及补全时如何替换命令行上的文字。
阅读[[https://zsh.sourceforge.net/Doc/Release/Completion-System.html#Completion-System][官方文档]]以获得更多细节。
这里我只给出几个简单的示例。
向补全列表里加入若干词汇:
#+BEGIN_SRC sh
compadd foo bar blah
#+END_SRC
同上但显示注释:
#+BEGIN_SRC sh
compadd -X '一些注释' foo bar blah
#+END_SRC
同上但在补全前自动插入"what_"前缀
#+BEGIN_SRC sh
compadd -P what_ foo bar blah
#+END_SRC
同上但补全后自动插入"_todo"后缀:
#+BEGIN_SRC sh
compadd -S _todo foo bar blah
#+END_SRC
同上但在后缀后打空格时自动移除"_todo"后缀:
#+BEGIN_SRC sh
compadd -P _todo -q foo bar blah
#+END_SRC
向补全数组$wordsarraywordsarray即“词数组”加入词汇
#+BEGIN_SRC sh
compadd -a wordsarray
#+END_SRC
* 测试与debug
重新加载补全函数:
#+BEGIN_SRC sh
> unfunction _func
> autoload -U _func
#+END_SRC
这些函数会提供有用的信息。
如果默认按键没有用你可以尝试Alt+x然后再输入命令名。
| 函数 | 默认按键 | 作用 |
|-----------------+--------------------+----------------------------------------------------------------|
| _complete_help | Ctrl+x h | 在当前光标位置补全时显示有关上下文名称、标签和补全函数的信息 |
| _complete_help | Alt+2 Ctrl+x h | 同上但显示更多信息 |
| _complete_debug | Ctrl+x ? | 执行正常补全但跟踪补全系统执行的shell命令并存入一个临时文件 |
* 踩坑了吧 (需要小心的东西)
记得在补全函数的文件开头加那行#compdef
_arguments或_regex_arguments的定义中要使用正确的引号
如果定义中有变量要展开,用双引号,其它情况用单引号,
并且记得在ITEM项目描述处用不同的引号。译注见[[#动作Actions][动作Actions]]章节)
_arguments、_alternative、_regex_arguments等的定义处要在正确的地方使用正确数量的冒号“:”。
使用_regex_arguments时要记得在开头写匹配命令的模式不需要加入匹配动作action
记得在_regex_arguments的任何PATTERN模式参数后加上null字符$'\0'
* 小贴士
有时一个子命令后只会跟一个选项这时zsh会在tab在子命令后按下时自动补全。如果你想要在补全前先列出选项和描述
你可以向ACTION动作加入另一个空选项比如\:),如':TAG:DESCRIPTION:((opt1\:"opt1描述" \:))'
注意这只对在定义参数中使用ACTION的工具函数_arguments、_regex_arguments等有效。
* 其它资源
[[https://wikimatze.de/writing-zsh-completion-for-padrino/][]]是个展示_arguments函数的基本使用方法的教程短小精悍
而[[https://web.archive.org/web/20190411104837/http://www.linux-mag.com/id/1106/][]]是_arguments函数的稍稍更进阶的教程。
[[https://zsh.sourceforge.net/Doc/Release/Completion-System.html#Completion-System][]]是zshcompsys手册页man page