Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

440 rindas
17 KiB

  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. # First of all, ensure predictable parsing.
  30. zsh_highlight__aliases=`builtin alias -Lm '[^+]*'`
  31. # In zsh <= 5.2, `alias -L` emits aliases that begin with a plus sign ('alias -- +foo=42')
  32. # them without a '--' guard, so they don't round trip.
  33. #
  34. # Hence, we exclude them from unaliasing:
  35. builtin unalias -m '[^+]*'
  36. # Set $0 to the expected value, regardless of functionargzero.
  37. 0=${(%):-%N}
  38. if true; then
  39. # $0 is reliable
  40. typeset -g ZSH_HIGHLIGHT_VERSION=$(<"${0:A:h}"/.version)
  41. typeset -g ZSH_HIGHLIGHT_REVISION=$(<"${0:A:h}"/.revision-hash)
  42. if [[ $ZSH_HIGHLIGHT_REVISION == \$Format:* ]]; then
  43. # When running from a source tree without 'make install', $ZSH_HIGHLIGHT_REVISION
  44. # would be set to '$Format:%H$' literally. That's an invalid value, and obtaining
  45. # the valid value (via `git rev-parse HEAD`, as Makefile does) might be costly, so:
  46. ZSH_HIGHLIGHT_REVISION=HEAD
  47. fi
  48. fi
  49. # -------------------------------------------------------------------------------------------------
  50. # Core highlighting update system
  51. # -------------------------------------------------------------------------------------------------
  52. # Use workaround for bug in ZSH?
  53. # zsh-users/zsh@48cadf4 http://www.zsh.org/mla/workers//2017/msg00034.html
  54. autoload -Uz is-at-least
  55. if is-at-least 5.4; then
  56. zsh_highlight__pat_static_bug=false
  57. else
  58. zsh_highlight__pat_static_bug=true
  59. fi
  60. # Array declaring active highlighters names.
  61. typeset -ga ZSH_HIGHLIGHT_HIGHLIGHTERS
  62. # Update ZLE buffer syntax highlighting.
  63. #
  64. # Invokes each highlighter that needs updating.
  65. # This function is supposed to be called whenever the ZLE state changes.
  66. _zsh_highlight()
  67. {
  68. # Store the previous command return code to restore it whatever happens.
  69. local ret=$?
  70. # Remove all highlighting in isearch, so that only the underlining done by zsh itself remains.
  71. # For details see FAQ entry 'Why does syntax highlighting not work while searching history?'.
  72. # This disables highlighting during isearch (for reasons explained in README.md) unless zsh is new enough
  73. # and doesn't have the pattern matching bug
  74. if [[ $WIDGET == zle-isearch-update ]] && { $zsh_highlight__pat_static_bug || ! (( $+ISEARCHMATCH_ACTIVE )) }; then
  75. region_highlight=()
  76. return $ret
  77. fi
  78. # Before we 'emulate -L', save the user's options
  79. local -A zsyh_user_options
  80. if zmodload -e zsh/parameter; then
  81. zsyh_user_options=("${(@kv)options}")
  82. else
  83. local canonical_options onoff option raw_options
  84. raw_options=(${(f)"$(emulate -R zsh; set -o)"})
  85. canonical_options=(${${${(M)raw_options:#*off}%% *}#no} ${${(M)raw_options:#*on}%% *})
  86. for option in $canonical_options; do
  87. [[ -o $option ]]
  88. # This variable cannot be eliminated c.f. workers/42101.
  89. onoff=${${=:-off on}[2-$?]}
  90. zsyh_user_options+=($option $onoff)
  91. done
  92. fi
  93. typeset -r zsyh_user_options
  94. emulate -L zsh
  95. setopt localoptions warncreateglobal
  96. local REPLY # don't leak $REPLY into global scope
  97. # Do not highlight if there are more than 300 chars in the buffer. It's most
  98. # likely a pasted command or a huge list of files in that case..
  99. [[ -n ${ZSH_HIGHLIGHT_MAXLENGTH:-} ]] && [[ $#BUFFER -gt $ZSH_HIGHLIGHT_MAXLENGTH ]] && return $ret
  100. # Do not highlight if there are pending inputs (copy/paste).
  101. [[ $PENDING -gt 0 ]] && return $ret
  102. # Reset region highlight to build it from scratch
  103. typeset -ga region_highlight
  104. region_highlight=();
  105. {
  106. local cache_place
  107. local -a region_highlight_copy
  108. # Select which highlighters in ZSH_HIGHLIGHT_HIGHLIGHTERS need to be invoked.
  109. local highlighter; for highlighter in $ZSH_HIGHLIGHT_HIGHLIGHTERS; do
  110. # eval cache place for current highlighter and prepare it
  111. cache_place="_zsh_highlight__highlighter_${highlighter}_cache"
  112. typeset -ga ${cache_place}
  113. # If highlighter needs to be invoked
  114. if ! type "_zsh_highlight_highlighter_${highlighter}_predicate" >&/dev/null; then
  115. echo "zsh-syntax-highlighting: warning: disabling the ${(qq)highlighter} highlighter as it has not been loaded" >&2
  116. # TODO: use ${(b)} rather than ${(q)} if supported
  117. ZSH_HIGHLIGHT_HIGHLIGHTERS=( ${ZSH_HIGHLIGHT_HIGHLIGHTERS:#${highlighter}} )
  118. elif "_zsh_highlight_highlighter_${highlighter}_predicate"; then
  119. # save a copy, and cleanup region_highlight
  120. region_highlight_copy=("${region_highlight[@]}")
  121. region_highlight=()
  122. # Execute highlighter and save result
  123. {
  124. "_zsh_highlight_highlighter_${highlighter}_paint"
  125. } always {
  126. : ${(AP)cache_place::="${region_highlight[@]}"}
  127. }
  128. # Restore saved region_highlight
  129. region_highlight=("${region_highlight_copy[@]}")
  130. fi
  131. # Use value form cache if any cached
  132. region_highlight+=("${(@P)cache_place}")
  133. done
  134. # Re-apply zle_highlight settings
  135. # region
  136. if (( REGION_ACTIVE == 1 )); then
  137. _zsh_highlight_apply_zle_highlight region standout "$MARK" "$CURSOR"
  138. elif (( REGION_ACTIVE == 2 )); then
  139. () {
  140. local needle=$'\n'
  141. integer min max
  142. if (( MARK > CURSOR )) ; then
  143. min=$CURSOR max=$MARK
  144. else
  145. min=$MARK max=$CURSOR
  146. fi
  147. # CURSOR and MARK are 0 indexed between letters like region_highlight
  148. # Do not include the newline in the highlight
  149. (( min = ${BUFFER[(Ib:min:)$needle]} ))
  150. (( max = ${BUFFER[(ib:max:)$needle]} - 1 ))
  151. _zsh_highlight_apply_zle_highlight region standout "$min" "$max"
  152. }
  153. fi
  154. # yank / paste (zsh-5.1.1 and newer)
  155. (( $+YANK_ACTIVE )) && (( YANK_ACTIVE )) && _zsh_highlight_apply_zle_highlight paste standout "$YANK_START" "$YANK_END"
  156. # isearch
  157. (( $+ISEARCHMATCH_ACTIVE )) && (( ISEARCHMATCH_ACTIVE )) && _zsh_highlight_apply_zle_highlight isearch underline "$ISEARCHMATCH_START" "$ISEARCHMATCH_END"
  158. # suffix
  159. (( $+SUFFIX_ACTIVE )) && (( SUFFIX_ACTIVE )) && _zsh_highlight_apply_zle_highlight suffix bold "$SUFFIX_START" "$SUFFIX_END"
  160. return $ret
  161. } always {
  162. typeset -g _ZSH_HIGHLIGHT_PRIOR_BUFFER="$BUFFER"
  163. typeset -gi _ZSH_HIGHLIGHT_PRIOR_CURSOR=$CURSOR
  164. }
  165. }
  166. # Apply highlighting based on entries in the zle_highlight array.
  167. # This function takes four arguments:
  168. # 1. The exact entry (no patterns) in the zle_highlight array:
  169. # region, paste, isearch, or suffix
  170. # 2. The default highlighting that should be applied if the entry is unset
  171. # 3. and 4. Two integer values describing the beginning and end of the
  172. # range. The order does not matter.
  173. _zsh_highlight_apply_zle_highlight() {
  174. local entry="$1" default="$2"
  175. integer first="$3" second="$4"
  176. # read the relevant entry from zle_highlight
  177. #
  178. # ### In zsh≥5.0.8 we'd use ${(b)entry}, but we support older zsh's, so we don't
  179. # ### add (b). The only effect is on the failure mode for callers that violate
  180. # ### the precondition.
  181. local region="${zle_highlight[(r)${entry}:*]-}"
  182. if [[ -z "$region" ]]; then
  183. # entry not specified at all, use default value
  184. region=$default
  185. else
  186. # strip prefix
  187. region="${region#${entry}:}"
  188. # no highlighting when set to the empty string or to 'none'
  189. if [[ -z "$region" ]] || [[ "$region" == none ]]; then
  190. return
  191. fi
  192. fi
  193. integer start end
  194. if (( first < second )); then
  195. start=$first end=$second
  196. else
  197. start=$second end=$first
  198. fi
  199. region_highlight+=("$start $end $region")
  200. }
  201. # -------------------------------------------------------------------------------------------------
  202. # API/utility functions for highlighters
  203. # -------------------------------------------------------------------------------------------------
  204. # Array used by highlighters to declare user overridable styles.
  205. typeset -gA ZSH_HIGHLIGHT_STYLES
  206. # Whether the command line buffer has been modified or not.
  207. #
  208. # Returns 0 if the buffer has changed since _zsh_highlight was last called.
  209. _zsh_highlight_buffer_modified()
  210. {
  211. [[ "${_ZSH_HIGHLIGHT_PRIOR_BUFFER:-}" != "$BUFFER" ]]
  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. # Add a highlight defined by ZSH_HIGHLIGHT_STYLES.
  221. #
  222. # Should be used by all highlighters aside from 'pattern' (cf. ZSH_HIGHLIGHT_PATTERN).
  223. # Overwritten in tests/test-highlighting.zsh when testing.
  224. _zsh_highlight_add_highlight()
  225. {
  226. local -i start end
  227. local highlight
  228. start=$1
  229. end=$2
  230. shift 2
  231. for highlight; do
  232. if (( $+ZSH_HIGHLIGHT_STYLES[$highlight] )); then
  233. region_highlight+=("$start $end $ZSH_HIGHLIGHT_STYLES[$highlight]")
  234. break
  235. fi
  236. done
  237. }
  238. # -------------------------------------------------------------------------------------------------
  239. # Setup functions
  240. # -------------------------------------------------------------------------------------------------
  241. # Helper for _zsh_highlight_bind_widgets
  242. # $1 is name of widget to call
  243. _zsh_highlight_call_widget()
  244. {
  245. builtin zle "$@" &&
  246. _zsh_highlight
  247. }
  248. # Rebind all ZLE widgets to make them invoke _zsh_highlights.
  249. _zsh_highlight_bind_widgets()
  250. {
  251. setopt localoptions noksharrays
  252. typeset -F SECONDS
  253. local prefix=orig-s$SECONDS-r$RANDOM # unique each time, in case we're sourced more than once
  254. # Load ZSH module zsh/zleparameter, needed to override user defined widgets.
  255. zmodload zsh/zleparameter 2>/dev/null || {
  256. print -r -- >&2 'zsh-syntax-highlighting: failed loading zsh/zleparameter.'
  257. return 1
  258. }
  259. # Override ZLE widgets to make them invoke _zsh_highlight.
  260. local -U widgets_to_bind
  261. widgets_to_bind=(${${(k)widgets}:#(.*|run-help|which-command|beep|set-local-history|yank|yank-pop)})
  262. # Always wrap special zle-line-finish widget. This is needed to decide if the
  263. # current line ends and special highlighting logic needs to be applied.
  264. # E.g. remove cursor imprint, don't highlight partial paths, ...
  265. widgets_to_bind+=(zle-line-finish)
  266. # Always wrap special zle-isearch-update widget to be notified of updates in isearch.
  267. # This is needed because we need to disable highlighting in that case.
  268. widgets_to_bind+=(zle-isearch-update)
  269. local cur_widget
  270. for cur_widget in $widgets_to_bind; do
  271. case ${widgets[$cur_widget]:-""} in
  272. # Already rebound event: do nothing.
  273. user:_zsh_highlight_widget_*);;
  274. # The "eval"'s are required to make $cur_widget a closure: the value of the parameter at function
  275. # definition time is used.
  276. #
  277. # We can't use ${0/_zsh_highlight_widget_} because these widgets are always invoked with
  278. # NO_function_argzero, regardless of the option's setting here.
  279. # User defined widget: override and rebind old one with prefix "orig-".
  280. user:*) zle -N $prefix-$cur_widget ${widgets[$cur_widget]#*:}
  281. eval "_zsh_highlight_widget_${(q)prefix}-${(q)cur_widget}() { _zsh_highlight_call_widget ${(q)prefix}-${(q)cur_widget} -- \"\$@\" }"
  282. zle -N $cur_widget _zsh_highlight_widget_$prefix-$cur_widget;;
  283. # Completion widget: override and rebind old one with prefix "orig-".
  284. completion:*) zle -C $prefix-$cur_widget ${${(s.:.)widgets[$cur_widget]}[2,3]}
  285. eval "_zsh_highlight_widget_${(q)prefix}-${(q)cur_widget}() { _zsh_highlight_call_widget ${(q)prefix}-${(q)cur_widget} -- \"\$@\" }"
  286. zle -N $cur_widget _zsh_highlight_widget_$prefix-$cur_widget;;
  287. # Builtin widget: override and make it call the builtin ".widget".
  288. builtin) eval "_zsh_highlight_widget_${(q)prefix}-${(q)cur_widget}() { _zsh_highlight_call_widget .${(q)cur_widget} -- \"\$@\" }"
  289. zle -N $cur_widget _zsh_highlight_widget_$prefix-$cur_widget;;
  290. # Incomplete or nonexistent widget: Bind to z-sy-h directly.
  291. *)
  292. if [[ $cur_widget == zle-* ]] && (( ! ${+widgets[$cur_widget]} )); then
  293. _zsh_highlight_widget_${cur_widget}() { :; _zsh_highlight }
  294. zle -N $cur_widget _zsh_highlight_widget_$cur_widget
  295. else
  296. # Default: unhandled case.
  297. print -r -- >&2 "zsh-syntax-highlighting: unhandled ZLE widget ${(qq)cur_widget}"
  298. 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\`.)"
  299. fi
  300. esac
  301. done
  302. }
  303. # Load highlighters from directory.
  304. #
  305. # Arguments:
  306. # 1) Path to the highlighters directory.
  307. _zsh_highlight_load_highlighters()
  308. {
  309. setopt localoptions noksharrays
  310. # Check the directory exists.
  311. [[ -d "$1" ]] || {
  312. print -r -- >&2 "zsh-syntax-highlighting: highlighters directory ${(qq)1} not found."
  313. return 1
  314. }
  315. # Load highlighters from highlighters directory and check they define required functions.
  316. local highlighter highlighter_dir
  317. for highlighter_dir ($1/*/(/)); do
  318. highlighter="${highlighter_dir:t}"
  319. [[ -f "$highlighter_dir${highlighter}-highlighter.zsh" ]] &&
  320. . "$highlighter_dir${highlighter}-highlighter.zsh"
  321. if type "_zsh_highlight_highlighter_${highlighter}_paint" &> /dev/null &&
  322. type "_zsh_highlight_highlighter_${highlighter}_predicate" &> /dev/null;
  323. then
  324. # New (0.5.0) function names
  325. elif type "_zsh_highlight_${highlighter}_highlighter" &> /dev/null &&
  326. type "_zsh_highlight_${highlighter}_highlighter_predicate" &> /dev/null;
  327. then
  328. # Old (0.4.x) function names
  329. if false; then
  330. # TODO: only show this warning for plugin authors/maintainers, not for end users
  331. 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"
  332. fi
  333. # Make it work.
  334. eval "_zsh_highlight_highlighter_${(q)highlighter}_paint() { _zsh_highlight_${(q)highlighter}_highlighter \"\$@\" }"
  335. eval "_zsh_highlight_highlighter_${(q)highlighter}_predicate() { _zsh_highlight_${(q)highlighter}_highlighter_predicate \"\$@\" }"
  336. else
  337. 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"}."
  338. fi
  339. done
  340. }
  341. # -------------------------------------------------------------------------------------------------
  342. # Setup
  343. # -------------------------------------------------------------------------------------------------
  344. # Try binding widgets.
  345. _zsh_highlight_bind_widgets || {
  346. print -r -- >&2 'zsh-syntax-highlighting: failed binding ZLE widgets, exiting.'
  347. return 1
  348. }
  349. # Resolve highlighters directory location.
  350. _zsh_highlight_load_highlighters "${ZSH_HIGHLIGHT_HIGHLIGHTERS_DIR:-${${0:A}:h}/highlighters}" || {
  351. print -r -- >&2 'zsh-syntax-highlighting: failed loading highlighters, exiting.'
  352. return 1
  353. }
  354. # Reset scratch variables when commandline is done.
  355. _zsh_highlight_preexec_hook()
  356. {
  357. typeset -g _ZSH_HIGHLIGHT_PRIOR_BUFFER=
  358. typeset -gi _ZSH_HIGHLIGHT_PRIOR_CURSOR=
  359. }
  360. autoload -Uz add-zsh-hook
  361. add-zsh-hook preexec _zsh_highlight_preexec_hook 2>/dev/null || {
  362. print -r -- >&2 'zsh-syntax-highlighting: failed loading add-zsh-hook.'
  363. }
  364. # Load zsh/parameter module if available
  365. zmodload zsh/parameter 2>/dev/null || true
  366. # Initialize the array of active highlighters if needed.
  367. [[ $#ZSH_HIGHLIGHT_HIGHLIGHTERS -eq 0 ]] && ZSH_HIGHLIGHT_HIGHLIGHTERS=(main)
  368. # Restore the aliases we unned
  369. eval "$zsh_highlight__aliases"
  370. builtin unset zsh_highlight__aliases
  371. # Set $?.
  372. true