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.

286 regels
11 KiB

9 jaren geleden
  1. # -------------------------------------------------------------------------------------------------
  2. # Copyright (c) 2010-2015 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. () {
  97. if (( REGION_ACTIVE )) ; then
  98. # zle_highlight[region] defaults to 'standout' if unspecified
  99. local region="${${zle_highlight[(r)region:*]#region:}:-standout}"
  100. integer start end
  101. if (( MARK > CURSOR )) ; then
  102. start=$CURSOR end=$MARK
  103. else
  104. start=$MARK end=$CURSOR
  105. fi
  106. region_highlight+=("$start $end $region")
  107. fi
  108. }
  109. # YANK_ACTIVE is only available in zsh-5.1.1 and newer
  110. (( $+YANK_ACTIVE )) && () {
  111. if (( YANK_ACTIVE )) ; then
  112. # zle_highlight[paste] defaults to 'standout' if unspecified
  113. local paste="${${zle_highlight[(r)paste:*]#paste:}:-standout}"
  114. integer start end
  115. if (( YANK_END > YANK_START )) ; then
  116. start=$YANK_START end=$YANK_END
  117. else
  118. start=$YANK_END end=$YANK_START
  119. fi
  120. region_highlight+=("$start $end $paste")
  121. fi
  122. }
  123. return $ret
  124. } always {
  125. typeset -g _ZSH_HIGHLIGHT_PRIOR_BUFFER="$BUFFER"
  126. typeset -gi _ZSH_HIGHLIGHT_PRIOR_CURSOR=$CURSOR
  127. }
  128. }
  129. # -------------------------------------------------------------------------------------------------
  130. # API/utility functions for highlighters
  131. # -------------------------------------------------------------------------------------------------
  132. # Array used by highlighters to declare user overridable styles.
  133. typeset -gA ZSH_HIGHLIGHT_STYLES
  134. # Whether the command line buffer has been modified or not.
  135. #
  136. # Returns 0 if the buffer has changed since _zsh_highlight was last called.
  137. _zsh_highlight_buffer_modified()
  138. {
  139. [[ "${_ZSH_HIGHLIGHT_PRIOR_BUFFER:-}" != "$BUFFER" ]]
  140. }
  141. # Whether the cursor has moved or not.
  142. #
  143. # Returns 0 if the cursor has moved since _zsh_highlight was last called.
  144. _zsh_highlight_cursor_moved()
  145. {
  146. [[ -n $CURSOR ]] && [[ -n ${_ZSH_HIGHLIGHT_PRIOR_CURSOR-} ]] && (($_ZSH_HIGHLIGHT_PRIOR_CURSOR != $CURSOR))
  147. }
  148. # -------------------------------------------------------------------------------------------------
  149. # Setup functions
  150. # -------------------------------------------------------------------------------------------------
  151. # Helper for _zsh_highlight_bind_widgets
  152. # $1 is name of widget to call
  153. _zsh_highlight_call_widget()
  154. {
  155. builtin zle "$@" &&
  156. _zsh_highlight
  157. }
  158. # Rebind all ZLE widgets to make them invoke _zsh_highlights.
  159. _zsh_highlight_bind_widgets()
  160. {
  161. setopt localoptions noksharrays
  162. # Load ZSH module zsh/zleparameter, needed to override user defined widgets.
  163. zmodload zsh/zleparameter 2>/dev/null || {
  164. echo 'zsh-syntax-highlighting: failed loading zsh/zleparameter.' >&2
  165. return 1
  166. }
  167. # Override ZLE widgets to make them invoke _zsh_highlight.
  168. local cur_widget
  169. for cur_widget in ${${(f)"$(builtin zle -la)"}:#(.*|_*|orig-*|run-help|which-command|beep|set-local-history|yank)}; do
  170. case $widgets[$cur_widget] in
  171. # Already rebound event: do nothing.
  172. user:$cur_widget|user:_zsh_highlight_widget_*);;
  173. # User defined widget: override and rebind old one with prefix "orig-".
  174. user:*) eval "zle -N orig-$cur_widget ${widgets[$cur_widget]#*:}; \
  175. _zsh_highlight_widget_$cur_widget() { _zsh_highlight_call_widget orig-$cur_widget \"\$@\" }; \
  176. zle -N $cur_widget _zsh_highlight_widget_$cur_widget";;
  177. # Completion widget: override and rebind old one with prefix "orig-".
  178. completion:*) eval "zle -C orig-$cur_widget ${${widgets[$cur_widget]#*:}/:/ }; \
  179. _zsh_highlight_widget_$cur_widget() { _zsh_highlight_call_widget orig-$cur_widget \"\$@\" }; \
  180. zle -N $cur_widget _zsh_highlight_widget_$cur_widget";;
  181. # Builtin widget: override and make it call the builtin ".widget".
  182. builtin) eval "_zsh_highlight_widget_$cur_widget() { _zsh_highlight_call_widget .$cur_widget \"\$@\" }; \
  183. zle -N $cur_widget _zsh_highlight_widget_$cur_widget";;
  184. # Default: unhandled case.
  185. *) echo "zsh-syntax-highlighting: unhandled ZLE widget '$cur_widget'" >&2 ;;
  186. esac
  187. done
  188. }
  189. # Load highlighters from directory.
  190. #
  191. # Arguments:
  192. # 1) Path to the highlighters directory.
  193. _zsh_highlight_load_highlighters()
  194. {
  195. setopt localoptions noksharrays
  196. # Check the directory exists.
  197. [[ -d "$1" ]] || {
  198. echo "zsh-syntax-highlighting: highlighters directory '$1' not found." >&2
  199. return 1
  200. }
  201. # Load highlighters from highlighters directory and check they define required functions.
  202. local highlighter highlighter_dir
  203. for highlighter_dir ($1/*/); do
  204. highlighter="${highlighter_dir:t}"
  205. [[ -f "$highlighter_dir/${highlighter}-highlighter.zsh" ]] && {
  206. . "$highlighter_dir/${highlighter}-highlighter.zsh"
  207. type "_zsh_highlight_${highlighter}_highlighter" &> /dev/null &&
  208. type "_zsh_highlight_${highlighter}_highlighter_predicate" &> /dev/null || {
  209. 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
  210. }
  211. }
  212. done
  213. }
  214. # -------------------------------------------------------------------------------------------------
  215. # Setup
  216. # -------------------------------------------------------------------------------------------------
  217. # Try binding widgets.
  218. _zsh_highlight_bind_widgets || {
  219. echo 'zsh-syntax-highlighting: failed binding ZLE widgets, exiting.' >&2
  220. return 1
  221. }
  222. # Resolve highlighters directory location.
  223. _zsh_highlight_load_highlighters "${ZSH_HIGHLIGHT_HIGHLIGHTERS_DIR:-${${0:A}:h}/highlighters}" || {
  224. echo 'zsh-syntax-highlighting: failed loading highlighters, exiting.' >&2
  225. return 1
  226. }
  227. # Reset scratch variables when commandline is done.
  228. _zsh_highlight_preexec_hook()
  229. {
  230. typeset -g _ZSH_HIGHLIGHT_PRIOR_BUFFER=
  231. typeset -gi _ZSH_HIGHLIGHT_PRIOR_CURSOR=
  232. }
  233. autoload -U add-zsh-hook
  234. add-zsh-hook preexec _zsh_highlight_preexec_hook 2>/dev/null || {
  235. echo 'zsh-syntax-highlighting: failed loading add-zsh-hook.' >&2
  236. }
  237. # Initialize the array of active highlighters if needed.
  238. [[ $#ZSH_HIGHLIGHT_HIGHLIGHTERS -eq 0 ]] && ZSH_HIGHLIGHT_HIGHLIGHTERS=(main) || true