You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

267 line
12 KiB

  1. # -------------------------------------------------------------------------------------------------
  2. # Copyright (c) 2010-2020 zsh-syntax-highlighting contributors
  3. # All rights reserved.
  4. #
  5. # Redistribution and use in source and binary forms, with or without modification, are permitted
  6. # provided that the following conditions are met:
  7. #
  8. # * Redistributions of source code must retain the above copyright notice, this list of conditions
  9. # and the following disclaimer.
  10. # * Redistributions in binary form must reproduce the above copyright notice, this list of
  11. # conditions and the following disclaimer in the documentation and/or other materials provided
  12. # with the distribution.
  13. # * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors
  14. # may be used to endorse or promote products derived from this software without specific prior
  15. # written permission.
  16. #
  17. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
  18. # IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  19. # FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
  20. # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  21. # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  22. # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
  23. # IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
  24. # OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. # -------------------------------------------------------------------------------------------------
  26. # -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*-
  27. # vim: ft=zsh sw=2 ts=2 et
  28. # -------------------------------------------------------------------------------------------------
  29. # Set $0 to the expected value, regardless of functionargzero.
  30. 0=${(%):-%N}
  31. # Update ZLE buffer syntax highlighting.
  32. #
  33. # Invokes each highlighter that needs updating.
  34. # This function is supposed to be called whenever the ZLE state changes.
  35. #
  36. # This function must not be defined or run under emulate zsh so zsyh_user_options is correct.
  37. _zsh_highlight()
  38. {
  39. # Store the previous command return code to restore it whatever happens.
  40. local ret=$?
  41. # Make it read-only. Can't combine this with the previous line when POSIX_BUILTINS may be set.
  42. typeset -r ret
  43. # $region_highlight should be predefined, either by zle or by the test suite's mock (non-special) array.
  44. (( ${+region_highlight} )) || {
  45. echo >&2 'zsh-syntax-highlighting: error: $region_highlight is not defined'
  46. echo >&2 'zsh-syntax-highlighting: (Check whether zsh-syntax-highlighting was installed according to the instructions.)'
  47. return $ret
  48. }
  49. # Probe the memo= feature, once.
  50. (( ${+zsh_highlight__memo_feature} )) || {
  51. region_highlight+=( " 0 0 fg=red, memo=zsh-syntax-highlighting" )
  52. case ${region_highlight[-1]} in
  53. ("0 0 fg=red")
  54. # zsh 5.8 or earlier
  55. integer -gr zsh_highlight__memo_feature=0
  56. ;;
  57. ("0 0 fg=red memo=zsh-syntax-highlighting")
  58. # zsh 5.9 or later
  59. integer -gr zsh_highlight__memo_feature=1
  60. ;;
  61. (" 0 0 fg=red, memo=zsh-syntax-highlighting") ;&
  62. (*)
  63. # We can get here in two ways:
  64. #
  65. # 1. When not running as a widget. In that case, $region_highlight is
  66. # not a special variable (= one with custom getter/setter functions
  67. # written in C) but an ordinary one, so the third case pattern matches
  68. # and we fall through to this block. (The test suite uses this codepath.)
  69. #
  70. # 2. When running under a future version of zsh that will have changed
  71. # the serialization of $region_highlight elements from their underlying
  72. # C structs, so that none of the previous case patterns will match.
  73. #
  74. # In either case, fall back to a version check.
  75. #
  76. # The memo= feature was added to zsh in commit zsh-5.8-172-gdd6e702ee.
  77. # The version number at the time was 5.8.0.2-dev (see Config/version.mk).
  78. # Therefore, on 5.8.0.3 and newer the memo= feature is available.
  79. #
  80. # On zsh version 5.8.0.2 between the aforementioned commit and the
  81. # first Config/version.mk bump after it (which, at the time of writing,
  82. # is yet to come), this condition will false negative.
  83. if is-at-least 5.8.0.3 $ZSH_VERSION.0.0; then
  84. integer -gr zsh_highlight__memo_feature=1
  85. else
  86. integer -gr zsh_highlight__memo_feature=0
  87. fi
  88. ;;
  89. esac
  90. region_highlight[-1]=()
  91. }
  92. # Reset region_highlight to build it from scratch
  93. if (( zsh_highlight__memo_feature )); then
  94. region_highlight=( "${(@)region_highlight:#*memo=zsh-syntax-highlighting*}" )
  95. else
  96. # Legacy codepath. Not very interoperable with other plugins (issue #418).
  97. region_highlight=()
  98. fi
  99. # Remove all highlighting in isearch, so that only the underlining done by zsh itself remains.
  100. # For details see FAQ entry 'Why does syntax highlighting not work while searching history?'.
  101. # This disables highlighting during isearch (for reasons explained in README.md) unless zsh is new enough
  102. # and doesn't have the pattern matching bug
  103. if [[ $WIDGET == zle-isearch-update ]] && { $zsh_highlight__pat_static_bug || ! (( $+ISEARCHMATCH_ACTIVE )) }; then
  104. return $ret
  105. fi
  106. # Before we 'emulate -L', save the user's options
  107. local -A zsyh_user_options
  108. if zmodload -e zsh/parameter; then
  109. zsyh_user_options=("${(kv)options[@]}")
  110. else
  111. local canonical_options onoff option raw_options
  112. raw_options=(${(f)"$(emulate -R zsh; set -o)"})
  113. canonical_options=(${${${(M)raw_options:#*off}%% *}#no} ${${(M)raw_options:#*on}%% *})
  114. for option in "${canonical_options[@]}"; do
  115. [[ -o $option ]]
  116. case $? in
  117. (0) zsyh_user_options+=($option on);;
  118. (1) zsyh_user_options+=($option off);;
  119. (*) # Can't happen, surely?
  120. echo "zsh-syntax-highlighting: warning: '[[ -o $option ]]' returned $?"
  121. ;;
  122. esac
  123. done
  124. fi
  125. typeset -r zsyh_user_options
  126. _zsh_highlight_internal
  127. return ret
  128. }
  129. emulate zsh -c 'source ${0:h}/driver.zsh'
  130. # Helper for _zsh_highlight_bind_widgets
  131. # $1 is name of widget to call
  132. _zsh_highlight_call_widget()
  133. {
  134. builtin zle "$@" &&
  135. _zsh_highlight
  136. }
  137. # Decide whether to use the zle-line-pre-redraw codepath (colloquially known as
  138. # "feature/redrawhook", after the topic branch's name) or the legacy "bind all
  139. # widgets" codepath.
  140. #
  141. # We use the new codepath under two conditions:
  142. #
  143. # 1. If it's available, which we check by testing for add-zle-hook-widget's availability.
  144. #
  145. # 2. If zsh has the memo= feature, which is required for interoperability reasons.
  146. # See issues #579 and #735, and the issues referenced from them.
  147. #
  148. # We check this with a plain version number check, since a functional check,
  149. # as done by _zsh_highlight, can only be done from inside a widget
  150. # function — a catch-22.
  151. #
  152. # See _zsh_highlight for the magic version number. (The use of 5.8.0.2
  153. # rather than 5.8.0.3 as in the _zsh_highlight is deliberate.)
  154. if is-at-least 5.8.0.2 $ZSH_VERSION.0.0 && _zsh_highlight__function_callable_p add-zle-hook-widget
  155. then
  156. autoload -U add-zle-hook-widget
  157. _zsh_highlight__zle-line-finish() {
  158. # Reset $WIDGET since the 'main' highlighter depends on it.
  159. #
  160. # Since $WIDGET is declared by zle as read-only in this function's scope,
  161. # a nested function is required in order to shadow its built-in value;
  162. # see "User-defined widgets" in zshall.
  163. () {
  164. local -h -r WIDGET=zle-line-finish
  165. _zsh_highlight
  166. }
  167. }
  168. _zsh_highlight__zle-line-pre-redraw() {
  169. # Set $? to 0 for _zsh_highlight. Without this, subsequent
  170. # zle-line-pre-redraw hooks won't run, since add-zle-hook-widget happens to
  171. # call us with $? == 1 in the common case.
  172. true && _zsh_highlight "$@"
  173. }
  174. _zsh_highlight_bind_widgets(){}
  175. if [[ -o zle ]]; then
  176. add-zle-hook-widget zle-line-pre-redraw _zsh_highlight__zle-line-pre-redraw
  177. add-zle-hook-widget zle-line-finish _zsh_highlight__zle-line-finish
  178. fi
  179. else
  180. # Rebind all ZLE widgets to make them invoke _zsh_highlights.
  181. _zsh_highlight_bind_widgets()
  182. {
  183. setopt localoptions noksharrays
  184. typeset -F SECONDS
  185. local prefix=orig-s$SECONDS-r$RANDOM # unique each time, in case we're sourced more than once
  186. # Load ZSH module zsh/zleparameter, needed to override user defined widgets.
  187. zmodload zsh/zleparameter 2>/dev/null || {
  188. print -r -- >&2 'zsh-syntax-highlighting: failed loading zsh/zleparameter.'
  189. return 1
  190. }
  191. # Override ZLE widgets to make them invoke _zsh_highlight.
  192. local -U widgets_to_bind
  193. widgets_to_bind=(${${(k)widgets}:#(.*|run-help|which-command|beep|set-local-history|yank|yank-pop)})
  194. # Always wrap special zle-line-finish widget. This is needed to decide if the
  195. # current line ends and special highlighting logic needs to be applied.
  196. # E.g. remove cursor imprint, don't highlight partial paths, ...
  197. widgets_to_bind+=(zle-line-finish)
  198. # Always wrap special zle-isearch-update widget to be notified of updates in isearch.
  199. # This is needed because we need to disable highlighting in that case.
  200. widgets_to_bind+=(zle-isearch-update)
  201. local cur_widget
  202. for cur_widget in $widgets_to_bind; do
  203. case ${widgets[$cur_widget]:-""} in
  204. # Already rebound event: do nothing.
  205. user:_zsh_highlight_widget_*);;
  206. # The "eval"'s are required to make $cur_widget a closure: the value of the parameter at function
  207. # definition time is used.
  208. #
  209. # We can't use ${0/_zsh_highlight_widget_} because these widgets are always invoked with
  210. # NO_function_argzero, regardless of the option's setting here.
  211. # User defined widget: override and rebind old one with prefix "orig-".
  212. user:*) zle -N $prefix-$cur_widget ${widgets[$cur_widget]#*:}
  213. eval "_zsh_highlight_widget_${(q)prefix}-${(q)cur_widget}() { _zsh_highlight_call_widget ${(q)prefix}-${(q)cur_widget} -- \"\$@\" }"
  214. zle -N $cur_widget _zsh_highlight_widget_$prefix-$cur_widget;;
  215. # Completion widget: override and rebind old one with prefix "orig-".
  216. completion:*) zle -C $prefix-$cur_widget ${${(s.:.)widgets[$cur_widget]}[2,3]}
  217. eval "_zsh_highlight_widget_${(q)prefix}-${(q)cur_widget}() { _zsh_highlight_call_widget ${(q)prefix}-${(q)cur_widget} -- \"\$@\" }"
  218. zle -N $cur_widget _zsh_highlight_widget_$prefix-$cur_widget;;
  219. # Builtin widget: override and make it call the builtin ".widget".
  220. builtin) eval "_zsh_highlight_widget_${(q)prefix}-${(q)cur_widget}() { _zsh_highlight_call_widget .${(q)cur_widget} -- \"\$@\" }"
  221. zle -N $cur_widget _zsh_highlight_widget_$prefix-$cur_widget;;
  222. # Incomplete or nonexistent widget: Bind to z-sy-h directly.
  223. *)
  224. if [[ $cur_widget == zle-* ]] && (( ! ${+widgets[$cur_widget]} )); then
  225. _zsh_highlight_widget_${cur_widget}() { :; _zsh_highlight }
  226. zle -N $cur_widget _zsh_highlight_widget_$cur_widget
  227. else
  228. # Default: unhandled case.
  229. print -r -- >&2 "zsh-syntax-highlighting: unhandled ZLE widget ${(qq)cur_widget}"
  230. print -r -- >&2 "zsh-syntax-highlighting: (This is sometimes caused by doing \`bindkey <keys> ${(q-)cur_widget}\` without creating the ${(qq)cur_widget} widget with \`zle -N\` or \`zle -C\`.)"
  231. fi
  232. esac
  233. done
  234. }
  235. fi
  236. # Try binding widgets.
  237. _zsh_highlight_bind_widgets || {
  238. print -r -- >&2 'zsh-syntax-highlighting: failed binding ZLE widgets, exiting.'
  239. return 1
  240. }
  241. # Set $?.
  242. true