Commit missing plugin file
[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
31 # Set $0 to the expected value, regardless of functionargzero.
32 0=${(%):-%N}
33 if true; then
34 # $0 is reliable
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
42 fi
43 fi
44
45 # -------------------------------------------------------------------------------------------------
46 # Core highlighting update system
47 # -------------------------------------------------------------------------------------------------
48
49 # Array declaring active highlighters names.
50 typeset -ga ZSH_HIGHLIGHT_HIGHLIGHTERS
51
52 # Update ZLE buffer syntax highlighting.
53 #
54 # Invokes each highlighter that needs updating.
55 # This function is supposed to be called whenever the ZLE state changes.
56 _zsh_highlight()
57 {
58 # Store the previous command return code to restore it whatever happens.
59 local ret=$?
60
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
64 region_highlight=()
65 return $ret
66 fi
67
68 setopt localoptions warncreateglobal
69 setopt localoptions noksharrays
70 local REPLY # don't leak $REPLY into global scope
71
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
75
76 # Do not highlight if there are pending inputs (copy/paste).
77 [[ $PENDING -gt 0 ]] && return $ret
78
79 # Reset region highlight to build it from scratch
80 typeset -ga region_highlight
81 region_highlight=();
82
83 {
84 local cache_place
85 local -a region_highlight_copy
86
87 # Select which highlighters in ZSH_HIGHLIGHT_HIGHLIGHTERS need to be invoked.
88 local highlighter; for highlighter in $ZSH_HIGHLIGHT_HIGHLIGHTERS; do
89
90 # eval cache place for current highlighter and prepare it
91 cache_place="_zsh_highlight__highlighter_${highlighter}_cache"
92 typeset -ga ${cache_place}
93
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
100
101 # save a copy, and cleanup region_highlight
102 region_highlight_copy=("${region_highlight[@]}")
103 region_highlight=()
104
105 # Execute highlighter and save result
106 {
107 "_zsh_highlight_highlighter_${highlighter}_paint"
108 } always {
109 eval "${cache_place}=(\"\${region_highlight[@]}\")"
110 }
111
112 # Restore saved region_highlight
113 region_highlight=("${region_highlight_copy[@]}")
114
115 fi
116
117 # Use value form cache if any cached
118 eval "region_highlight+=(\"\${${cache_place}[@]}\")"
119
120 done
121
122 # Re-apply zle_highlight settings
123
124 # region
125 if (( REGION_ACTIVE == 1 )); then
126 _zsh_highlight_apply_zle_highlight region standout "$MARK" "$CURSOR"
127 elif (( REGION_ACTIVE == 2 )); then
128 () {
129 local needle=$'\n'
130 integer min max
131 if (( MARK > CURSOR )) ; then
132 min=$CURSOR max=$MARK
133 else
134 min=$MARK max=$CURSOR
135 fi
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"
139 }
140 fi
141
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"
144
145 # isearch
146 (( $+ISEARCHMATCH_ACTIVE )) && (( ISEARCHMATCH_ACTIVE )) && _zsh_highlight_apply_zle_highlight isearch underline "$ISEARCHMATCH_START" "$ISEARCHMATCH_END"
147
148 # suffix
149 (( $+SUFFIX_ACTIVE )) && (( SUFFIX_ACTIVE )) && _zsh_highlight_apply_zle_highlight suffix bold "$SUFFIX_START" "$SUFFIX_END"
150
151
152 return $ret
153
154
155 } always {
156 typeset -g _ZSH_HIGHLIGHT_PRIOR_BUFFER="$BUFFER"
157 typeset -gi _ZSH_HIGHLIGHT_PRIOR_CURSOR=$CURSOR
158 }
159 }
160
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"
171
172 # read the relevant entry from zle_highlight
173 local region="${zle_highlight[(r)${entry}:*]}"
174
175 if [[ -z "$region" ]]; then
176 # entry not specified at all, use default value
177 region=$default
178 else
179 # strip prefix
180 region="${region#${entry}:}"
181
182 # no highlighting when set to the empty string or to 'none'
183 if [[ -z "$region" ]] || [[ "$region" == none ]]; then
184 return
185 fi
186 fi
187
188 integer start end
189 if (( first < second )); then
190 start=$first end=$second
191 else
192 start=$second end=$first
193 fi
194 region_highlight+=("$start $end $region")
195 }
196
197
198 # -------------------------------------------------------------------------------------------------
199 # API/utility functions for highlighters
200 # -------------------------------------------------------------------------------------------------
201
202 # Array used by highlighters to declare user overridable styles.
203 typeset -gA ZSH_HIGHLIGHT_STYLES
204
205 # Whether the command line buffer has been modified or not.
206 #
207 # Returns 0 if the buffer has changed since _zsh_highlight was last called.
208 _zsh_highlight_buffer_modified()
209 {
210 [[ "${_ZSH_HIGHLIGHT_PRIOR_BUFFER:-}" != "$BUFFER" ]]
211 }
212
213 # Whether the cursor has moved or not.
214 #
215 # Returns 0 if the cursor has moved since _zsh_highlight was last called.
216 _zsh_highlight_cursor_moved()
217 {
218 [[ -n $CURSOR ]] && [[ -n ${_ZSH_HIGHLIGHT_PRIOR_CURSOR-} ]] && (($_ZSH_HIGHLIGHT_PRIOR_CURSOR != $CURSOR))
219 }
220
221 # Add a highlight defined by ZSH_HIGHLIGHT_STYLES.
222 #
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()
226 {
227 local -i start end
228 local highlight
229 start=$1
230 end=$2
231 shift 2
232 for highlight; do
233 if (( $+ZSH_HIGHLIGHT_STYLES[$highlight] )); then
234 region_highlight+=("$start $end $ZSH_HIGHLIGHT_STYLES[$highlight]")
235 break
236 fi
237 done
238 }
239
240 # -------------------------------------------------------------------------------------------------
241 # Setup functions
242 # -------------------------------------------------------------------------------------------------
243
244 # Helper for _zsh_highlight_bind_widgets
245 # $1 is name of widget to call
246 _zsh_highlight_call_widget()
247 {
248 builtin zle "$@" &&
249 _zsh_highlight
250 }
251
252 # Rebind all ZLE widgets to make them invoke _zsh_highlights.
253 _zsh_highlight_bind_widgets()
254 {
255 setopt localoptions noksharrays
256 typeset -F SECONDS
257 local prefix=orig-s$SECONDS-r$RANDOM # unique each time, in case we're sourced more than once
258
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.'
262 return 1
263 }
264
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)})
268
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)
273
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)
277
278 local cur_widget
279 for cur_widget in $widgets_to_bind; do
280 case $widgets[$cur_widget] in
281
282 # Already rebound event: do nothing.
283 user:_zsh_highlight_widget_*);;
284
285 # The "eval"'s are required to make $cur_widget a closure: the value of the parameter at function
286 # definition time is used.
287 #
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.
290
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;;
295
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;;
300
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;;
304
305 # Incomplete or nonexistent widget: Bind to z-sy-h directly.
306 *)
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
310 else
311 # Default: unhandled case.
312 print -r -- >&2 "zsh-syntax-highlighting: unhandled ZLE widget ${(qq)cur_widget}"
313 fi
314 esac
315 done
316 }
317
318 # Load highlighters from directory.
319 #
320 # Arguments:
321 # 1) Path to the highlighters directory.
322 _zsh_highlight_load_highlighters()
323 {
324 setopt localoptions noksharrays
325
326 # Check the directory exists.
327 [[ -d "$1" ]] || {
328 print -r -- >&2 "zsh-syntax-highlighting: highlighters directory ${(qq)1} not found."
329 return 1
330 }
331
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;
340 then
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;
344 then
345 # Old (0.4.x) function names
346 if false; then
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"
349 fi
350 # Make it work.
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 \"\$@\" }"
353 else
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"}."
355 fi
356 done
357 }
358
359
360 # -------------------------------------------------------------------------------------------------
361 # Setup
362 # -------------------------------------------------------------------------------------------------
363
364 # Try binding widgets.
365 _zsh_highlight_bind_widgets || {
366 print -r -- >&2 'zsh-syntax-highlighting: failed binding ZLE widgets, exiting.'
367 return 1
368 }
369
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.'
373 return 1
374 }
375
376 # Reset scratch variables when commandline is done.
377 _zsh_highlight_preexec_hook()
378 {
379 typeset -g _ZSH_HIGHLIGHT_PRIOR_BUFFER=
380 typeset -gi _ZSH_HIGHLIGHT_PRIOR_CURSOR=
381 }
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.'
385 }
386
387 # Load zsh/parameter module if available
388 zmodload zsh/parameter 2>/dev/null || true
389
390 autoload -U is-at-least
391
392 # Initialize the array of active highlighters if needed.
393 [[ $#ZSH_HIGHLIGHT_HIGHLIGHTERS -eq 0 ]] && ZSH_HIGHLIGHT_HIGHLIGHTERS=(main) || true