zsh_completions.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. package cobra
  2. import (
  3. "bytes"
  4. "fmt"
  5. "io"
  6. "os"
  7. )
  8. // GenZshCompletionFile generates zsh completion file including descriptions.
  9. func (c *Command) GenZshCompletionFile(filename string) error {
  10. return c.genZshCompletionFile(filename, true)
  11. }
  12. // GenZshCompletion generates zsh completion file including descriptions
  13. // and writes it to the passed writer.
  14. func (c *Command) GenZshCompletion(w io.Writer) error {
  15. return c.genZshCompletion(w, true)
  16. }
  17. // GenZshCompletionFileNoDesc generates zsh completion file without descriptions.
  18. func (c *Command) GenZshCompletionFileNoDesc(filename string) error {
  19. return c.genZshCompletionFile(filename, false)
  20. }
  21. // GenZshCompletionNoDesc generates zsh completion file without descriptions
  22. // and writes it to the passed writer.
  23. func (c *Command) GenZshCompletionNoDesc(w io.Writer) error {
  24. return c.genZshCompletion(w, false)
  25. }
  26. // MarkZshCompPositionalArgumentFile only worked for zsh and its behavior was
  27. // not consistent with Bash completion. It has therefore been disabled.
  28. // Instead, when no other completion is specified, file completion is done by
  29. // default for every argument. One can disable file completion on a per-argument
  30. // basis by using ValidArgsFunction and ShellCompDirectiveNoFileComp.
  31. // To achieve file extension filtering, one can use ValidArgsFunction and
  32. // ShellCompDirectiveFilterFileExt.
  33. //
  34. // Deprecated
  35. func (c *Command) MarkZshCompPositionalArgumentFile(argPosition int, patterns ...string) error {
  36. return nil
  37. }
  38. // MarkZshCompPositionalArgumentWords only worked for zsh. It has therefore
  39. // been disabled.
  40. // To achieve the same behavior across all shells, one can use
  41. // ValidArgs (for the first argument only) or ValidArgsFunction for
  42. // any argument (can include the first one also).
  43. //
  44. // Deprecated
  45. func (c *Command) MarkZshCompPositionalArgumentWords(argPosition int, words ...string) error {
  46. return nil
  47. }
  48. func (c *Command) genZshCompletionFile(filename string, includeDesc bool) error {
  49. outFile, err := os.Create(filename)
  50. if err != nil {
  51. return err
  52. }
  53. defer outFile.Close()
  54. return c.genZshCompletion(outFile, includeDesc)
  55. }
  56. func (c *Command) genZshCompletion(w io.Writer, includeDesc bool) error {
  57. buf := new(bytes.Buffer)
  58. genZshComp(buf, c.Name(), includeDesc)
  59. _, err := buf.WriteTo(w)
  60. return err
  61. }
  62. func genZshComp(buf io.StringWriter, name string, includeDesc bool) {
  63. compCmd := ShellCompRequestCmd
  64. if !includeDesc {
  65. compCmd = ShellCompNoDescRequestCmd
  66. }
  67. WriteStringAndCheck(buf, fmt.Sprintf(`#compdef _%[1]s %[1]s
  68. # zsh completion for %-36[1]s -*- shell-script -*-
  69. __%[1]s_debug()
  70. {
  71. local file="$BASH_COMP_DEBUG_FILE"
  72. if [[ -n ${file} ]]; then
  73. echo "$*" >> "${file}"
  74. fi
  75. }
  76. _%[1]s()
  77. {
  78. local shellCompDirectiveError=%[3]d
  79. local shellCompDirectiveNoSpace=%[4]d
  80. local shellCompDirectiveNoFileComp=%[5]d
  81. local shellCompDirectiveFilterFileExt=%[6]d
  82. local shellCompDirectiveFilterDirs=%[7]d
  83. local lastParam lastChar flagPrefix requestComp out directive comp lastComp noSpace
  84. local -a completions
  85. __%[1]s_debug "\n========= starting completion logic =========="
  86. __%[1]s_debug "CURRENT: ${CURRENT}, words[*]: ${words[*]}"
  87. # The user could have moved the cursor backwards on the command-line.
  88. # We need to trigger completion from the $CURRENT location, so we need
  89. # to truncate the command-line ($words) up to the $CURRENT location.
  90. # (We cannot use $CURSOR as its value does not work when a command is an alias.)
  91. words=("${=words[1,CURRENT]}")
  92. __%[1]s_debug "Truncated words[*]: ${words[*]},"
  93. lastParam=${words[-1]}
  94. lastChar=${lastParam[-1]}
  95. __%[1]s_debug "lastParam: ${lastParam}, lastChar: ${lastChar}"
  96. # For zsh, when completing a flag with an = (e.g., %[1]s -n=<TAB>)
  97. # completions must be prefixed with the flag
  98. setopt local_options BASH_REMATCH
  99. if [[ "${lastParam}" =~ '-.*=' ]]; then
  100. # We are dealing with a flag with an =
  101. flagPrefix="-P ${BASH_REMATCH}"
  102. fi
  103. # Prepare the command to obtain completions
  104. requestComp="${words[1]} %[2]s ${words[2,-1]}"
  105. if [ "${lastChar}" = "" ]; then
  106. # If the last parameter is complete (there is a space following it)
  107. # We add an extra empty parameter so we can indicate this to the go completion code.
  108. __%[1]s_debug "Adding extra empty parameter"
  109. requestComp="${requestComp} \"\""
  110. fi
  111. __%[1]s_debug "About to call: eval ${requestComp}"
  112. # Use eval to handle any environment variables and such
  113. out=$(eval ${requestComp} 2>/dev/null)
  114. __%[1]s_debug "completion output: ${out}"
  115. # Extract the directive integer following a : from the last line
  116. local lastLine
  117. while IFS='\n' read -r line; do
  118. lastLine=${line}
  119. done < <(printf "%%s\n" "${out[@]}")
  120. __%[1]s_debug "last line: ${lastLine}"
  121. if [ "${lastLine[1]}" = : ]; then
  122. directive=${lastLine[2,-1]}
  123. # Remove the directive including the : and the newline
  124. local suffix
  125. (( suffix=${#lastLine}+2))
  126. out=${out[1,-$suffix]}
  127. else
  128. # There is no directive specified. Leave $out as is.
  129. __%[1]s_debug "No directive found. Setting do default"
  130. directive=0
  131. fi
  132. __%[1]s_debug "directive: ${directive}"
  133. __%[1]s_debug "completions: ${out}"
  134. __%[1]s_debug "flagPrefix: ${flagPrefix}"
  135. if [ $((directive & shellCompDirectiveError)) -ne 0 ]; then
  136. __%[1]s_debug "Completion received error. Ignoring completions."
  137. return
  138. fi
  139. while IFS='\n' read -r comp; do
  140. if [ -n "$comp" ]; then
  141. # If requested, completions are returned with a description.
  142. # The description is preceded by a TAB character.
  143. # For zsh's _describe, we need to use a : instead of a TAB.
  144. # We first need to escape any : as part of the completion itself.
  145. comp=${comp//:/\\:}
  146. local tab=$(printf '\t')
  147. comp=${comp//$tab/:}
  148. __%[1]s_debug "Adding completion: ${comp}"
  149. completions+=${comp}
  150. lastComp=$comp
  151. fi
  152. done < <(printf "%%s\n" "${out[@]}")
  153. if [ $((directive & shellCompDirectiveNoSpace)) -ne 0 ]; then
  154. __%[1]s_debug "Activating nospace."
  155. noSpace="-S ''"
  156. fi
  157. if [ $((directive & shellCompDirectiveFilterFileExt)) -ne 0 ]; then
  158. # File extension filtering
  159. local filteringCmd
  160. filteringCmd='_files'
  161. for filter in ${completions[@]}; do
  162. if [ ${filter[1]} != '*' ]; then
  163. # zsh requires a glob pattern to do file filtering
  164. filter="\*.$filter"
  165. fi
  166. filteringCmd+=" -g $filter"
  167. done
  168. filteringCmd+=" ${flagPrefix}"
  169. __%[1]s_debug "File filtering command: $filteringCmd"
  170. _arguments '*:filename:'"$filteringCmd"
  171. elif [ $((directive & shellCompDirectiveFilterDirs)) -ne 0 ]; then
  172. # File completion for directories only
  173. local subDir
  174. subdir="${completions[1]}"
  175. if [ -n "$subdir" ]; then
  176. __%[1]s_debug "Listing directories in $subdir"
  177. pushd "${subdir}" >/dev/null 2>&1
  178. else
  179. __%[1]s_debug "Listing directories in ."
  180. fi
  181. local result
  182. _arguments '*:dirname:_files -/'" ${flagPrefix}"
  183. result=$?
  184. if [ -n "$subdir" ]; then
  185. popd >/dev/null 2>&1
  186. fi
  187. return $result
  188. else
  189. __%[1]s_debug "Calling _describe"
  190. if eval _describe "completions" completions $flagPrefix $noSpace; then
  191. __%[1]s_debug "_describe found some completions"
  192. # Return the success of having called _describe
  193. return 0
  194. else
  195. __%[1]s_debug "_describe did not find completions."
  196. __%[1]s_debug "Checking if we should do file completion."
  197. if [ $((directive & shellCompDirectiveNoFileComp)) -ne 0 ]; then
  198. __%[1]s_debug "deactivating file completion"
  199. # We must return an error code here to let zsh know that there were no
  200. # completions found by _describe; this is what will trigger other
  201. # matching algorithms to attempt to find completions.
  202. # For example zsh can match letters in the middle of words.
  203. return 1
  204. else
  205. # Perform file completion
  206. __%[1]s_debug "Activating file completion"
  207. # We must return the result of this command, so it must be the
  208. # last command, or else we must store its result to return it.
  209. _arguments '*:filename:_files'" ${flagPrefix}"
  210. fi
  211. fi
  212. fi
  213. }
  214. # don't run the completion function when being source-ed or eval-ed
  215. if [ "$funcstack[1]" = "_%[1]s" ]; then
  216. _%[1]s
  217. fi
  218. `, name, compCmd,
  219. ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp,
  220. ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs))
  221. }