fish_completions.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. package cobra
  2. import (
  3. "bytes"
  4. "fmt"
  5. "io"
  6. "os"
  7. "strings"
  8. )
  9. func genFishComp(buf io.StringWriter, name string, includeDesc bool) {
  10. // Variables should not contain a '-' or ':' character
  11. nameForVar := name
  12. nameForVar = strings.Replace(nameForVar, "-", "_", -1)
  13. nameForVar = strings.Replace(nameForVar, ":", "_", -1)
  14. compCmd := ShellCompRequestCmd
  15. if !includeDesc {
  16. compCmd = ShellCompNoDescRequestCmd
  17. }
  18. WriteStringAndCheck(buf, fmt.Sprintf("# fish completion for %-36s -*- shell-script -*-\n", name))
  19. WriteStringAndCheck(buf, fmt.Sprintf(`
  20. function __%[1]s_debug
  21. set -l file "$BASH_COMP_DEBUG_FILE"
  22. if test -n "$file"
  23. echo "$argv" >> $file
  24. end
  25. end
  26. function __%[1]s_perform_completion
  27. __%[1]s_debug "Starting __%[1]s_perform_completion"
  28. # Extract all args except the last one
  29. set -l args (commandline -opc)
  30. # Extract the last arg and escape it in case it is a space
  31. set -l lastArg (string escape -- (commandline -ct))
  32. __%[1]s_debug "args: $args"
  33. __%[1]s_debug "last arg: $lastArg"
  34. set -l requestComp "$args[1] %[3]s $args[2..-1] $lastArg"
  35. __%[1]s_debug "Calling $requestComp"
  36. set -l results (eval $requestComp 2> /dev/null)
  37. # Some programs may output extra empty lines after the directive.
  38. # Let's ignore them or else it will break completion.
  39. # Ref: https://github.com/spf13/cobra/issues/1279
  40. for line in $results[-1..1]
  41. if test (string trim -- $line) = ""
  42. # Found an empty line, remove it
  43. set results $results[1..-2]
  44. else
  45. # Found non-empty line, we have our proper output
  46. break
  47. end
  48. end
  49. set -l comps $results[1..-2]
  50. set -l directiveLine $results[-1]
  51. # For Fish, when completing a flag with an = (e.g., <program> -n=<TAB>)
  52. # completions must be prefixed with the flag
  53. set -l flagPrefix (string match -r -- '-.*=' "$lastArg")
  54. __%[1]s_debug "Comps: $comps"
  55. __%[1]s_debug "DirectiveLine: $directiveLine"
  56. __%[1]s_debug "flagPrefix: $flagPrefix"
  57. for comp in $comps
  58. printf "%%s%%s\n" "$flagPrefix" "$comp"
  59. end
  60. printf "%%s\n" "$directiveLine"
  61. end
  62. # This function does two things:
  63. # - Obtain the completions and store them in the global __%[1]s_comp_results
  64. # - Return false if file completion should be performed
  65. function __%[1]s_prepare_completions
  66. __%[1]s_debug ""
  67. __%[1]s_debug "========= starting completion logic =========="
  68. # Start fresh
  69. set --erase __%[1]s_comp_results
  70. set -l results (__%[1]s_perform_completion)
  71. __%[1]s_debug "Completion results: $results"
  72. if test -z "$results"
  73. __%[1]s_debug "No completion, probably due to a failure"
  74. # Might as well do file completion, in case it helps
  75. return 1
  76. end
  77. set -l directive (string sub --start 2 $results[-1])
  78. set --global __%[1]s_comp_results $results[1..-2]
  79. __%[1]s_debug "Completions are: $__%[1]s_comp_results"
  80. __%[1]s_debug "Directive is: $directive"
  81. set -l shellCompDirectiveError %[4]d
  82. set -l shellCompDirectiveNoSpace %[5]d
  83. set -l shellCompDirectiveNoFileComp %[6]d
  84. set -l shellCompDirectiveFilterFileExt %[7]d
  85. set -l shellCompDirectiveFilterDirs %[8]d
  86. if test -z "$directive"
  87. set directive 0
  88. end
  89. set -l compErr (math (math --scale 0 $directive / $shellCompDirectiveError) %% 2)
  90. if test $compErr -eq 1
  91. __%[1]s_debug "Received error directive: aborting."
  92. # Might as well do file completion, in case it helps
  93. return 1
  94. end
  95. set -l filefilter (math (math --scale 0 $directive / $shellCompDirectiveFilterFileExt) %% 2)
  96. set -l dirfilter (math (math --scale 0 $directive / $shellCompDirectiveFilterDirs) %% 2)
  97. if test $filefilter -eq 1; or test $dirfilter -eq 1
  98. __%[1]s_debug "File extension filtering or directory filtering not supported"
  99. # Do full file completion instead
  100. return 1
  101. end
  102. set -l nospace (math (math --scale 0 $directive / $shellCompDirectiveNoSpace) %% 2)
  103. set -l nofiles (math (math --scale 0 $directive / $shellCompDirectiveNoFileComp) %% 2)
  104. __%[1]s_debug "nospace: $nospace, nofiles: $nofiles"
  105. # If we want to prevent a space, or if file completion is NOT disabled,
  106. # we need to count the number of valid completions.
  107. # To do so, we will filter on prefix as the completions we have received
  108. # may not already be filtered so as to allow fish to match on different
  109. # criteria than the prefix.
  110. if test $nospace -ne 0; or test $nofiles -eq 0
  111. set -l prefix (commandline -t | string escape --style=regex)
  112. __%[1]s_debug "prefix: $prefix"
  113. set -l completions (string match -r -- "^$prefix.*" $__%[1]s_comp_results)
  114. set --global __%[1]s_comp_results $completions
  115. __%[1]s_debug "Filtered completions are: $__%[1]s_comp_results"
  116. # Important not to quote the variable for count to work
  117. set -l numComps (count $__%[1]s_comp_results)
  118. __%[1]s_debug "numComps: $numComps"
  119. if test $numComps -eq 1; and test $nospace -ne 0
  120. # We must first split on \t to get rid of the descriptions to be
  121. # able to check what the actual completion will be.
  122. # We don't need descriptions anyway since there is only a single
  123. # real completion which the shell will expand immediately.
  124. set -l split (string split --max 1 \t $__%[1]s_comp_results[1])
  125. # Fish won't add a space if the completion ends with any
  126. # of the following characters: @=/:.,
  127. set -l lastChar (string sub -s -1 -- $split)
  128. if not string match -r -q "[@=/:.,]" -- "$lastChar"
  129. # In other cases, to support the "nospace" directive we trick the shell
  130. # by outputting an extra, longer completion.
  131. __%[1]s_debug "Adding second completion to perform nospace directive"
  132. set --global __%[1]s_comp_results $split[1] $split[1].
  133. __%[1]s_debug "Completions are now: $__%[1]s_comp_results"
  134. end
  135. end
  136. if test $numComps -eq 0; and test $nofiles -eq 0
  137. # To be consistent with bash and zsh, we only trigger file
  138. # completion when there are no other completions
  139. __%[1]s_debug "Requesting file completion"
  140. return 1
  141. end
  142. end
  143. return 0
  144. end
  145. # Since Fish completions are only loaded once the user triggers them, we trigger them ourselves
  146. # so we can properly delete any completions provided by another script.
  147. # Only do this if the program can be found, or else fish may print some errors; besides,
  148. # the existing completions will only be loaded if the program can be found.
  149. if type -q "%[2]s"
  150. # The space after the program name is essential to trigger completion for the program
  151. # and not completion of the program name itself.
  152. # Also, we use '> /dev/null 2>&1' since '&>' is not supported in older versions of fish.
  153. complete --do-complete "%[2]s " > /dev/null 2>&1
  154. end
  155. # Remove any pre-existing completions for the program since we will be handling all of them.
  156. complete -c %[2]s -e
  157. # The call to __%[1]s_prepare_completions will setup __%[1]s_comp_results
  158. # which provides the program's completion choices.
  159. complete -c %[2]s -n '__%[1]s_prepare_completions' -f -a '$__%[1]s_comp_results'
  160. `, nameForVar, name, compCmd,
  161. ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp,
  162. ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs))
  163. }
  164. // GenFishCompletion generates fish completion file and writes to the passed writer.
  165. func (c *Command) GenFishCompletion(w io.Writer, includeDesc bool) error {
  166. buf := new(bytes.Buffer)
  167. genFishComp(buf, c.Name(), includeDesc)
  168. _, err := buf.WriteTo(w)
  169. return err
  170. }
  171. // GenFishCompletionFile generates fish completion file.
  172. func (c *Command) GenFishCompletionFile(filename string, includeDesc bool) error {
  173. outFile, err := os.Create(filename)
  174. if err != nil {
  175. return err
  176. }
  177. defer outFile.Close()
  178. return c.GenFishCompletion(outFile, includeDesc)
  179. }