dots

Just my dots
git clone git://git.wrpr.us/dots
Log | Files | Refs | README

zsh-syntax-highlighting.zsh (24522B)


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