zsh-syntax-highlighting.zsh 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  1. # -------------------------------------------------------------------------------------------------
  2. # Copyright (c) 2010-2016 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. # First of all, ensure predictable parsing.
  30. zsh_highlight__aliases=`builtin alias -Lm '[^+]*'`
  31. # In zsh <= 5.2, `alias -L` emits aliases that begin with a plus sign ('alias -- +foo=42')
  32. # them without a '--' guard, so they don't round trip.
  33. #
  34. # Hence, we exclude them from unaliasing:
  35. builtin unalias -m '[^+]*'
  36. # Set $0 to the expected value, regardless of functionargzero.
  37. #0=${(%):-%N}
  38. #if true; then
  39. # # $0 is reliable
  40. # typeset -g ZSH_HIGHLIGHT_VERSION=$(<"${0:A:h}"/.version)
  41. # typeset -g ZSH_HIGHLIGHT_REVISION=$(<"${0:A:h}"/.revision-hash)
  42. # if [[ $ZSH_HIGHLIGHT_REVISION == \$Format:* ]]; then
  43. # # When running from a source tree without 'make install', $ZSH_HIGHLIGHT_REVISION
  44. # # would be set to '$Format:%H$' literally. That's an invalid value, and obtaining
  45. # # the valid value (via `git rev-parse HEAD`, as Makefile does) might be costly, so:
  46. # ZSH_HIGHLIGHT_REVISION=HEAD
  47. # fi
  48. #fi
  49. # -------------------------------------------------------------------------------------------------
  50. # Core highlighting update system
  51. # -------------------------------------------------------------------------------------------------
  52. # Use workaround for bug in ZSH?
  53. # zsh-users/zsh@48cadf4 http://www.zsh.org/mla/workers//2017/msg00034.html
  54. autoload -U is-at-least
  55. if is-at-least 5.4; then
  56. zsh_highlight__pat_static_bug=false
  57. else
  58. zsh_highlight__pat_static_bug=true
  59. fi
  60. # Array declaring active highlighters names.
  61. typeset -ga ZSH_HIGHLIGHT_HIGHLIGHTERS
  62. # Update ZLE buffer syntax highlighting.
  63. #
  64. # Invokes each highlighter that needs updating.
  65. # This function is supposed to be called whenever the ZLE state changes.
  66. _zsh_highlight()
  67. {
  68. # Store the previous command return code to restore it whatever happens.
  69. local ret=$?
  70. # Remove all highlighting in isearch, so that only the underlining done by zsh itself remains.
  71. # For details see FAQ entry 'Why does syntax highlighting not work while searching history?'.
  72. # This disables highlighting during isearch (for reasons explained in README.md) unless zsh is new enough
  73. # and doesn't have the pattern matching bug
  74. if [[ $WIDGET == zle-isearch-update ]] && { $zsh_highlight__pat_static_bug || ! (( $+ISEARCHMATCH_ACTIVE )) }; then
  75. region_highlight=()
  76. return $ret
  77. fi
  78. setopt localoptions warncreateglobal
  79. setopt localoptions noksharrays
  80. local REPLY # don't leak $REPLY into global scope
  81. # Do not highlight if there are more than 300 chars in the buffer. It's most
  82. # likely a pasted command or a huge list of files in that case..
  83. [[ -n ${ZSH_HIGHLIGHT_MAXLENGTH:-} ]] && [[ $#BUFFER -gt $ZSH_HIGHLIGHT_MAXLENGTH ]] && return $ret
  84. # Do not highlight if there are pending inputs (copy/paste).
  85. [[ $PENDING -gt 0 ]] && return $ret
  86. # Reset region highlight to build it from scratch
  87. typeset -ga region_highlight
  88. region_highlight=();
  89. {
  90. local cache_place
  91. local -a region_highlight_copy
  92. # Select which highlighters in ZSH_HIGHLIGHT_HIGHLIGHTERS need to be invoked.
  93. local highlighter; for highlighter in $ZSH_HIGHLIGHT_HIGHLIGHTERS; do
  94. # eval cache place for current highlighter and prepare it
  95. cache_place="_zsh_highlight__highlighter_${highlighter}_cache"
  96. typeset -ga ${cache_place}
  97. # If highlighter needs to be invoked
  98. if ! type "_zsh_highlight_highlighter_${highlighter}_predicate" >&/dev/null; then
  99. echo "zsh-syntax-highlighting: warning: disabling the ${(qq)highlighter} highlighter as it has not been loaded" >&2
  100. # TODO: use ${(b)} rather than ${(q)} if supported
  101. ZSH_HIGHLIGHT_HIGHLIGHTERS=( ${ZSH_HIGHLIGHT_HIGHLIGHTERS:#${highlighter}} )
  102. elif "_zsh_highlight_highlighter_${highlighter}_predicate"; then
  103. # save a copy, and cleanup region_highlight
  104. region_highlight_copy=("${region_highlight[@]}")
  105. region_highlight=()
  106. # Execute highlighter and save result
  107. {
  108. "_zsh_highlight_highlighter_${highlighter}_paint"
  109. } always {
  110. eval "${cache_place}=(\"\${region_highlight[@]}\")"
  111. }
  112. # Restore saved region_highlight
  113. region_highlight=("${region_highlight_copy[@]}")
  114. fi
  115. # Use value form cache if any cached
  116. eval "region_highlight+=(\"\${${cache_place}[@]}\")"
  117. done
  118. # Re-apply zle_highlight settings
  119. # region
  120. if (( REGION_ACTIVE == 1 )); then
  121. _zsh_highlight_apply_zle_highlight region standout "$MARK" "$CURSOR"
  122. elif (( REGION_ACTIVE == 2 )); then
  123. () {
  124. local needle=$'\n'
  125. integer min max
  126. if (( MARK > CURSOR )) ; then
  127. min=$CURSOR max=$MARK
  128. else
  129. min=$MARK max=$CURSOR
  130. fi
  131. (( min = ${${BUFFER[1,$min]}[(I)$needle]} ))
  132. (( max += ${${BUFFER:($max-1)}[(i)$needle]} - 1 ))
  133. _zsh_highlight_apply_zle_highlight region standout "$min" "$max"
  134. }
  135. fi
  136. # yank / paste (zsh-5.1.1 and newer)
  137. (( $+YANK_ACTIVE )) && (( YANK_ACTIVE )) && _zsh_highlight_apply_zle_highlight paste standout "$YANK_START" "$YANK_END"
  138. # isearch
  139. (( $+ISEARCHMATCH_ACTIVE )) && (( ISEARCHMATCH_ACTIVE )) && _zsh_highlight_apply_zle_highlight isearch underline "$ISEARCHMATCH_START" "$ISEARCHMATCH_END"
  140. # suffix
  141. (( $+SUFFIX_ACTIVE )) && (( SUFFIX_ACTIVE )) && _zsh_highlight_apply_zle_highlight suffix bold "$SUFFIX_START" "$SUFFIX_END"
  142. return $ret
  143. } always {
  144. typeset -g _ZSH_HIGHLIGHT_PRIOR_BUFFER="$BUFFER"
  145. typeset -gi _ZSH_HIGHLIGHT_PRIOR_CURSOR=$CURSOR
  146. }
  147. }
  148. # Apply highlighting based on entries in the zle_highlight array.
  149. # This function takes four arguments:
  150. # 1. The exact entry (no patterns) in the zle_highlight array:
  151. # region, paste, isearch, or suffix
  152. # 2. The default highlighting that should be applied if the entry is unset
  153. # 3. and 4. Two integer values describing the beginning and end of the
  154. # range. The order does not matter.
  155. _zsh_highlight_apply_zle_highlight() {
  156. local entry="$1" default="$2"
  157. integer first="$3" second="$4"
  158. # read the relevant entry from zle_highlight
  159. local region="${zle_highlight[(r)${entry}:*]}"
  160. if [[ -z "$region" ]]; then
  161. # entry not specified at all, use default value
  162. region=$default
  163. else
  164. # strip prefix
  165. region="${region#${entry}:}"
  166. # no highlighting when set to the empty string or to 'none'
  167. if [[ -z "$region" ]] || [[ "$region" == none ]]; then
  168. return
  169. fi
  170. fi
  171. integer start end
  172. if (( first < second )); then
  173. start=$first end=$second
  174. else
  175. start=$second end=$first
  176. fi
  177. region_highlight+=("$start $end $region")
  178. }
  179. # -------------------------------------------------------------------------------------------------
  180. # API/utility functions for highlighters
  181. # -------------------------------------------------------------------------------------------------
  182. # Array used by highlighters to declare user overridable styles.
  183. typeset -gA ZSH_HIGHLIGHT_STYLES
  184. # Whether the command line buffer has been modified or not.
  185. #
  186. # Returns 0 if the buffer has changed since _zsh_highlight was last called.
  187. _zsh_highlight_buffer_modified()
  188. {
  189. [[ "${_ZSH_HIGHLIGHT_PRIOR_BUFFER:-}" != "$BUFFER" ]]
  190. }
  191. # Whether the cursor has moved or not.
  192. #
  193. # Returns 0 if the cursor has moved since _zsh_highlight was last called.
  194. _zsh_highlight_cursor_moved()
  195. {
  196. [[ -n $CURSOR ]] && [[ -n ${_ZSH_HIGHLIGHT_PRIOR_CURSOR-} ]] && (($_ZSH_HIGHLIGHT_PRIOR_CURSOR != $CURSOR))
  197. }
  198. # Add a highlight defined by ZSH_HIGHLIGHT_STYLES.
  199. #
  200. # Should be used by all highlighters aside from 'pattern' (cf. ZSH_HIGHLIGHT_PATTERN).
  201. # Overwritten in tests/test-highlighting.zsh when testing.
  202. _zsh_highlight_add_highlight()
  203. {
  204. local -i start end
  205. local highlight
  206. start=$1
  207. end=$2
  208. shift 2
  209. for highlight; do
  210. if (( $+ZSH_HIGHLIGHT_STYLES[$highlight] )); then
  211. region_highlight+=("$start $end $ZSH_HIGHLIGHT_STYLES[$highlight]")
  212. break
  213. fi
  214. done
  215. }
  216. # -------------------------------------------------------------------------------------------------
  217. # Setup functions
  218. # -------------------------------------------------------------------------------------------------
  219. # Helper for _zsh_highlight_bind_widgets
  220. # $1 is name of widget to call
  221. _zsh_highlight_call_widget()
  222. {
  223. builtin zle "$@" &&
  224. _zsh_highlight
  225. }
  226. # Rebind all ZLE widgets to make them invoke _zsh_highlights.
  227. _zsh_highlight_bind_widgets()
  228. {
  229. setopt localoptions noksharrays
  230. typeset -F SECONDS
  231. local prefix=orig-s$SECONDS-r$RANDOM # unique each time, in case we're sourced more than once
  232. # Load ZSH module zsh/zleparameter, needed to override user defined widgets.
  233. zmodload zsh/zleparameter 2>/dev/null || {
  234. print -r -- >&2 'zsh-syntax-highlighting: failed loading zsh/zleparameter.'
  235. return 1
  236. }
  237. # Override ZLE widgets to make them invoke _zsh_highlight.
  238. local -U widgets_to_bind
  239. widgets_to_bind=(${${(k)widgets}:#(.*|run-help|which-command|beep|set-local-history|yank)})
  240. # Always wrap special zle-line-finish widget. This is needed to decide if the
  241. # current line ends and special highlighting logic needs to be applied.
  242. # E.g. remove cursor imprint, don't highlight partial paths, ...
  243. widgets_to_bind+=(zle-line-finish)
  244. # Always wrap special zle-isearch-update widget to be notified of updates in isearch.
  245. # This is needed because we need to disable highlighting in that case.
  246. widgets_to_bind+=(zle-isearch-update)
  247. local cur_widget
  248. for cur_widget in $widgets_to_bind; do
  249. case $widgets[$cur_widget] in
  250. # Already rebound event: do nothing.
  251. user:_zsh_highlight_widget_*);;
  252. # The "eval"'s are required to make $cur_widget a closure: the value of the parameter at function
  253. # definition time is used.
  254. #
  255. # We can't use ${0/_zsh_highlight_widget_} because these widgets are always invoked with
  256. # NO_function_argzero, regardless of the option's setting here.
  257. # User defined widget: override and rebind old one with prefix "orig-".
  258. user:*) zle -N $prefix-$cur_widget ${widgets[$cur_widget]#*:}
  259. eval "_zsh_highlight_widget_${(q)prefix}-${(q)cur_widget}() { _zsh_highlight_call_widget ${(q)prefix}-${(q)cur_widget} -- \"\$@\" }"
  260. zle -N $cur_widget _zsh_highlight_widget_$prefix-$cur_widget;;
  261. # Completion widget: override and rebind old one with prefix "orig-".
  262. completion:*) zle -C $prefix-$cur_widget ${${(s.:.)widgets[$cur_widget]}[2,3]}
  263. eval "_zsh_highlight_widget_${(q)prefix}-${(q)cur_widget}() { _zsh_highlight_call_widget ${(q)prefix}-${(q)cur_widget} -- \"\$@\" }"
  264. zle -N $cur_widget _zsh_highlight_widget_$prefix-$cur_widget;;
  265. # Builtin widget: override and make it call the builtin ".widget".
  266. builtin) eval "_zsh_highlight_widget_${(q)prefix}-${(q)cur_widget}() { _zsh_highlight_call_widget .${(q)cur_widget} -- \"\$@\" }"
  267. zle -N $cur_widget _zsh_highlight_widget_$prefix-$cur_widget;;
  268. # Incomplete or nonexistent widget: Bind to z-sy-h directly.
  269. *)
  270. if [[ $cur_widget == zle-* ]] && [[ -z $widgets[$cur_widget] ]]; then
  271. _zsh_highlight_widget_${cur_widget}() { :; _zsh_highlight }
  272. zle -N $cur_widget _zsh_highlight_widget_$cur_widget
  273. else
  274. # Default: unhandled case.
  275. print -r -- >&2 "zsh-syntax-highlighting: unhandled ZLE widget ${(qq)cur_widget}"
  276. 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\`.)"
  277. fi
  278. esac
  279. done
  280. }
  281. # Load highlighters from directory.
  282. #
  283. # Arguments:
  284. # 1) Path to the highlighters directory.
  285. _zsh_highlight_load_highlighters()
  286. {
  287. setopt localoptions noksharrays
  288. # Check the directory exists.
  289. [[ -d "$1" ]] || {
  290. print -r -- >&2 "zsh-syntax-highlighting: highlighters directory ${(qq)1} not found."
  291. return 1
  292. }
  293. # Load highlighters from highlighters directory and check they define required functions.
  294. local highlighter highlighter_dir
  295. for highlighter_dir ($1/*/); do
  296. highlighter="${highlighter_dir:t}"
  297. [[ -f "$highlighter_dir${highlighter}-highlighter.zsh" ]] &&
  298. . "$highlighter_dir${highlighter}-highlighter.zsh"
  299. if type "_zsh_highlight_highlighter_${highlighter}_paint" &> /dev/null &&
  300. type "_zsh_highlight_highlighter_${highlighter}_predicate" &> /dev/null;
  301. then
  302. # New (0.5.0) function names
  303. elif type "_zsh_highlight_${highlighter}_highlighter" &> /dev/null &&
  304. type "_zsh_highlight_${highlighter}_highlighter_predicate" &> /dev/null;
  305. then
  306. # Old (0.4.x) function names
  307. if false; then
  308. # TODO: only show this warning for plugin authors/maintainers, not for end users
  309. print -r -- >&2 "zsh-syntax-highlighting: warning: ${(qq)highlighter} highlighter uses deprecated entry point names; please ask its maintainer to update it: https://github.com/zsh-users/zsh-syntax-highlighting/issues/329"
  310. fi
  311. # Make it work.
  312. eval "_zsh_highlight_highlighter_${(q)highlighter}_paint() { _zsh_highlight_${(q)highlighter}_highlighter \"\$@\" }"
  313. eval "_zsh_highlight_highlighter_${(q)highlighter}_predicate() { _zsh_highlight_${(q)highlighter}_highlighter_predicate \"\$@\" }"
  314. else
  315. print -r -- >&2 "zsh-syntax-highlighting: ${(qq)highlighter} highlighter should define both required functions '_zsh_highlight_highlighter_${highlighter}_paint' and '_zsh_highlight_highlighter_${highlighter}_predicate' in ${(qq):-"$highlighter_dir${highlighter}-highlighter.zsh"}."
  316. fi
  317. done
  318. }
  319. # -------------------------------------------------------------------------------------------------
  320. # Setup
  321. # -------------------------------------------------------------------------------------------------
  322. # Try binding widgets.
  323. _zsh_highlight_bind_widgets || {
  324. print -r -- >&2 'zsh-syntax-highlighting: failed binding ZLE widgets, exiting.'
  325. return 1
  326. }
  327. # Resolve highlighters directory location.
  328. _zsh_highlight_load_highlighters "${ZSH_HIGHLIGHT_HIGHLIGHTERS_DIR:-${${0:A}:h}/highlighters}" || {
  329. print -r -- >&2 'zsh-syntax-highlighting: failed loading highlighters, exiting.'
  330. return 1
  331. }
  332. # Reset scratch variables when commandline is done.
  333. _zsh_highlight_preexec_hook()
  334. {
  335. typeset -g _ZSH_HIGHLIGHT_PRIOR_BUFFER=
  336. typeset -gi _ZSH_HIGHLIGHT_PRIOR_CURSOR=
  337. }
  338. autoload -U add-zsh-hook
  339. add-zsh-hook preexec _zsh_highlight_preexec_hook 2>/dev/null || {
  340. print -r -- >&2 'zsh-syntax-highlighting: failed loading add-zsh-hook.'
  341. }
  342. # Load zsh/parameter module if available
  343. zmodload zsh/parameter 2>/dev/null || true
  344. # Initialize the array of active highlighters if needed.
  345. [[ $#ZSH_HIGHLIGHT_HIGHLIGHTERS -eq 0 ]] && ZSH_HIGHLIGHT_HIGHLIGHTERS=(main)
  346. # Restore the aliases we unned
  347. eval "$zsh_highlight__aliases"
  348. builtin unset zsh_highlight__aliases
  349. # Set $?.
  350. true