選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

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