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.

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