zsh_completions.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  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 compCount comp lastComp
  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. compCount=0
  140. while IFS='\n' read -r comp; do
  141. if [ -n "$comp" ]; then
  142. # If requested, completions are returned with a description.
  143. # The description is preceded by a TAB character.
  144. # For zsh's _describe, we need to use a : instead of a TAB.
  145. # We first need to escape any : as part of the completion itself.
  146. comp=${comp//:/\\:}
  147. local tab=$(printf '\t')
  148. comp=${comp//$tab/:}
  149. ((compCount++))
  150. __%[1]s_debug "Adding completion: ${comp}"
  151. completions+=${comp}
  152. lastComp=$comp
  153. fi
  154. done < <(printf "%%s\n" "${out[@]}")
  155. if [ $((directive & shellCompDirectiveFilterFileExt)) -ne 0 ]; then
  156. # File extension filtering
  157. local filteringCmd
  158. filteringCmd='_files'
  159. for filter in ${completions[@]}; do
  160. if [ ${filter[1]} != '*' ]; then
  161. # zsh requires a glob pattern to do file filtering
  162. filter="\*.$filter"
  163. fi
  164. filteringCmd+=" -g $filter"
  165. done
  166. filteringCmd+=" ${flagPrefix}"
  167. __%[1]s_debug "File filtering command: $filteringCmd"
  168. _arguments '*:filename:'"$filteringCmd"
  169. elif [ $((directive & shellCompDirectiveFilterDirs)) -ne 0 ]; then
  170. # File completion for directories only
  171. local subDir
  172. subdir="${completions[1]}"
  173. if [ -n "$subdir" ]; then
  174. __%[1]s_debug "Listing directories in $subdir"
  175. pushd "${subdir}" >/dev/null 2>&1
  176. else
  177. __%[1]s_debug "Listing directories in ."
  178. fi
  179. _arguments '*:dirname:_files -/'" ${flagPrefix}"
  180. if [ -n "$subdir" ]; then
  181. popd >/dev/null 2>&1
  182. fi
  183. elif [ $((directive & shellCompDirectiveNoSpace)) -ne 0 ] && [ ${compCount} -eq 1 ]; then
  184. __%[1]s_debug "Activating nospace."
  185. # We can use compadd here as there is no description when
  186. # there is only one completion.
  187. compadd -S '' "${lastComp}"
  188. elif [ ${compCount} -eq 0 ]; then
  189. if [ $((directive & shellCompDirectiveNoFileComp)) -ne 0 ]; then
  190. __%[1]s_debug "deactivating file completion"
  191. else
  192. # Perform file completion
  193. __%[1]s_debug "activating file completion"
  194. _arguments '*:filename:_files'" ${flagPrefix}"
  195. fi
  196. else
  197. _describe "completions" completions $(echo $flagPrefix)
  198. fi
  199. }
  200. # don't run the completion function when being source-ed or eval-ed
  201. if [ "$funcstack[1]" = "_%[1]s" ]; then
  202. _%[1]s
  203. fi
  204. `, name, compCmd,
  205. ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp,
  206. ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs))
  207. }