e4e44fa8b2c318013d60e9cfdcdf1bb667e4e542
[zsh.git] / .zsh / zsh-syntax-highlighting / zsh-syntax-highlighting.zsh
1 # -------------------------------------------------------------------------------------------------
2 # Copyright (c) 2010-2016 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 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.
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 # -------------------------------------------------------------------------------------------------
53 # Core highlighting update system
54 # -------------------------------------------------------------------------------------------------
55
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
61 else
62 zsh_highlight__pat_static_bug=true
63 fi
64
65 # Array declaring active highlighters names.
66 typeset -ga ZSH_HIGHLIGHT_HIGHLIGHTERS
67
68 # Update ZLE buffer syntax highlighting.
69 #
70 # Invokes each highlighter that needs updating.
71 # This function is supposed to be called whenever the ZLE state changes.
72 _zsh_highlight()
73 {
74 # Store the previous command return code to restore it whatever happens.
75 local ret=$?
76
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
82 region_highlight=()
83 return $ret
84 fi
85
86 setopt localoptions warncreateglobal
87 setopt localoptions noksharrays
88 local REPLY # don't leak $REPLY into global scope
89
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
93
94 # Do not highlight if there are pending inputs (copy/paste).
95 [[ $PENDING -gt 0 ]] && return $ret
96
97 # Reset region highlight to build it from scratch
98 typeset -ga region_highlight
99 region_highlight=();
100
101 {
102 local cache_place
103 local -a region_highlight_copy
104
105 # Select which highlighters in ZSH_HIGHLIGHT_HIGHLIGHTERS need to be invoked.
106 local highlighter; for highlighter in $ZSH_HIGHLIGHT_HIGHLIGHTERS; do
107
108 # eval cache place for current highlighter and prepare it
109 cache_place="_zsh_highlight__highlighter_${highlighter}_cache"
110 typeset -ga ${cache_place}
111
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
118
119 # save a copy, and cleanup region_highlight
120 region_highlight_copy=("${region_highlight[@]}")
121 region_highlight=()
122
123 # Execute highlighter and save result
124 {
125 "_zsh_highlight_highlighter_${highlighter}_paint"
126 } always {
127 eval "${cache_place}=(\"\${region_highlight[@]}\")"
128 }
129
130 # Restore saved region_highlight
131 region_highlight=("${region_highlight_copy[@]}")
132
133 fi
134
135 # Use value form cache if any cached
136 eval "region_highlight+=(\"\${${cache_place}[@]}\")"
137
138 done
139
140 # Re-apply zle_highlight settings
141
142 # region
143 if (( REGION_ACTIVE == 1 )); then
144 _zsh_highlight_apply_zle_highlight region standout "$MARK" "$CURSOR"
145 elif (( REGION_ACTIVE == 2 )); then
146 () {
147 local needle=$'\n'
148 integer min max
149 if (( MARK > CURSOR )) ; then
150 min=$CURSOR max=$MARK
151 else
152 min=$MARK max=$CURSOR
153 fi
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"
157 }
158 fi
159
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"
162
163 # isearch
164 (( $+ISEARCHMATCH_ACTIVE )) && (( ISEARCHMATCH_ACTIVE )) && _zsh_highlight_apply_zle_highlight isearch underline "$ISEARCHMATCH_START" "$ISEARCHMATCH_END"
165
166 # suffix
167 (( $+SUFFIX_ACTIVE )) && (( SUFFIX_ACTIVE )) && _zsh_highlight_apply_zle_highlight suffix bold "$SUFFIX_START" "$SUFFIX_END"
168
169
170 return $ret
171
172
173 } always {
174 typeset -g _ZSH_HIGHLIGHT_PRIOR_BUFFER="$BUFFER"
175 typeset -gi _ZSH_HIGHLIGHT_PRIOR_CURSOR=$CURSOR
176 }
177 }
178
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"
189
190 # read the relevant entry from zle_highlight
191 #
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}:*]-}"
196
197 if [[ -z "$region" ]]; then
198 # entry not specified at all, use default value
199 region=$default
200 else
201 # strip prefix
202 region="${region#${entry}:}"
203
204 # no highlighting when set to the empty string or to 'none'
205 if [[ -z "$region" ]] || [[ "$region" == none ]]; then
206 return
207 fi
208 fi
209
210 integer start end
211 if (( first < second )); then
212 start=$first end=$second
213 else
214 start=$second end=$first
215 fi
216 region_highlight+=("$start $end $region")
217 }
218
219
220 # -------------------------------------------------------------------------------------------------
221 # API/utility functions for highlighters
222 # -------------------------------------------------------------------------------------------------
223
224 # Array used by highlighters to declare user overridable styles.
225 typeset -gA ZSH_HIGHLIGHT_STYLES
226
227 # Whether the command line buffer has been modified or not.
228 #
229 # Returns 0 if the buffer has changed since _zsh_highlight was last called.
230 _zsh_highlight_buffer_modified()
231 {
232 [[ "${_ZSH_HIGHLIGHT_PRIOR_BUFFER:-}" != "$BUFFER" ]]
233 }
234
235 # Whether the cursor has moved or not.
236 #
237 # Returns 0 if the cursor has moved since _zsh_highlight was last called.
238 _zsh_highlight_cursor_moved()
239 {
240 [[ -n $CURSOR ]] && [[ -n ${_ZSH_HIGHLIGHT_PRIOR_CURSOR-} ]] && (($_ZSH_HIGHLIGHT_PRIOR_CURSOR != $CURSOR))
241 }
242
243 # Add a highlight defined by ZSH_HIGHLIGHT_STYLES.
244 #
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()
248 {
249 local -i start end
250 local highlight
251 start=$1
252 end=$2
253 shift 2
254 for highlight; do
255 if (( $+ZSH_HIGHLIGHT_STYLES[$highlight] )); then
256 region_highlight+=("$start $end $ZSH_HIGHLIGHT_STYLES[$highlight]")
257 break
258 fi
259 done
260 }
261
262 # -------------------------------------------------------------------------------------------------
263 # Setup functions
264 # -------------------------------------------------------------------------------------------------
265
266 # Helper for _zsh_highlight_bind_widgets
267 # $1 is name of widget to call
268 _zsh_highlight_call_widget()
269 {
270 builtin zle "$@" &&
271 _zsh_highlight
272 }
273
274 # Rebind all ZLE widgets to make them invoke _zsh_highlights.
275 _zsh_highlight_bind_widgets()
276 {
277 setopt localoptions noksharrays
278 typeset -F SECONDS
279 local prefix=orig-s$SECONDS-r$RANDOM # unique each time, in case we're sourced more than once
280
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.'
284 return 1
285 }
286
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)})
290
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)
295
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)
299
300 local cur_widget
301 for cur_widget in $widgets_to_bind; do
302 case ${widgets[$cur_widget]:-""} in
303
304 # Already rebound event: do nothing.
305 user:_zsh_highlight_widget_*);;
306
307 # The "eval"'s are required to make $cur_widget a closure: the value of the parameter at function
308 # definition time is used.
309 #
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.
312
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;;
317
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;;
322
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;;
326
327 # Incomplete or nonexistent widget: Bind to z-sy-h directly.
328 *)
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
332 else
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\`.)"
336 fi
337 esac
338 done
339 }
340
341 # Load highlighters from directory.
342 #
343 # Arguments:
344 # 1) Path to the highlighters directory.
345 _zsh_highlight_load_highlighters()
346 {
347 setopt localoptions noksharrays
348
349 # Check the directory exists.
350 [[ -d "$1" ]] || {
351 print -r -- >&2 "zsh-syntax-highlighting: highlighters directory ${(qq)1} not found."
352 return 1
353 }
354
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;
363 then
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;
367 then
368 # Old (0.4.x) function names
369 if false; then
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"
372 fi
373 # Make it work.
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 \"\$@\" }"
376 else
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"}."
378 fi
379 done
380 }
381
382
383 # -------------------------------------------------------------------------------------------------
384 # Setup
385 # -------------------------------------------------------------------------------------------------
386
387 # Try binding widgets.
388 _zsh_highlight_bind_widgets || {
389 print -r -- >&2 'zsh-syntax-highlighting: failed binding ZLE widgets, exiting.'
390 return 1
391 }
392
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.'
396 return 1
397 }
398
399 # Reset scratch variables when commandline is done.
400 _zsh_highlight_preexec_hook()
401 {
402 typeset -g _ZSH_HIGHLIGHT_PRIOR_BUFFER=
403 typeset -gi _ZSH_HIGHLIGHT_PRIOR_CURSOR=
404 }
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.'
408 }
409
410 # Load zsh/parameter module if available
411 zmodload zsh/parameter 2>/dev/null || true
412
413 # Initialize the array of active highlighters if needed.
414 [[ $#ZSH_HIGHLIGHT_HIGHLIGHTERS -eq 0 ]] && ZSH_HIGHLIGHT_HIGHLIGHTERS=(main)
415
416 # Restore the aliases we unned
417 eval "$zsh_highlight__aliases"
418 builtin unset zsh_highlight__aliases
419
420 # Set $?.
421 true