zsh-syntax-highlighting.zsh 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601
  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. # First of all, ensure predictable parsing.
  30. typeset zsh_highlight__aliases="$(builtin alias -Lm '[^+]*')"
  31. # In zsh <= 5.2, aliases that begin with a plus sign ('alias -- +foo=42')
  32. # are emitted by `alias -L` 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. # This function takes a single argument F and returns True iff F is an autoload stub.
  50. _zsh_highlight__function_is_autoload_stub_p() {
  51. if zmodload -e zsh/parameter; then
  52. #(( ${+functions[$1]} )) &&
  53. [[ "$functions[$1]" == *"builtin autoload -X"* ]]
  54. else
  55. #[[ $(type -wa -- "$1") == *'function'* ]] &&
  56. [[ "${${(@f)"$(which -- "$1")"}[2]}" == $'\t'$histchars[3]' undefined' ]]
  57. fi
  58. # Do nothing here: return the exit code of the if.
  59. }
  60. # Return True iff the argument denotes a function name.
  61. _zsh_highlight__is_function_p() {
  62. if zmodload -e zsh/parameter; then
  63. (( ${+functions[$1]} ))
  64. else
  65. [[ $(type -wa -- "$1") == *'function'* ]]
  66. fi
  67. }
  68. # This function takes a single argument F and returns True iff F denotes the
  69. # name of a callable function. A function is callable if it is fully defined
  70. # or if it is marked for autoloading and autoloading it at the first call to it
  71. # will succeed. In particular, if F has been marked for autoloading
  72. # but is not available in $fpath, then calling this function on F will return False.
  73. #
  74. # See users/21671 http://www.zsh.org/cgi-bin/mla/redirect?USERNUMBER=21671
  75. _zsh_highlight__function_callable_p() {
  76. if _zsh_highlight__is_function_p "$1" &&
  77. ! _zsh_highlight__function_is_autoload_stub_p "$1"
  78. then
  79. # Already fully loaded.
  80. return 0 # true
  81. else
  82. # "$1" is either an autoload stub, or not a function at all.
  83. #
  84. # Use a subshell to avoid affecting the calling shell.
  85. #
  86. # We expect 'autoload +X' to return non-zero if it fails to fully load
  87. # the function.
  88. ( autoload -U +X -- "$1" 2>/dev/null )
  89. return $?
  90. fi
  91. }
  92. # -------------------------------------------------------------------------------------------------
  93. # Core highlighting update system
  94. # -------------------------------------------------------------------------------------------------
  95. # Use workaround for bug in ZSH?
  96. # zsh-users/zsh@48cadf4 http://www.zsh.org/mla/workers//2017/msg00034.html
  97. autoload -Uz is-at-least
  98. if is-at-least 5.4; then
  99. typeset -g zsh_highlight__pat_static_bug=false
  100. else
  101. typeset -g zsh_highlight__pat_static_bug=true
  102. fi
  103. # Array declaring active highlighters names.
  104. typeset -ga ZSH_HIGHLIGHT_HIGHLIGHTERS
  105. # Update ZLE buffer syntax highlighting.
  106. #
  107. # Invokes each highlighter that needs updating.
  108. # This function is supposed to be called whenever the ZLE state changes.
  109. _zsh_highlight()
  110. {
  111. # Store the previous command return code to restore it whatever happens.
  112. local ret=$?
  113. # Make it read-only. Can't combine this with the previous line when POSIX_BUILTINS may be set.
  114. typeset -r ret
  115. # $region_highlight should be predefined, either by zle or by the test suite's mock (non-special) array.
  116. (( ${+region_highlight} )) || {
  117. echo >&2 'zsh-syntax-highlighting: error: $region_highlight is not defined'
  118. echo >&2 'zsh-syntax-highlighting: (Check whether zsh-syntax-highlighting was installed according to the instructions.)'
  119. return $ret
  120. }
  121. # Probe the memo= feature, once.
  122. (( ${+zsh_highlight__memo_feature} )) || {
  123. region_highlight+=( " 0 0 fg=red, memo=zsh-syntax-highlighting" )
  124. case ${region_highlight[-1]} in
  125. ("0 0 fg=red")
  126. # zsh 5.8 or earlier
  127. integer -gr zsh_highlight__memo_feature=0
  128. ;;
  129. ("0 0 fg=red memo=zsh-syntax-highlighting")
  130. # zsh 5.9 or later
  131. integer -gr zsh_highlight__memo_feature=1
  132. ;;
  133. (" 0 0 fg=red, memo=zsh-syntax-highlighting") ;&
  134. (*)
  135. # We can get here in two ways:
  136. #
  137. # 1. When not running as a widget. In that case, $region_highlight is
  138. # not a special variable (= one with custom getter/setter functions
  139. # written in C) but an ordinary one, so the third case pattern matches
  140. # and we fall through to this block. (The test suite uses this codepath.)
  141. #
  142. # 2. When running under a future version of zsh that will have changed
  143. # the serialization of $region_highlight elements from their underlying
  144. # C structs, so that none of the previous case patterns will match.
  145. #
  146. # In either case, fall back to a version check.
  147. #
  148. # The memo= feature was added to zsh in commit zsh-5.8-172-gdd6e702ee.
  149. # The version number at the time was 5.8.0.2-dev (see Config/version.mk).
  150. # Therefore, on zsh master 5.8.0.3 and newer the memo= feature is available.
  151. # However, there's also the zsh 5.8.1 release, which doesn't have the
  152. # memo= feature.
  153. #
  154. # On zsh master 5.8.0.2 between the aforementioned commit and the
  155. # first Config/version.mk bump after it (zsh-5.8-607-g75c1edde5, the
  156. # bump to 5.8.1.1-dev following the backport to master of the bump
  157. # to 5.8.1), this condition will false negative.
  158. if is-at-least 5.8.1.1 $ZSH_VERSION.0.0; then
  159. integer -gr zsh_highlight__memo_feature=1
  160. else
  161. integer -gr zsh_highlight__memo_feature=0
  162. fi
  163. ;;
  164. esac
  165. region_highlight[-1]=()
  166. }
  167. # Reset region_highlight to build it from scratch
  168. if (( zsh_highlight__memo_feature )); then
  169. region_highlight=( "${(@)region_highlight:#*memo=zsh-syntax-highlighting*}" )
  170. else
  171. # Legacy codepath. Not very interoperable with other plugins (issue #418).
  172. region_highlight=()
  173. fi
  174. # Remove all highlighting in isearch, so that only the underlining done by zsh itself remains.
  175. # For details see FAQ entry 'Why does syntax highlighting not work while searching history?'.
  176. # This disables highlighting during isearch (for reasons explained in README.md) unless zsh is new enough
  177. # and doesn't have the pattern matching bug
  178. if [[ $WIDGET == zle-isearch-update ]] && { $zsh_highlight__pat_static_bug || ! (( $+ISEARCHMATCH_ACTIVE )) }; then
  179. return $ret
  180. fi
  181. # Before we 'emulate -L', save the user's options
  182. local -A zsyh_user_options
  183. if zmodload -e zsh/parameter; then
  184. zsyh_user_options=("${(kv)options[@]}")
  185. else
  186. local canonical_options onoff option raw_options
  187. raw_options=(${(f)"$(emulate -R zsh; set -o)"})
  188. canonical_options=(${${${(M)raw_options:#*off}%% *}#no} ${${(M)raw_options:#*on}%% *})
  189. for option in "${canonical_options[@]}"; do
  190. [[ -o $option ]]
  191. case $? in
  192. (0) zsyh_user_options+=($option on);;
  193. (1) zsyh_user_options+=($option off);;
  194. (*) # Can't happen, surely?
  195. echo "zsh-syntax-highlighting: warning: '[[ -o $option ]]' returned $?"
  196. ;;
  197. esac
  198. done
  199. fi
  200. typeset -r zsyh_user_options
  201. emulate -L zsh
  202. setopt localoptions warncreateglobal nobashrematch
  203. local REPLY # don't leak $REPLY into global scope
  204. # Do not highlight if there are more than 300 chars in the buffer. It's most
  205. # likely a pasted command or a huge list of files in that case..
  206. [[ -n ${ZSH_HIGHLIGHT_MAXLENGTH:-} ]] && [[ $#BUFFER -gt $ZSH_HIGHLIGHT_MAXLENGTH ]] && return $ret
  207. # Do not highlight if there are pending inputs (copy/paste).
  208. (( KEYS_QUEUED_COUNT > 0 )) && return $ret
  209. (( PENDING > 0 )) && return $ret
  210. {
  211. local cache_place
  212. local -a region_highlight_copy
  213. # Select which highlighters in ZSH_HIGHLIGHT_HIGHLIGHTERS need to be invoked.
  214. local highlighter; for highlighter in $ZSH_HIGHLIGHT_HIGHLIGHTERS; do
  215. # eval cache place for current highlighter and prepare it
  216. cache_place="_zsh_highlight__highlighter_${highlighter}_cache"
  217. typeset -ga ${cache_place}
  218. # If highlighter needs to be invoked
  219. if ! type "_zsh_highlight_highlighter_${highlighter}_predicate" >&/dev/null; then
  220. echo "zsh-syntax-highlighting: warning: disabling the ${(qq)highlighter} highlighter as it has not been loaded" >&2
  221. # TODO: use ${(b)} rather than ${(q)} if supported
  222. ZSH_HIGHLIGHT_HIGHLIGHTERS=( ${ZSH_HIGHLIGHT_HIGHLIGHTERS:#${highlighter}} )
  223. elif "_zsh_highlight_highlighter_${highlighter}_predicate"; then
  224. # save a copy, and cleanup region_highlight
  225. region_highlight_copy=("${region_highlight[@]}")
  226. region_highlight=()
  227. # Execute highlighter and save result
  228. {
  229. "_zsh_highlight_highlighter_${highlighter}_paint"
  230. } always {
  231. : ${(AP)cache_place::="${region_highlight[@]}"}
  232. }
  233. # Restore saved region_highlight
  234. region_highlight=("${region_highlight_copy[@]}")
  235. fi
  236. # Use value form cache if any cached
  237. region_highlight+=("${(@P)cache_place}")
  238. done
  239. # Re-apply zle_highlight settings
  240. # region
  241. () {
  242. (( REGION_ACTIVE )) || return
  243. integer min max
  244. if (( MARK > CURSOR )) ; then
  245. min=$CURSOR max=$MARK
  246. else
  247. min=$MARK max=$CURSOR
  248. fi
  249. if (( REGION_ACTIVE == 1 )); then
  250. [[ $KEYMAP = vicmd ]] && (( max++ ))
  251. elif (( REGION_ACTIVE == 2 )); then
  252. local needle=$'\n'
  253. # CURSOR and MARK are 0 indexed between letters like region_highlight
  254. # Do not include the newline in the highlight
  255. (( min = ${BUFFER[(Ib:min:)$needle]} ))
  256. (( max = ${BUFFER[(ib:max:)$needle]} - 1 ))
  257. fi
  258. _zsh_highlight_apply_zle_highlight region standout "$min" "$max"
  259. }
  260. # yank / paste (zsh-5.1.1 and newer)
  261. (( $+YANK_ACTIVE )) && (( YANK_ACTIVE )) && _zsh_highlight_apply_zle_highlight paste standout "$YANK_START" "$YANK_END"
  262. # isearch
  263. (( $+ISEARCHMATCH_ACTIVE )) && (( ISEARCHMATCH_ACTIVE )) && _zsh_highlight_apply_zle_highlight isearch underline "$ISEARCHMATCH_START" "$ISEARCHMATCH_END"
  264. # suffix
  265. (( $+SUFFIX_ACTIVE )) && (( SUFFIX_ACTIVE )) && _zsh_highlight_apply_zle_highlight suffix bold "$SUFFIX_START" "$SUFFIX_END"
  266. return $ret
  267. } always {
  268. typeset -g _ZSH_HIGHLIGHT_PRIOR_BUFFER="$BUFFER"
  269. typeset -gi _ZSH_HIGHLIGHT_PRIOR_CURSOR=$CURSOR
  270. }
  271. }
  272. # Apply highlighting based on entries in the zle_highlight array.
  273. # This function takes four arguments:
  274. # 1. The exact entry (no patterns) in the zle_highlight array:
  275. # region, paste, isearch, or suffix
  276. # 2. The default highlighting that should be applied if the entry is unset
  277. # 3. and 4. Two integer values describing the beginning and end of the
  278. # range. The order does not matter.
  279. _zsh_highlight_apply_zle_highlight() {
  280. local entry="$1" default="$2"
  281. integer first="$3" second="$4"
  282. # read the relevant entry from zle_highlight
  283. #
  284. # ### In zsh≥5.0.8 we'd use ${(b)entry}, but we support older zsh's, so we don't
  285. # ### add (b). The only effect is on the failure mode for callers that violate
  286. # ### the precondition.
  287. local region="${zle_highlight[(r)${entry}:*]-}"
  288. if [[ -z "$region" ]]; then
  289. # entry not specified at all, use default value
  290. region=$default
  291. else
  292. # strip prefix
  293. region="${region#${entry}:}"
  294. # no highlighting when set to the empty string or to 'none'
  295. if [[ -z "$region" ]] || [[ "$region" == none ]]; then
  296. return
  297. fi
  298. fi
  299. integer start end
  300. if (( first < second )); then
  301. start=$first end=$second
  302. else
  303. start=$second end=$first
  304. fi
  305. region_highlight+=("$start $end $region, memo=zsh-syntax-highlighting")
  306. }
  307. # -------------------------------------------------------------------------------------------------
  308. # API/utility functions for highlighters
  309. # -------------------------------------------------------------------------------------------------
  310. # Array used by highlighters to declare user overridable styles.
  311. typeset -gA ZSH_HIGHLIGHT_STYLES
  312. # Whether the command line buffer has been modified or not.
  313. #
  314. # Returns 0 if the buffer has changed since _zsh_highlight was last called.
  315. _zsh_highlight_buffer_modified()
  316. {
  317. [[ "${_ZSH_HIGHLIGHT_PRIOR_BUFFER:-}" != "$BUFFER" ]]
  318. }
  319. # Whether the cursor has moved or not.
  320. #
  321. # Returns 0 if the cursor has moved since _zsh_highlight was last called.
  322. _zsh_highlight_cursor_moved()
  323. {
  324. [[ -n $CURSOR ]] && [[ -n ${_ZSH_HIGHLIGHT_PRIOR_CURSOR-} ]] && (($_ZSH_HIGHLIGHT_PRIOR_CURSOR != $CURSOR))
  325. }
  326. # Add a highlight defined by ZSH_HIGHLIGHT_STYLES.
  327. #
  328. # Should be used by all highlighters aside from 'pattern' (cf. ZSH_HIGHLIGHT_PATTERN).
  329. # Overwritten in tests/test-highlighting.zsh when testing.
  330. _zsh_highlight_add_highlight()
  331. {
  332. local -i start end
  333. local highlight
  334. start=$1
  335. end=$2
  336. shift 2
  337. for highlight; do
  338. if (( $+ZSH_HIGHLIGHT_STYLES[$highlight] )); then
  339. region_highlight+=("$start $end $ZSH_HIGHLIGHT_STYLES[$highlight], memo=zsh-syntax-highlighting")
  340. break
  341. fi
  342. done
  343. }
  344. # -------------------------------------------------------------------------------------------------
  345. # Setup functions
  346. # -------------------------------------------------------------------------------------------------
  347. # Helper for _zsh_highlight_bind_widgets
  348. # $1 is name of widget to call
  349. _zsh_highlight_call_widget()
  350. {
  351. builtin zle "$@" &&
  352. _zsh_highlight
  353. }
  354. # Decide whether to use the zle-line-pre-redraw codepath (colloquially known as
  355. # "feature/redrawhook", after the topic branch's name) or the legacy "bind all
  356. # widgets" codepath.
  357. #
  358. # We use the new codepath under two conditions:
  359. #
  360. # 1. If it's available, which we check by testing for add-zle-hook-widget's availability.
  361. #
  362. # 2. If zsh has the memo= feature, which is required for interoperability reasons.
  363. # See issues #579 and #735, and the issues referenced from them.
  364. #
  365. # We check this with a plain version number check, since a functional check,
  366. # as done by _zsh_highlight, can only be done from inside a widget
  367. # function — a catch-22.
  368. #
  369. # See _zsh_highlight for the magic version number.
  370. if is-at-least 5.8.1.1 $ZSH_VERSION.0.0 && _zsh_highlight__function_callable_p add-zle-hook-widget
  371. then
  372. autoload -U add-zle-hook-widget
  373. _zsh_highlight__zle-line-finish() {
  374. # Reset $WIDGET since the 'main' highlighter depends on it.
  375. #
  376. # Since $WIDGET is declared by zle as read-only in this function's scope,
  377. # a nested function is required in order to shadow its built-in value;
  378. # see "User-defined widgets" in zshall.
  379. () {
  380. local -h -r WIDGET=zle-line-finish
  381. _zsh_highlight
  382. }
  383. }
  384. _zsh_highlight__zle-line-pre-redraw() {
  385. # Set $? to 0 for _zsh_highlight. Without this, subsequent
  386. # zle-line-pre-redraw hooks won't run, since add-zle-hook-widget happens to
  387. # call us with $? == 1 in the common case.
  388. true && _zsh_highlight "$@"
  389. }
  390. _zsh_highlight_bind_widgets(){}
  391. if [[ -o zle ]]; then
  392. add-zle-hook-widget zle-line-pre-redraw _zsh_highlight__zle-line-pre-redraw
  393. add-zle-hook-widget zle-line-finish _zsh_highlight__zle-line-finish
  394. fi
  395. else
  396. # Rebind all ZLE widgets to make them invoke _zsh_highlights.
  397. _zsh_highlight_bind_widgets()
  398. {
  399. setopt localoptions noksharrays
  400. typeset -F SECONDS
  401. local prefix=orig-s$SECONDS-r$RANDOM # unique each time, in case we're sourced more than once
  402. # Load ZSH module zsh/zleparameter, needed to override user defined widgets.
  403. zmodload zsh/zleparameter 2>/dev/null || {
  404. print -r -- >&2 'zsh-syntax-highlighting: failed loading zsh/zleparameter.'
  405. return 1
  406. }
  407. # Override ZLE widgets to make them invoke _zsh_highlight.
  408. local -U widgets_to_bind
  409. widgets_to_bind=(${${(k)widgets}:#(.*|run-help|which-command|beep|set-local-history|yank|yank-pop)})
  410. # Always wrap special zle-line-finish widget. This is needed to decide if the
  411. # current line ends and special highlighting logic needs to be applied.
  412. # E.g. remove cursor imprint, don't highlight partial paths, ...
  413. widgets_to_bind+=(zle-line-finish)
  414. # Always wrap special zle-isearch-update widget to be notified of updates in isearch.
  415. # This is needed because we need to disable highlighting in that case.
  416. widgets_to_bind+=(zle-isearch-update)
  417. local cur_widget
  418. for cur_widget in $widgets_to_bind; do
  419. case ${widgets[$cur_widget]:-""} in
  420. # Already rebound event: do nothing.
  421. user:_zsh_highlight_widget_*);;
  422. # The "eval"'s are required to make $cur_widget a closure: the value of the parameter at function
  423. # definition time is used.
  424. #
  425. # We can't use ${0/_zsh_highlight_widget_} because these widgets are always invoked with
  426. # NO_function_argzero, regardless of the option's setting here.
  427. # User defined widget: override and rebind old one with prefix "orig-".
  428. user:*) zle -N $prefix-$cur_widget ${widgets[$cur_widget]#*:}
  429. eval "_zsh_highlight_widget_${(q)prefix}-${(q)cur_widget}() { _zsh_highlight_call_widget ${(q)prefix}-${(q)cur_widget} -- \"\$@\" }"
  430. zle -N $cur_widget _zsh_highlight_widget_$prefix-$cur_widget;;
  431. # Completion widget: override and rebind old one with prefix "orig-".
  432. completion:*) zle -C $prefix-$cur_widget ${${(s.:.)widgets[$cur_widget]}[2,3]}
  433. eval "_zsh_highlight_widget_${(q)prefix}-${(q)cur_widget}() { _zsh_highlight_call_widget ${(q)prefix}-${(q)cur_widget} -- \"\$@\" }"
  434. zle -N $cur_widget _zsh_highlight_widget_$prefix-$cur_widget;;
  435. # Builtin widget: override and make it call the builtin ".widget".
  436. builtin) eval "_zsh_highlight_widget_${(q)prefix}-${(q)cur_widget}() { _zsh_highlight_call_widget .${(q)cur_widget} -- \"\$@\" }"
  437. zle -N $cur_widget _zsh_highlight_widget_$prefix-$cur_widget;;
  438. # Incomplete or nonexistent widget: Bind to z-sy-h directly.
  439. *)
  440. if [[ $cur_widget == zle-* ]] && (( ! ${+widgets[$cur_widget]} )); then
  441. _zsh_highlight_widget_${cur_widget}() { :; _zsh_highlight }
  442. zle -N $cur_widget _zsh_highlight_widget_$cur_widget
  443. else
  444. # Default: unhandled case.
  445. print -r -- >&2 "zsh-syntax-highlighting: unhandled ZLE widget ${(qq)cur_widget}"
  446. 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\`.)"
  447. fi
  448. esac
  449. done
  450. }
  451. fi
  452. # Load highlighters from directory.
  453. #
  454. # Arguments:
  455. # 1) Path to the highlighters directory.
  456. _zsh_highlight_load_highlighters()
  457. {
  458. setopt localoptions noksharrays bareglobqual
  459. # Check the directory exists.
  460. [[ -d "$1" ]] || {
  461. print -r -- >&2 "zsh-syntax-highlighting: highlighters directory ${(qq)1} not found."
  462. return 1
  463. }
  464. # Load highlighters from highlighters directory and check they define required functions.
  465. local highlighter highlighter_dir
  466. for highlighter_dir ($1/*/(/)); do
  467. highlighter="${highlighter_dir:t}"
  468. [[ -f "$highlighter_dir${highlighter}-highlighter.zsh" ]] &&
  469. . "$highlighter_dir${highlighter}-highlighter.zsh"
  470. if type "_zsh_highlight_highlighter_${highlighter}_paint" &> /dev/null &&
  471. type "_zsh_highlight_highlighter_${highlighter}_predicate" &> /dev/null;
  472. then
  473. # New (0.5.0) function names
  474. elif type "_zsh_highlight_${highlighter}_highlighter" &> /dev/null &&
  475. type "_zsh_highlight_${highlighter}_highlighter_predicate" &> /dev/null;
  476. then
  477. # Old (0.4.x) function names
  478. if false; then
  479. # TODO: only show this warning for plugin authors/maintainers, not for end users
  480. 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"
  481. fi
  482. # Make it work.
  483. eval "_zsh_highlight_highlighter_${(q)highlighter}_paint() { _zsh_highlight_${(q)highlighter}_highlighter \"\$@\" }"
  484. eval "_zsh_highlight_highlighter_${(q)highlighter}_predicate() { _zsh_highlight_${(q)highlighter}_highlighter_predicate \"\$@\" }"
  485. else
  486. 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"}."
  487. fi
  488. done
  489. }
  490. # -------------------------------------------------------------------------------------------------
  491. # Setup
  492. # -------------------------------------------------------------------------------------------------
  493. # Try binding widgets.
  494. _zsh_highlight_bind_widgets || {
  495. print -r -- >&2 'zsh-syntax-highlighting: failed binding ZLE widgets, exiting.'
  496. return 1
  497. }
  498. # Resolve highlighters directory location.
  499. _zsh_highlight_load_highlighters "${ZSH_HIGHLIGHT_HIGHLIGHTERS_DIR:-${${0:A}:h}/highlighters}" || {
  500. print -r -- >&2 'zsh-syntax-highlighting: failed loading highlighters, exiting.'
  501. return 1
  502. }
  503. # Reset scratch variables when commandline is done.
  504. _zsh_highlight_preexec_hook()
  505. {
  506. typeset -g _ZSH_HIGHLIGHT_PRIOR_BUFFER=
  507. typeset -gi _ZSH_HIGHLIGHT_PRIOR_CURSOR=
  508. }
  509. autoload -Uz add-zsh-hook
  510. add-zsh-hook preexec _zsh_highlight_preexec_hook 2>/dev/null || {
  511. print -r -- >&2 'zsh-syntax-highlighting: failed loading add-zsh-hook.'
  512. }
  513. # Load zsh/parameter module if available
  514. zmodload zsh/parameter 2>/dev/null || true
  515. # Initialize the array of active highlighters if needed.
  516. [[ $#ZSH_HIGHLIGHT_HIGHLIGHTERS -eq 0 ]] && ZSH_HIGHLIGHT_HIGHLIGHTERS=(main brackets)
  517. if (( $+X_ZSH_HIGHLIGHT_DIRS_BLACKLIST )); then
  518. print >&2 'zsh-syntax-highlighting: X_ZSH_HIGHLIGHT_DIRS_BLACKLIST is deprecated. Please use ZSH_HIGHLIGHT_DIRS_BLACKLIST.'
  519. ZSH_HIGHLIGHT_DIRS_BLACKLIST=($X_ZSH_HIGHLIGHT_DIRS_BLACKLIST)
  520. unset X_ZSH_HIGHLIGHT_DIRS_BLACKLIST
  521. fi
  522. # Restore the aliases we unned
  523. eval "$zsh_highlight__aliases"
  524. builtin unset zsh_highlight__aliases
  525. # Set $?.
  526. true