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.

615 line
25 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. # 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 a function has been marked for autoloading
  72. # but is not available in $fpath, then this function will return False therefor.
  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 5.8.0.3 and newer the memo= feature is available.
  151. #
  152. # On zsh version 5.8.0.2 between the aforementioned commit and the
  153. # first Config/version.mk bump after it (which, at the time of writing,
  154. # is yet to come), this condition will false negative.
  155. if is-at-least 5.8.0.3 $ZSH_VERSION.0.0; then
  156. integer -gr zsh_highlight__memo_feature=1
  157. else
  158. integer -gr zsh_highlight__memo_feature=0
  159. fi
  160. ;;
  161. esac
  162. region_highlight[-1]=()
  163. }
  164. # Remove all highlighting in isearch, so that only the underlining done by zsh itself remains.
  165. # For details see FAQ entry 'Why does syntax highlighting not work while searching history?'.
  166. # This disables highlighting during isearch (for reasons explained in README.md) unless zsh is new enough
  167. # and doesn't have the pattern matching bug
  168. if [[ $WIDGET == zle-isearch-update ]] && { $zsh_highlight__pat_static_bug || ! (( $+ISEARCHMATCH_ACTIVE )) } ||
  169. # Do not highlight if there are more than 300 chars in the buffer. It's most
  170. # likely a pasted command or a huge list of files in that case..
  171. [[ -n ${ZSH_HIGHLIGHT_MAXLENGTH:-} ]] && (( ${#BUFFER} > ZSH_HIGHLIGHT_MAXLENGTH )) ||
  172. # Do not highlight if there are pending inputs (copy/paste).
  173. (( PENDING )); then
  174. # Reset region_highlight to build it from scratch
  175. if (( zsh_highlight__memo_feature )); then
  176. region_highlight=( "${(@)region_highlight:#*memo=zsh-syntax-highlighting*}" )
  177. else
  178. # Legacy codepath. Not very interoperable with other plugins (issue #418).
  179. region_highlight=()
  180. fi
  181. return $ret
  182. fi
  183. # Before we 'emulate -L', save the user's options
  184. local -A zsyh_user_options
  185. if zmodload -e zsh/parameter; then
  186. if [[ -n ${ZSH_HIGHLIGHT_HIGHLIGHTERS:#(brackets|cursor|line|main|pattern|regexp|root)} ]]; then
  187. # Copy all options if there are user-defined highlighters
  188. zsyh_user_options=("${(kv)options[@]}")
  189. else
  190. # Copy a subset of options used by the bundled highlighters. This is faster than
  191. # copying all options.
  192. zsyh_user_options=(
  193. ignorebraces "${options[ignorebraces]}"
  194. ignoreclosebraces "${options[ignoreclosebraces]-off}"
  195. pathdirs "${options[pathdirs]}"
  196. interactivecomments "${options[interactivecomments]}"
  197. globassign "${options[globassign]}"
  198. multifuncdef "${options[multifuncdef]}"
  199. autocd "${options[autocd]}"
  200. equals "${options[equals]}"
  201. multios "${options[multios]}"
  202. rcquotes "${options[rcquotes]}"
  203. )
  204. fi
  205. else
  206. local canonical_options onoff option raw_options
  207. raw_options=(${(f)"$(emulate -R zsh; set -o)"})
  208. canonical_options=(${${${(M)raw_options:#*off}%% *}#no} ${${(M)raw_options:#*on}%% *})
  209. for option in "${canonical_options[@]}"; do
  210. [[ -o $option ]]
  211. case $? in
  212. (0) zsyh_user_options+=($option on);;
  213. (1) zsyh_user_options+=($option off);;
  214. (*) # Can't happen, surely?
  215. echo "zsh-syntax-highlighting: warning: '[[ -o $option ]]' returned $?"
  216. ;;
  217. esac
  218. done
  219. fi
  220. typeset -r zsyh_user_options
  221. local -a new_highlight
  222. if (( zsh_highlight__memo_feature )); then
  223. new_highlight=( "${(@)region_highlight:#*memo=zsh-syntax-highlighting*}" )
  224. fi
  225. emulate -L zsh
  226. setopt warncreateglobal nobashrematch
  227. local REPLY # don't leak $REPLY into global scope
  228. {
  229. local cache_place pred
  230. # Select which highlighters in ZSH_HIGHLIGHT_HIGHLIGHTERS need to be invoked.
  231. local highlighter; for highlighter in $ZSH_HIGHLIGHT_HIGHLIGHTERS; do
  232. # eval cache place for current highlighter and prepare it
  233. cache_place="_zsh_highlight__highlighter_${highlighter}_cache"
  234. typeset -ga ${cache_place}
  235. # If highlighter needs to be invoked
  236. pred="_zsh_highlight_highlighter_${highlighter}_predicate"
  237. if (( ! $pred )); then
  238. if type $pred >&/dev/null; then
  239. typeset -gri $pred=1
  240. else
  241. echo "zsh-syntax-highlighting: warning: disabling the ${(qq)highlighter} highlighter as it has not been loaded" >&2
  242. # TODO: use ${(b)} rather than ${(q)} if supported
  243. ZSH_HIGHLIGHT_HIGHLIGHTERS=( ${ZSH_HIGHLIGHT_HIGHLIGHTERS:#${highlighter}} )
  244. continue
  245. fi
  246. fi
  247. if $pred; then
  248. # Execute highlighter and save result
  249. region_highlight=()
  250. "_zsh_highlight_highlighter_${highlighter}_paint"
  251. : ${(AP)cache_place::="${region_highlight[@]}"}
  252. new_highlight+=($region_highlight)
  253. else
  254. # Use value form cache if any cached
  255. new_highlight+=("${(@P)cache_place}")
  256. fi
  257. done
  258. region_highlight=($new_highlight)
  259. # Re-apply zle_highlight settings
  260. # region
  261. (( REGION_ACTIVE )) && () {
  262. integer min max
  263. if (( MARK > CURSOR )) ; then
  264. min=$CURSOR max=$MARK
  265. else
  266. min=$MARK max=$CURSOR
  267. fi
  268. if (( REGION_ACTIVE == 1 )); then
  269. [[ $KEYMAP = vicmd ]] && (( max++ ))
  270. elif (( REGION_ACTIVE == 2 )); then
  271. local needle=$'\n'
  272. # CURSOR and MARK are 0 indexed between letters like region_highlight
  273. # Do not include the newline in the highlight
  274. (( min = ${BUFFER[(Ib:min:)$needle]} ))
  275. (( max = ${BUFFER[(ib:max:)$needle]} - 1 ))
  276. fi
  277. _zsh_highlight_apply_zle_highlight region standout "$min" "$max"
  278. }
  279. # yank / paste (zsh-5.1.1 and newer)
  280. (( YANK_ACTIVE )) && _zsh_highlight_apply_zle_highlight paste standout "$YANK_START" "$YANK_END"
  281. # isearch
  282. (( ISEARCHMATCH_ACTIVE )) && _zsh_highlight_apply_zle_highlight isearch underline "$ISEARCHMATCH_START" "$ISEARCHMATCH_END"
  283. # suffix
  284. (( SUFFIX_ACTIVE )) && _zsh_highlight_apply_zle_highlight suffix bold "$SUFFIX_START" "$SUFFIX_END"
  285. return $ret
  286. } always {
  287. typeset -g _ZSH_HIGHLIGHT_PRIOR_BUFFER="$BUFFER"
  288. typeset -gi _ZSH_HIGHLIGHT_PRIOR_CURSOR=$CURSOR
  289. }
  290. }
  291. # Apply highlighting based on entries in the zle_highlight array.
  292. # This function takes four arguments:
  293. # 1. The exact entry (no patterns) in the zle_highlight array:
  294. # region, paste, isearch, or suffix
  295. # 2. The default highlighting that should be applied if the entry is unset
  296. # 3. and 4. Two integer values describing the beginning and end of the
  297. # range. The order does not matter.
  298. _zsh_highlight_apply_zle_highlight() {
  299. local entry="$1" default="$2"
  300. integer first="$3" second="$4"
  301. # read the relevant entry from zle_highlight
  302. #
  303. # ### In zsh≥5.0.8 we'd use ${(b)entry}, but we support older zsh's, so we don't
  304. # ### add (b). The only effect is on the failure mode for callers that violate
  305. # ### the precondition.
  306. local region="${zle_highlight[(r)${entry}:*]-}"
  307. if [[ -z "$region" ]]; then
  308. # entry not specified at all, use default value
  309. region=$default
  310. else
  311. # strip prefix
  312. region="${region#${entry}:}"
  313. # no highlighting when set to the empty string or to 'none'
  314. if [[ -z "$region" ]] || [[ "$region" == none ]]; then
  315. return
  316. fi
  317. fi
  318. integer start end
  319. if (( first < second )); then
  320. start=$first end=$second
  321. else
  322. start=$second end=$first
  323. fi
  324. region_highlight+=("$start $end $region, memo=zsh-syntax-highlighting")
  325. }
  326. # -------------------------------------------------------------------------------------------------
  327. # API/utility functions for highlighters
  328. # -------------------------------------------------------------------------------------------------
  329. # Array used by highlighters to declare user overridable styles.
  330. typeset -gA ZSH_HIGHLIGHT_STYLES
  331. # Whether the command line buffer has been modified or not.
  332. #
  333. # Returns 0 if the buffer has changed since _zsh_highlight was last called.
  334. _zsh_highlight_buffer_modified()
  335. {
  336. [[ "${_ZSH_HIGHLIGHT_PRIOR_BUFFER:-}" != "$BUFFER" ]]
  337. }
  338. # Whether the cursor has moved or not.
  339. #
  340. # Returns 0 if the cursor has moved since _zsh_highlight was last called.
  341. _zsh_highlight_cursor_moved()
  342. {
  343. [[ -n $CURSOR ]] && [[ -n ${_ZSH_HIGHLIGHT_PRIOR_CURSOR-} ]] && (($_ZSH_HIGHLIGHT_PRIOR_CURSOR != $CURSOR))
  344. }
  345. # Add a highlight defined by ZSH_HIGHLIGHT_STYLES.
  346. #
  347. # Should be used by all highlighters aside from 'pattern' (cf. ZSH_HIGHLIGHT_PATTERN).
  348. # Overwritten in tests/test-highlighting.zsh when testing.
  349. _zsh_highlight_add_highlight()
  350. {
  351. local -i start end
  352. local highlight
  353. start=$1
  354. end=$2
  355. shift 2
  356. for highlight; do
  357. if (( $+ZSH_HIGHLIGHT_STYLES[$highlight] )); then
  358. region_highlight+=("$start $end $ZSH_HIGHLIGHT_STYLES[$highlight], memo=zsh-syntax-highlighting")
  359. break
  360. fi
  361. done
  362. }
  363. # -------------------------------------------------------------------------------------------------
  364. # Setup functions
  365. # -------------------------------------------------------------------------------------------------
  366. # Helper for _zsh_highlight_bind_widgets
  367. # $1 is name of widget to call
  368. _zsh_highlight_call_widget()
  369. {
  370. builtin zle "$@" &&
  371. _zsh_highlight
  372. }
  373. # Decide whether to use the zle-line-pre-redraw codepath (colloquially known as
  374. # "feature/redrawhook", after the topic branch's name) or the legacy "bind all
  375. # widgets" codepath.
  376. #
  377. # We use the new codepath under two conditions:
  378. #
  379. # 1. If it's available, which we check by testing for add-zle-hook-widget's availability.
  380. #
  381. # 2. If zsh has the memo= feature, which is required for interoperability reasons.
  382. # See issues #579 and #735, and the issues referenced from them.
  383. #
  384. # We check this with a plain version number check, since a functional check,
  385. # as done by _zsh_highlight, can only be done from inside a widget
  386. # function — a catch-22.
  387. #
  388. # See _zsh_highlight for the magic version number. (The use of 5.8.0.2
  389. # rather than 5.8.0.3 as in the _zsh_highlight is deliberate.)
  390. if is-at-least 5.8.0.2 $ZSH_VERSION.0.0 && _zsh_highlight__function_callable_p add-zle-hook-widget
  391. then
  392. autoload -U add-zle-hook-widget
  393. _zsh_highlight__zle-line-finish() {
  394. # Reset $WIDGET since the 'main' highlighter depends on it.
  395. #
  396. # Since $WIDGET is declared by zle as read-only in this function's scope,
  397. # a nested function is required in order to shadow its built-in value;
  398. # see "User-defined widgets" in zshall.
  399. () {
  400. local -h -r WIDGET=zle-line-finish
  401. _zsh_highlight
  402. }
  403. }
  404. _zsh_highlight__zle-line-pre-redraw() {
  405. # Set $? to 0 for _zsh_highlight. Without this, subsequent
  406. # zle-line-pre-redraw hooks won't run, since add-zle-hook-widget happens to
  407. # call us with $? == 1 in the common case.
  408. true && _zsh_highlight "$@"
  409. }
  410. _zsh_highlight_bind_widgets(){}
  411. if [[ -o zle ]]; then
  412. add-zle-hook-widget zle-line-pre-redraw _zsh_highlight__zle-line-pre-redraw
  413. add-zle-hook-widget zle-line-finish _zsh_highlight__zle-line-finish
  414. fi
  415. else
  416. # Rebind all ZLE widgets to make them invoke _zsh_highlights.
  417. _zsh_highlight_bind_widgets()
  418. {
  419. setopt localoptions noksharrays
  420. typeset -F SECONDS
  421. local prefix=orig-s$SECONDS-r$RANDOM # unique each time, in case we're sourced more than once
  422. # Load ZSH module zsh/zleparameter, needed to override user defined widgets.
  423. zmodload zsh/zleparameter 2>/dev/null || {
  424. print -r -- >&2 'zsh-syntax-highlighting: failed loading zsh/zleparameter.'
  425. return 1
  426. }
  427. # Override ZLE widgets to make them invoke _zsh_highlight.
  428. local -U widgets_to_bind
  429. widgets_to_bind=(${${(k)widgets}:#(.*|run-help|which-command|beep|set-local-history|yank|yank-pop)})
  430. # Always wrap special zle-line-finish widget. This is needed to decide if the
  431. # current line ends and special highlighting logic needs to be applied.
  432. # E.g. remove cursor imprint, don't highlight partial paths, ...
  433. widgets_to_bind+=(zle-line-finish)
  434. # Always wrap special zle-isearch-update widget to be notified of updates in isearch.
  435. # This is needed because we need to disable highlighting in that case.
  436. widgets_to_bind+=(zle-isearch-update)
  437. local cur_widget
  438. for cur_widget in $widgets_to_bind; do
  439. case ${widgets[$cur_widget]:-""} in
  440. # Already rebound event: do nothing.
  441. user:_zsh_highlight_widget_*);;
  442. # The "eval"'s are required to make $cur_widget a closure: the value of the parameter at function
  443. # definition time is used.
  444. #
  445. # We can't use ${0/_zsh_highlight_widget_} because these widgets are always invoked with
  446. # NO_function_argzero, regardless of the option's setting here.
  447. # User defined widget: override and rebind old one with prefix "orig-".
  448. user:*) zle -N $prefix-$cur_widget ${widgets[$cur_widget]#*:}
  449. eval "_zsh_highlight_widget_${(q)prefix}-${(q)cur_widget}() { _zsh_highlight_call_widget ${(q)prefix}-${(q)cur_widget} -- \"\$@\" }"
  450. zle -N $cur_widget _zsh_highlight_widget_$prefix-$cur_widget;;
  451. # Completion widget: override and rebind old one with prefix "orig-".
  452. completion:*) zle -C $prefix-$cur_widget ${${(s.:.)widgets[$cur_widget]}[2,3]}
  453. eval "_zsh_highlight_widget_${(q)prefix}-${(q)cur_widget}() { _zsh_highlight_call_widget ${(q)prefix}-${(q)cur_widget} -- \"\$@\" }"
  454. zle -N $cur_widget _zsh_highlight_widget_$prefix-$cur_widget;;
  455. # Builtin widget: override and make it call the builtin ".widget".
  456. builtin) eval "_zsh_highlight_widget_${(q)prefix}-${(q)cur_widget}() { _zsh_highlight_call_widget .${(q)cur_widget} -- \"\$@\" }"
  457. zle -N $cur_widget _zsh_highlight_widget_$prefix-$cur_widget;;
  458. # Incomplete or nonexistent widget: Bind to z-sy-h directly.
  459. *)
  460. if [[ $cur_widget == zle-* ]] && (( ! ${+widgets[$cur_widget]} )); then
  461. _zsh_highlight_widget_${cur_widget}() { :; _zsh_highlight }
  462. zle -N $cur_widget _zsh_highlight_widget_$cur_widget
  463. else
  464. # Default: unhandled case.
  465. print -r -- >&2 "zsh-syntax-highlighting: unhandled ZLE widget ${(qq)cur_widget}"
  466. 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\`.)"
  467. fi
  468. esac
  469. done
  470. }
  471. fi
  472. # Load highlighters from directory.
  473. #
  474. # Arguments:
  475. # 1) Path to the highlighters directory.
  476. _zsh_highlight_load_highlighters()
  477. {
  478. setopt localoptions noksharrays bareglobqual
  479. # Check the directory exists.
  480. [[ -d "$1" ]] || {
  481. print -r -- >&2 "zsh-syntax-highlighting: highlighters directory ${(qq)1} not found."
  482. return 1
  483. }
  484. # Load highlighters from highlighters directory and check they define required functions.
  485. local highlighter highlighter_dir
  486. for highlighter_dir ($1/*/(/)); do
  487. highlighter="${highlighter_dir:t}"
  488. [[ -f "$highlighter_dir${highlighter}-highlighter.zsh" ]] &&
  489. . "$highlighter_dir${highlighter}-highlighter.zsh"
  490. if type "_zsh_highlight_highlighter_${highlighter}_paint" &> /dev/null &&
  491. type "_zsh_highlight_highlighter_${highlighter}_predicate" &> /dev/null;
  492. then
  493. # New (0.5.0) function names
  494. elif type "_zsh_highlight_${highlighter}_highlighter" &> /dev/null &&
  495. type "_zsh_highlight_${highlighter}_highlighter_predicate" &> /dev/null;
  496. then
  497. # Old (0.4.x) function names
  498. if false; then
  499. # TODO: only show this warning for plugin authors/maintainers, not for end users
  500. 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"
  501. fi
  502. # Make it work.
  503. eval "_zsh_highlight_highlighter_${(q)highlighter}_paint() { _zsh_highlight_${(q)highlighter}_highlighter \"\$@\" }"
  504. eval "_zsh_highlight_highlighter_${(q)highlighter}_predicate() { _zsh_highlight_${(q)highlighter}_highlighter_predicate \"\$@\" }"
  505. else
  506. 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"}."
  507. fi
  508. done
  509. }
  510. # -------------------------------------------------------------------------------------------------
  511. # Setup
  512. # -------------------------------------------------------------------------------------------------
  513. # Try binding widgets.
  514. _zsh_highlight_bind_widgets || {
  515. print -r -- >&2 'zsh-syntax-highlighting: failed binding ZLE widgets, exiting.'
  516. return 1
  517. }
  518. # Resolve highlighters directory location.
  519. _zsh_highlight_load_highlighters "${ZSH_HIGHLIGHT_HIGHLIGHTERS_DIR:-${${0:A}:h}/highlighters}" || {
  520. print -r -- >&2 'zsh-syntax-highlighting: failed loading highlighters, exiting.'
  521. return 1
  522. }
  523. # Reset scratch variables when commandline is done.
  524. _zsh_highlight_preexec_hook()
  525. {
  526. typeset -g _ZSH_HIGHLIGHT_PRIOR_BUFFER=
  527. typeset -gi _ZSH_HIGHLIGHT_PRIOR_CURSOR=
  528. }
  529. autoload -Uz add-zsh-hook
  530. add-zsh-hook preexec _zsh_highlight_preexec_hook 2>/dev/null || {
  531. print -r -- >&2 'zsh-syntax-highlighting: failed loading add-zsh-hook.'
  532. }
  533. # Load zsh/parameter module if available
  534. zmodload zsh/parameter 2>/dev/null || true
  535. # Initialize the array of active highlighters if needed.
  536. [[ $#ZSH_HIGHLIGHT_HIGHLIGHTERS -eq 0 ]] && ZSH_HIGHLIGHT_HIGHLIGHTERS=(main)
  537. if (( $+X_ZSH_HIGHLIGHT_DIRS_BLACKLIST )); then
  538. print >&2 'zsh-syntax-highlighting: X_ZSH_HIGHLIGHT_DIRS_BLACKLIST is deprecated. Please use ZSH_HIGHLIGHT_DIRS_BLACKLIST.'
  539. ZSH_HIGHLIGHT_DIRS_BLACKLIST=($X_ZSH_HIGHLIGHT_DIRS_BLACKLIST)
  540. unset X_ZSH_HIGHLIGHT_DIRS_BLACKLIST
  541. fi
  542. # Restore the aliases we unned
  543. eval "$zsh_highlight__aliases"
  544. builtin unset zsh_highlight__aliases
  545. # Set $?.
  546. true