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 # -------------------------------------------------------------------------------------------------
31 # Set $0 to the expected value, regardless of functionargzero.
35 typeset
-g ZSH_HIGHLIGHT_VERSION
=$
(<"${0:A:h}"/.version
)
36 typeset
-g ZSH_HIGHLIGHT_REVISION
=$
(<"${0:A:h}"/.revision-hash
)
37 if [[ $ZSH_HIGHLIGHT_REVISION == \
$Format:* ]]; then
38 # When running from a source tree without 'make install', $ZSH_HIGHLIGHT_REVISION
39 # would be set to '$Format:%H$' literally. That's an invalid value, and obtaining
40 # the valid value (via `git rev-parse HEAD`, as Makefile does) might be costly, so:
41 ZSH_HIGHLIGHT_REVISION
=HEAD
45 # -------------------------------------------------------------------------------------------------
46 # Core highlighting update system
47 # -------------------------------------------------------------------------------------------------
49 # Array declaring active highlighters names.
50 typeset
-ga ZSH_HIGHLIGHT_HIGHLIGHTERS
52 # Update ZLE buffer syntax highlighting.
54 # Invokes each highlighter that needs updating.
55 # This function is supposed to be called whenever the ZLE state changes.
58 # Store the previous command return code to restore it whatever happens.
61 # Remove all highlighting in isearch, so that only the underlining done by zsh itself remains.
62 # For details see FAQ entry 'Why does syntax highlighting not work while searching history?'.
63 if [[ $WIDGET == zle-isearch-update
]] && ! (( $
+ISEARCHMATCH_ACTIVE
)); then
68 setopt localoptions warncreateglobal
69 setopt localoptions noksharrays
70 local REPLY
# don't leak $REPLY into global scope
72 # Do not highlight if there are more than 300 chars in the buffer. It's most
73 # likely a pasted command or a huge list of files in that case..
74 [[ -n ${ZSH_HIGHLIGHT_MAXLENGTH:-} ]] && [[ $#BUFFER -gt $ZSH_HIGHLIGHT_MAXLENGTH ]] && return $ret
76 # Do not highlight if there are pending inputs (copy/paste).
77 [[ $PENDING -gt 0 ]] && return $ret
79 # Reset region highlight to build it from scratch
80 typeset
-ga region_highlight
85 local -a region_highlight_copy
87 # Select which highlighters in ZSH_HIGHLIGHT_HIGHLIGHTERS need to be invoked.
88 local highlighter
; for highlighter
in $ZSH_HIGHLIGHT_HIGHLIGHTERS; do
90 # eval cache place for current highlighter and prepare it
91 cache_place
="_zsh_highlight__highlighter_${highlighter}_cache"
92 typeset
-ga ${cache_place}
94 # If highlighter needs to be invoked
95 if ! type "_zsh_highlight_highlighter_${highlighter}_predicate" >&/dev
/null
; then
96 echo "zsh-syntax-highlighting: warning: disabling the ${(qq)highlighter} highlighter as it has not been loaded" >&2
97 # TODO: use ${(b)} rather than ${(q)} if supported
98 ZSH_HIGHLIGHT_HIGHLIGHTERS
=( ${ZSH_HIGHLIGHT_HIGHLIGHTERS:#${highlighter}} )
99 elif "_zsh_highlight_highlighter_${highlighter}_predicate"; then
101 # save a copy, and cleanup region_highlight
102 region_highlight_copy
=("${region_highlight[@]}")
105 # Execute highlighter and save result
107 "_zsh_highlight_highlighter_${highlighter}_paint"
109 eval "${cache_place}=(\"\${region_highlight[@]}\")"
112 # Restore saved region_highlight
113 region_highlight
=("${region_highlight_copy[@]}")
117 # Use value form cache if any cached
118 eval "region_highlight+=(\"\${${cache_place}[@]}\")"
122 # Re-apply zle_highlight settings
125 if (( REGION_ACTIVE
== 1 )); then
126 _zsh_highlight_apply_zle_highlight region standout
"$MARK" "$CURSOR"
127 elif (( REGION_ACTIVE
== 2 )); then
131 if (( MARK
> CURSOR
)) ; then
132 min
=$CURSOR max
=$MARK
134 min
=$MARK max
=$CURSOR
136 (( min
= ${${BUFFER[1,$min]}[(I
)$needle]} ))
137 (( max
+= ${${BUFFER:($max-1)}[(i
)$needle]} - 1 ))
138 _zsh_highlight_apply_zle_highlight region standout
"$min" "$max"
142 # yank / paste (zsh-5.1.1 and newer)
143 (( $
+YANK_ACTIVE
)) && (( YANK_ACTIVE
)) && _zsh_highlight_apply_zle_highlight
paste standout
"$YANK_START" "$YANK_END"
146 (( $
+ISEARCHMATCH_ACTIVE
)) && (( ISEARCHMATCH_ACTIVE
)) && _zsh_highlight_apply_zle_highlight isearch underline
"$ISEARCHMATCH_START" "$ISEARCHMATCH_END"
149 (( $
+SUFFIX_ACTIVE
)) && (( SUFFIX_ACTIVE
)) && _zsh_highlight_apply_zle_highlight suffix bold
"$SUFFIX_START" "$SUFFIX_END"
156 typeset
-g _ZSH_HIGHLIGHT_PRIOR_BUFFER
="$BUFFER"
157 typeset
-gi _ZSH_HIGHLIGHT_PRIOR_CURSOR
=$CURSOR
161 # Apply highlighting based on entries in the zle_highlight array.
162 # This function takes four arguments:
163 # 1. The exact entry (no patterns) in the zle_highlight array:
164 # region, paste, isearch, or suffix
165 # 2. The default highlighting that should be applied if the entry is unset
166 # 3. and 4. Two integer values describing the beginning and end of the
167 # range. The order does not matter.
168 _zsh_highlight_apply_zle_highlight
() {
169 local entry
="$1" default
="$2"
170 integer first
="$3" second
="$4"
172 # read the relevant entry from zle_highlight
173 local region
="${zle_highlight[(r)${entry}:*]}"
175 if [[ -z "$region" ]]; then
176 # entry not specified at all, use default value
180 region
="${region#${entry}:}"
182 # no highlighting when set to the empty string or to 'none'
183 if [[ -z "$region" ]] ||
[[ "$region" == none
]]; then
189 if (( first
< second
)); then
190 start
=$first end
=$second
192 start
=$second end
=$first
194 region_highlight
+=("$start $end $region")
198 # -------------------------------------------------------------------------------------------------
199 # API/utility functions for highlighters
200 # -------------------------------------------------------------------------------------------------
202 # Array used by highlighters to declare user overridable styles.
203 typeset
-gA ZSH_HIGHLIGHT_STYLES
205 # Whether the command line buffer has been modified or not.
207 # Returns 0 if the buffer has changed since _zsh_highlight was last called.
208 _zsh_highlight_buffer_modified
()
210 [[ "${_ZSH_HIGHLIGHT_PRIOR_BUFFER:-}" != "$BUFFER" ]]
213 # Whether the cursor has moved or not.
215 # Returns 0 if the cursor has moved since _zsh_highlight was last called.
216 _zsh_highlight_cursor_moved
()
218 [[ -n $CURSOR ]] && [[ -n ${_ZSH_HIGHLIGHT_PRIOR_CURSOR-} ]] && (($_ZSH_HIGHLIGHT_PRIOR_CURSOR != $CURSOR))
221 # Add a highlight defined by ZSH_HIGHLIGHT_STYLES.
223 # Should be used by all highlighters aside from 'pattern' (cf. ZSH_HIGHLIGHT_PATTERN).
224 # Overwritten in tests/test-highlighting.zsh when testing.
225 _zsh_highlight_add_highlight
()
233 if (( $
+ZSH_HIGHLIGHT_STYLES
[$highlight] )); then
234 region_highlight
+=("$start $end $ZSH_HIGHLIGHT_STYLES[$highlight]")
240 # -------------------------------------------------------------------------------------------------
242 # -------------------------------------------------------------------------------------------------
244 # Helper for _zsh_highlight_bind_widgets
245 # $1 is name of widget to call
246 _zsh_highlight_call_widget
()
252 # Rebind all ZLE widgets to make them invoke _zsh_highlights.
253 _zsh_highlight_bind_widgets
()
255 setopt localoptions noksharrays
257 local prefix
=orig-s
$SECONDS-r$RANDOM # unique each time, in case we're sourced more than once
259 # Load ZSH module zsh/zleparameter, needed to override user defined widgets.
260 zmodload zsh
/zleparameter
2>/dev
/null ||
{
261 print
-r -- >&2 'zsh-syntax-highlighting: failed loading zsh/zleparameter.'
265 # Override ZLE widgets to make them invoke _zsh_highlight.
266 local -U widgets_to_bind
267 widgets_to_bind
=(${${(k)widgets}:#(.*|run-help|which-command|beep|set-local-history|yank)})
269 # Always wrap special zle-line-finish widget. This is needed to decide if the
270 # current line ends and special highlighting logic needs to be applied.
271 # E.g. remove cursor imprint, don't highlight partial paths, ...
272 widgets_to_bind
+=(zle-line-finish
)
274 # Always wrap special zle-isearch-update widget to be notified of updates in isearch.
275 # This is needed because we need to disable highlighting in that case.
276 widgets_to_bind
+=(zle-isearch-update
)
279 for cur_widget
in $widgets_to_bind; do
280 case $widgets[$cur_widget] in
282 # Already rebound event: do nothing.
283 user
:_zsh_highlight_widget_
*);;
285 # The "eval"'s are required to make $cur_widget a closure: the value of the parameter at function
286 # definition time is used.
288 # We can't use ${0/_zsh_highlight_widget_} because these widgets are always invoked with
289 # NO_function_argzero, regardless of the option's setting here.
291 # User defined widget: override and rebind old one with prefix "orig-".
292 user
:*) zle
-N $prefix-$cur_widget ${widgets[$cur_widget]#*:}
293 eval "_zsh_highlight_widget_${(q)prefix}-${(q)cur_widget}() { _zsh_highlight_call_widget ${(q)prefix}-${(q)cur_widget} -- \"\$@\" }"
294 zle
-N $cur_widget _zsh_highlight_widget_
$prefix-$cur_widget;;
296 # Completion widget: override and rebind old one with prefix "orig-".
297 completion
:*) zle
-C $prefix-$cur_widget ${${(s.:.)widgets[$cur_widget]}[2,3]}
298 eval "_zsh_highlight_widget_${(q)prefix}-${(q)cur_widget}() { _zsh_highlight_call_widget ${(q)prefix}-${(q)cur_widget} -- \"\$@\" }"
299 zle
-N $cur_widget _zsh_highlight_widget_
$prefix-$cur_widget;;
301 # Builtin widget: override and make it call the builtin ".widget".
302 builtin) eval "_zsh_highlight_widget_${(q)prefix}-${(q)cur_widget}() { _zsh_highlight_call_widget .${(q)cur_widget} -- \"\$@\" }"
303 zle
-N $cur_widget _zsh_highlight_widget_
$prefix-$cur_widget;;
305 # Incomplete or nonexistent widget: Bind to z-sy-h directly.
307 if [[ $cur_widget == zle-
* ]] && [[ -z $widgets[$cur_widget] ]]; then
308 _zsh_highlight_widget_
${cur_widget}() { :; _zsh_highlight
}
309 zle
-N $cur_widget _zsh_highlight_widget_
$cur_widget
311 # Default: unhandled case.
312 print
-r -- >&2 "zsh-syntax-highlighting: unhandled ZLE widget ${(qq)cur_widget}"
318 # Load highlighters from directory.
321 # 1) Path to the highlighters directory.
322 _zsh_highlight_load_highlighters
()
324 setopt localoptions noksharrays
326 # Check the directory exists.
328 print
-r -- >&2 "zsh-syntax-highlighting: highlighters directory ${(qq)1} not found."
332 # Load highlighters from highlighters directory and check they define required functions.
333 local highlighter highlighter_dir
334 for highlighter_dir
($1/*/); do
335 highlighter
="${highlighter_dir:t}"
336 [[ -f "$highlighter_dir/${highlighter}-highlighter.zsh" ]] &&
337 .
"$highlighter_dir/${highlighter}-highlighter.zsh"
338 if type "_zsh_highlight_highlighter_${highlighter}_paint" &> /dev
/null
&&
339 type "_zsh_highlight_highlighter_${highlighter}_predicate" &> /dev
/null
;
341 # New (0.5.0) function names
342 elif type "_zsh_highlight_${highlighter}_highlighter" &> /dev
/null
&&
343 type "_zsh_highlight_${highlighter}_highlighter_predicate" &> /dev
/null
;
345 # Old (0.4.x) function names
347 # TODO: only show this warning for plugin authors/maintainers, not for end users
348 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"
351 eval "_zsh_highlight_highlighter_${(q)highlighter}_paint() { _zsh_highlight_${(q)highlighter}_highlighter \"\$@\" }"
352 eval "_zsh_highlight_highlighter_${(q)highlighter}_predicate() { _zsh_highlight_${(q)highlighter}_highlighter_predicate \"\$@\" }"
354 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"}."
360 # -------------------------------------------------------------------------------------------------
362 # -------------------------------------------------------------------------------------------------
364 # Try binding widgets.
365 _zsh_highlight_bind_widgets ||
{
366 print
-r -- >&2 'zsh-syntax-highlighting: failed binding ZLE widgets, exiting.'
370 # Resolve highlighters directory location.
371 _zsh_highlight_load_highlighters
"${ZSH_HIGHLIGHT_HIGHLIGHTERS_DIR:-${${0:A}:h}/highlighters}" ||
{
372 print
-r -- >&@
'zsh-syntax-highlighting: failed loading highlighters, exiting.'
376 # Reset scratch variables when commandline is done.
377 _zsh_highlight_preexec_hook
()
379 typeset
-g _ZSH_HIGHLIGHT_PRIOR_BUFFER
=
380 typeset
-gi _ZSH_HIGHLIGHT_PRIOR_CURSOR
=
382 autoload
-U add-zsh-hook
383 add-zsh-hook preexec _zsh_highlight_preexec_hook
2>/dev
/null ||
{
384 print
-r -- >&2 'zsh-syntax-highlighting: failed loading add-zsh-hook.'
387 # Load zsh/parameter module if available
388 zmodload zsh
/parameter
2>/dev
/null || true
390 autoload
-U is-at-least
392 # Initialize the array of active highlighters if needed.
393 [[ $#ZSH_HIGHLIGHT_HIGHLIGHTERS -eq 0 ]] && ZSH_HIGHLIGHT_HIGHLIGHTERS
=(main
) || true