You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

335 lines
13 KiB

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