1 # -------------------------------------------------------------------------------------------------
2 # Copyright (c) 2010-2016 zsh-syntax-highlighting contributors
5 # Redistribution and use in source and binary forms, with or without modification, are permitted
6 # provided that the following conditions are met:
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
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 # -------------------------------------------------------------------------------------------------
30 # First of all, ensure predictable parsing.
31 zsh_highlight__aliases
=`builtin alias -Lm '[^+]*'`
32 # In zsh <= 5.2, `alias -L` emits aliases that begin with a plus sign ('alias -- +foo=42')
33 # them without a '--' guard, so they don't round trip.
35 # Hence, we exclude them from unaliasing:
36 builtin unalias -m '[^+]*'
38 # Set $0 to the expected value, regardless of functionargzero.
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
52 # -------------------------------------------------------------------------------------------------
53 # Core highlighting update system
54 # -------------------------------------------------------------------------------------------------
56 # Use workaround for bug in ZSH?
57 # zsh-users/zsh@48cadf4 http://www.zsh.org/mla/workers//2017/msg00034.html
58 autoload
-U is-at-least
59 if is-at-least
5.4; then
60 zsh_highlight__pat_static_bug
=false
62 zsh_highlight__pat_static_bug
=true
65 # Array declaring active highlighters names.
66 typeset
-ga ZSH_HIGHLIGHT_HIGHLIGHTERS
68 # Update ZLE buffer syntax highlighting.
70 # Invokes each highlighter that needs updating.
71 # This function is supposed to be called whenever the ZLE state changes.
74 # Store the previous command return code to restore it whatever happens.
77 # Remove all highlighting in isearch, so that only the underlining done by zsh itself remains.
78 # For details see FAQ entry 'Why does syntax highlighting not work while searching history?'.
79 # This disables highlighting during isearch (for reasons explained in README.md) unless zsh is new enough
80 # and doesn't have the pattern matching bug
81 if [[ $WIDGET == zle-isearch-update
]] && { $zsh_highlight__pat_static_bug ||
! (( $
+ISEARCHMATCH_ACTIVE
)) }; then
86 setopt localoptions warncreateglobal
87 setopt localoptions noksharrays
88 local REPLY
# don't leak $REPLY into global scope
90 # Do not highlight if there are more than 300 chars in the buffer. It's most
91 # likely a pasted command or a huge list of files in that case..
92 [[ -n ${ZSH_HIGHLIGHT_MAXLENGTH:-} ]] && [[ $#BUFFER -gt $ZSH_HIGHLIGHT_MAXLENGTH ]] && return $ret
94 # Do not highlight if there are pending inputs (copy/paste).
95 [[ $PENDING -gt 0 ]] && return $ret
97 # Reset region highlight to build it from scratch
98 typeset
-ga region_highlight
103 local -a region_highlight_copy
105 # Select which highlighters in ZSH_HIGHLIGHT_HIGHLIGHTERS need to be invoked.
106 local highlighter
; for highlighter
in $ZSH_HIGHLIGHT_HIGHLIGHTERS; do
108 # eval cache place for current highlighter and prepare it
109 cache_place
="_zsh_highlight__highlighter_${highlighter}_cache"
110 typeset
-ga ${cache_place}
112 # If highlighter needs to be invoked
113 if ! type "_zsh_highlight_highlighter_${highlighter}_predicate" >&/dev
/null
; then
114 echo "zsh-syntax-highlighting: warning: disabling the ${(qq)highlighter} highlighter as it has not been loaded" >&2
115 # TODO: use ${(b)} rather than ${(q)} if supported
116 ZSH_HIGHLIGHT_HIGHLIGHTERS
=( ${ZSH_HIGHLIGHT_HIGHLIGHTERS:#${highlighter}} )
117 elif "_zsh_highlight_highlighter_${highlighter}_predicate"; then
119 # save a copy, and cleanup region_highlight
120 region_highlight_copy
=("${region_highlight[@]}")
123 # Execute highlighter and save result
125 "_zsh_highlight_highlighter_${highlighter}_paint"
127 eval "${cache_place}=(\"\${region_highlight[@]}\")"
130 # Restore saved region_highlight
131 region_highlight
=("${region_highlight_copy[@]}")
135 # Use value form cache if any cached
136 eval "region_highlight+=(\"\${${cache_place}[@]}\")"
140 # Re-apply zle_highlight settings
143 if (( REGION_ACTIVE
== 1 )); then
144 _zsh_highlight_apply_zle_highlight region standout
"$MARK" "$CURSOR"
145 elif (( REGION_ACTIVE
== 2 )); then
149 if (( MARK
> CURSOR
)) ; then
150 min
=$CURSOR max
=$MARK
152 min
=$MARK max
=$CURSOR
154 (( min
= ${${BUFFER[1,$min]}[(I
)$needle]} ))
155 (( max
+= ${${BUFFER:($max-1)}[(i
)$needle]} - 1 ))
156 _zsh_highlight_apply_zle_highlight region standout
"$min" "$max"
160 # yank / paste (zsh-5.1.1 and newer)
161 (( $
+YANK_ACTIVE
)) && (( YANK_ACTIVE
)) && _zsh_highlight_apply_zle_highlight
paste standout
"$YANK_START" "$YANK_END"
164 (( $
+ISEARCHMATCH_ACTIVE
)) && (( ISEARCHMATCH_ACTIVE
)) && _zsh_highlight_apply_zle_highlight isearch underline
"$ISEARCHMATCH_START" "$ISEARCHMATCH_END"
167 (( $
+SUFFIX_ACTIVE
)) && (( SUFFIX_ACTIVE
)) && _zsh_highlight_apply_zle_highlight suffix bold
"$SUFFIX_START" "$SUFFIX_END"
174 typeset
-g _ZSH_HIGHLIGHT_PRIOR_BUFFER
="$BUFFER"
175 typeset
-gi _ZSH_HIGHLIGHT_PRIOR_CURSOR
=$CURSOR
179 # Apply highlighting based on entries in the zle_highlight array.
180 # This function takes four arguments:
181 # 1. The exact entry (no patterns) in the zle_highlight array:
182 # region, paste, isearch, or suffix
183 # 2. The default highlighting that should be applied if the entry is unset
184 # 3. and 4. Two integer values describing the beginning and end of the
185 # range. The order does not matter.
186 _zsh_highlight_apply_zle_highlight
() {
187 local entry
="$1" default
="$2"
188 integer first
="$3" second
="$4"
190 # read the relevant entry from zle_highlight
192 # ### In zsh≥5.0.8 we'd use ${(b)entry}, but we support older zsh's, so we don't
193 # ### add (b). The only effect is on the failure mode for callers that violate
194 # ### the precondition.
195 local region
="${zle_highlight[(r)${entry}:*]-}"
197 if [[ -z "$region" ]]; then
198 # entry not specified at all, use default value
202 region
="${region#${entry}:}"
204 # no highlighting when set to the empty string or to 'none'
205 if [[ -z "$region" ]] ||
[[ "$region" == none
]]; then
211 if (( first
< second
)); then
212 start
=$first end
=$second
214 start
=$second end
=$first
216 region_highlight
+=("$start $end $region")
220 # -------------------------------------------------------------------------------------------------
221 # API/utility functions for highlighters
222 # -------------------------------------------------------------------------------------------------
224 # Array used by highlighters to declare user overridable styles.
225 typeset
-gA ZSH_HIGHLIGHT_STYLES
227 # Whether the command line buffer has been modified or not.
229 # Returns 0 if the buffer has changed since _zsh_highlight was last called.
230 _zsh_highlight_buffer_modified
()
232 [[ "${_ZSH_HIGHLIGHT_PRIOR_BUFFER:-}" != "$BUFFER" ]]
235 # Whether the cursor has moved or not.
237 # Returns 0 if the cursor has moved since _zsh_highlight was last called.
238 _zsh_highlight_cursor_moved
()
240 [[ -n $CURSOR ]] && [[ -n ${_ZSH_HIGHLIGHT_PRIOR_CURSOR-} ]] && (($_ZSH_HIGHLIGHT_PRIOR_CURSOR != $CURSOR))
243 # Add a highlight defined by ZSH_HIGHLIGHT_STYLES.
245 # Should be used by all highlighters aside from 'pattern' (cf. ZSH_HIGHLIGHT_PATTERN).
246 # Overwritten in tests/test-highlighting.zsh when testing.
247 _zsh_highlight_add_highlight
()
255 if (( $
+ZSH_HIGHLIGHT_STYLES
[$highlight] )); then
256 region_highlight
+=("$start $end $ZSH_HIGHLIGHT_STYLES[$highlight]")
262 # -------------------------------------------------------------------------------------------------
264 # -------------------------------------------------------------------------------------------------
266 # Helper for _zsh_highlight_bind_widgets
267 # $1 is name of widget to call
268 _zsh_highlight_call_widget
()
274 # Rebind all ZLE widgets to make them invoke _zsh_highlights.
275 _zsh_highlight_bind_widgets
()
277 setopt localoptions noksharrays
279 local prefix
=orig-s
$SECONDS-r$RANDOM # unique each time, in case we're sourced more than once
281 # Load ZSH module zsh/zleparameter, needed to override user defined widgets.
282 zmodload zsh
/zleparameter
2>/dev
/null ||
{
283 print
-r -- >&2 'zsh-syntax-highlighting: failed loading zsh/zleparameter.'
287 # Override ZLE widgets to make them invoke _zsh_highlight.
288 local -U widgets_to_bind
289 widgets_to_bind
=(${${(k)widgets}:#(.*|run-help|which-command|beep|set-local-history|yank)})
291 # Always wrap special zle-line-finish widget. This is needed to decide if the
292 # current line ends and special highlighting logic needs to be applied.
293 # E.g. remove cursor imprint, don't highlight partial paths, ...
294 widgets_to_bind
+=(zle-line-finish
)
296 # Always wrap special zle-isearch-update widget to be notified of updates in isearch.
297 # This is needed because we need to disable highlighting in that case.
298 widgets_to_bind
+=(zle-isearch-update
)
301 for cur_widget
in $widgets_to_bind; do
302 case ${widgets[$cur_widget]:-""} in
304 # Already rebound event: do nothing.
305 user
:_zsh_highlight_widget_
*);;
307 # The "eval"'s are required to make $cur_widget a closure: the value of the parameter at function
308 # definition time is used.
310 # We can't use ${0/_zsh_highlight_widget_} because these widgets are always invoked with
311 # NO_function_argzero, regardless of the option's setting here.
313 # User defined widget: override and rebind old one with prefix "orig-".
314 user
:*) zle
-N $prefix-$cur_widget ${widgets[$cur_widget]#*:}
315 eval "_zsh_highlight_widget_${(q)prefix}-${(q)cur_widget}() { _zsh_highlight_call_widget ${(q)prefix}-${(q)cur_widget} -- \"\$@\" }"
316 zle
-N $cur_widget _zsh_highlight_widget_
$prefix-$cur_widget;;
318 # Completion widget: override and rebind old one with prefix "orig-".
319 completion
:*) zle
-C $prefix-$cur_widget ${${(s.:.)widgets[$cur_widget]}[2,3]}
320 eval "_zsh_highlight_widget_${(q)prefix}-${(q)cur_widget}() { _zsh_highlight_call_widget ${(q)prefix}-${(q)cur_widget} -- \"\$@\" }"
321 zle
-N $cur_widget _zsh_highlight_widget_
$prefix-$cur_widget;;
323 # Builtin widget: override and make it call the builtin ".widget".
324 builtin) eval "_zsh_highlight_widget_${(q)prefix}-${(q)cur_widget}() { _zsh_highlight_call_widget .${(q)cur_widget} -- \"\$@\" }"
325 zle
-N $cur_widget _zsh_highlight_widget_
$prefix-$cur_widget;;
327 # Incomplete or nonexistent widget: Bind to z-sy-h directly.
329 if [[ $cur_widget == zle-
* ]] && (( ! ${+widgets[$cur_widget]} )); then
330 _zsh_highlight_widget_
${cur_widget}() { :; _zsh_highlight
}
331 zle
-N $cur_widget _zsh_highlight_widget_
$cur_widget
333 # Default: unhandled case.
334 print
-r -- >&2 "zsh-syntax-highlighting: unhandled ZLE widget ${(qq)cur_widget}"
335 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\`.)"
341 # Load highlighters from directory.
344 # 1) Path to the highlighters directory.
345 _zsh_highlight_load_highlighters
()
347 setopt localoptions noksharrays
349 # Check the directory exists.
351 print
-r -- >&2 "zsh-syntax-highlighting: highlighters directory ${(qq)1} not found."
355 # Load highlighters from highlighters directory and check they define required functions.
356 local highlighter highlighter_dir
357 for highlighter_dir
($1/*/); do
358 highlighter
="${highlighter_dir:t}"
359 [[ -f "$highlighter_dir${highlighter}-highlighter.zsh" ]] &&
360 .
"$highlighter_dir${highlighter}-highlighter.zsh"
361 if type "_zsh_highlight_highlighter_${highlighter}_paint" &> /dev
/null
&&
362 type "_zsh_highlight_highlighter_${highlighter}_predicate" &> /dev
/null
;
364 # New (0.5.0) function names
365 elif type "_zsh_highlight_${highlighter}_highlighter" &> /dev
/null
&&
366 type "_zsh_highlight_${highlighter}_highlighter_predicate" &> /dev
/null
;
368 # Old (0.4.x) function names
370 # TODO: only show this warning for plugin authors/maintainers, not for end users
371 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"
374 eval "_zsh_highlight_highlighter_${(q)highlighter}_paint() { _zsh_highlight_${(q)highlighter}_highlighter \"\$@\" }"
375 eval "_zsh_highlight_highlighter_${(q)highlighter}_predicate() { _zsh_highlight_${(q)highlighter}_highlighter_predicate \"\$@\" }"
377 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"}."
383 # -------------------------------------------------------------------------------------------------
385 # -------------------------------------------------------------------------------------------------
387 # Try binding widgets.
388 _zsh_highlight_bind_widgets ||
{
389 print
-r -- >&2 'zsh-syntax-highlighting: failed binding ZLE widgets, exiting.'
393 # Resolve highlighters directory location.
394 _zsh_highlight_load_highlighters
"${ZSH_HIGHLIGHT_HIGHLIGHTERS_DIR:-${${0:A}:h}/highlighters}" ||
{
395 print
-r -- >&2 'zsh-syntax-highlighting: failed loading highlighters, exiting.'
399 # Reset scratch variables when commandline is done.
400 _zsh_highlight_preexec_hook
()
402 typeset
-g _ZSH_HIGHLIGHT_PRIOR_BUFFER
=
403 typeset
-gi _ZSH_HIGHLIGHT_PRIOR_CURSOR
=
405 autoload
-U add-zsh-hook
406 add-zsh-hook preexec _zsh_highlight_preexec_hook
2>/dev
/null ||
{
407 print
-r -- >&2 'zsh-syntax-highlighting: failed loading add-zsh-hook.'
410 # Load zsh/parameter module if available
411 zmodload zsh
/parameter
2>/dev
/null || true
413 # Initialize the array of active highlighters if needed.
414 [[ $#ZSH_HIGHLIGHT_HIGHLIGHTERS -eq 0 ]] && ZSH_HIGHLIGHT_HIGHLIGHTERS
=(main
)
416 # Restore the aliases we unned
417 eval "$zsh_highlight__aliases"
418 builtin unset zsh_highlight__aliases