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.

281 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. unset ZSH_HIGHLIGHT_REVISION
  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 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. local REPLY # don't leak $REPLY into global scope
  61. # Do not highlight if there are more than 300 chars in the buffer. It's most
  62. # likely a pasted command or a huge list of files in that case..
  63. [[ -n ${ZSH_HIGHLIGHT_MAXLENGTH:-} ]] && [[ $#BUFFER -gt $ZSH_HIGHLIGHT_MAXLENGTH ]] && return $ret
  64. # Do not highlight if there are pending inputs (copy/paste).
  65. [[ $PENDING -gt 0 ]] && return $ret
  66. # Reset region highlight to build it from scratch
  67. typeset -ga region_highlight
  68. region_highlight=();
  69. {
  70. local cache_place
  71. local -a region_highlight_copy
  72. # Select which highlighters in ZSH_HIGHLIGHT_HIGHLIGHTERS need to be invoked.
  73. local highlighter; for highlighter in $ZSH_HIGHLIGHT_HIGHLIGHTERS; do
  74. # eval cache place for current highlighter and prepare it
  75. cache_place="_zsh_highlight_${highlighter}_highlighter_cache"
  76. typeset -ga ${cache_place}
  77. # If highlighter needs to be invoked
  78. if "_zsh_highlight_${highlighter}_highlighter_predicate"; then
  79. # save a copy, and cleanup region_highlight
  80. region_highlight_copy=("${region_highlight[@]}")
  81. region_highlight=()
  82. # Execute highlighter and save result
  83. {
  84. "_zsh_highlight_${highlighter}_highlighter"
  85. } always {
  86. eval "${cache_place}=(\"\${region_highlight[@]}\")"
  87. }
  88. # Restore saved region_highlight
  89. region_highlight=("${region_highlight_copy[@]}")
  90. fi
  91. # Use value form cache if any cached
  92. eval "region_highlight+=(\"\${${cache_place}[@]}\")"
  93. done
  94. # Re-apply zle_highlight settings
  95. () {
  96. if (( REGION_ACTIVE )) ; then
  97. # zle_highlight[region] defaults to 'standout' if unspecified
  98. local region="${${zle_highlight[(r)region:*]#region:}:-standout}"
  99. integer start end
  100. if (( MARK > CURSOR )) ; then
  101. start=$CURSOR end=$MARK
  102. else
  103. start=$MARK end=$CURSOR
  104. fi
  105. region_highlight+=("$start $end $region")
  106. fi
  107. }
  108. # YANK_ACTIVE is only available in zsh-5.1.1 and newer
  109. (( $+YANK_ACTIVE )) && () {
  110. if (( YANK_ACTIVE )) ; then
  111. # zle_highlight[paste] defaults to 'standout' if unspecified
  112. local paste="${${zle_highlight[(r)paste:*]#paste:}:-standout}"
  113. integer start end
  114. if (( YANK_END > YANK_START )) ; then
  115. start=$YANK_START end=$YANK_END
  116. else
  117. start=$YANK_END end=$YANK_START
  118. fi
  119. region_highlight+=("$start $end $paste")
  120. fi
  121. }
  122. return $ret
  123. } always {
  124. typeset -g _ZSH_HIGHLIGHT_PRIOR_BUFFER="$BUFFER"
  125. typeset -gi _ZSH_HIGHLIGHT_PRIOR_CURSOR=$CURSOR
  126. }
  127. }
  128. # -------------------------------------------------------------------------------------------------
  129. # API/utility functions for highlighters
  130. # -------------------------------------------------------------------------------------------------
  131. # Array used by highlighters to declare user overridable styles.
  132. typeset -gA ZSH_HIGHLIGHT_STYLES
  133. # Whether the command line buffer has been modified or not.
  134. #
  135. # Returns 0 if the buffer has changed since _zsh_highlight was last called.
  136. _zsh_highlight_buffer_modified()
  137. {
  138. [[ "${_ZSH_HIGHLIGHT_PRIOR_BUFFER:-}" != "$BUFFER" ]]
  139. }
  140. # Whether the cursor has moved or not.
  141. #
  142. # Returns 0 if the cursor has moved since _zsh_highlight was last called.
  143. _zsh_highlight_cursor_moved()
  144. {
  145. [[ -n $CURSOR ]] && [[ -n ${_ZSH_HIGHLIGHT_PRIOR_CURSOR-} ]] && (($_ZSH_HIGHLIGHT_PRIOR_CURSOR != $CURSOR))
  146. }
  147. # -------------------------------------------------------------------------------------------------
  148. # Setup functions
  149. # -------------------------------------------------------------------------------------------------
  150. # Helper for _zsh_highlight_bind_widgets
  151. # $1 is name of widget to call
  152. _zsh_highlight_call_widget()
  153. {
  154. builtin zle "$@" &&
  155. _zsh_highlight
  156. }
  157. # Rebind all ZLE widgets to make them invoke _zsh_highlights.
  158. _zsh_highlight_bind_widgets()
  159. {
  160. # Load ZSH module zsh/zleparameter, needed to override user defined widgets.
  161. zmodload zsh/zleparameter 2>/dev/null || {
  162. echo 'zsh-syntax-highlighting: failed loading zsh/zleparameter.' >&2
  163. return 1
  164. }
  165. # Override ZLE widgets to make them invoke _zsh_highlight.
  166. local cur_widget
  167. for cur_widget in ${${(f)"$(builtin zle -la)"}:#(.*|_*|orig-*|run-help|which-command|beep|set-local-history|yank)}; do
  168. case $widgets[$cur_widget] in
  169. # Already rebound event: do nothing.
  170. user:$cur_widget|user:_zsh_highlight_widget_*);;
  171. # User defined widget: override and rebind old one with prefix "orig-".
  172. user:*) eval "zle -N orig-$cur_widget ${widgets[$cur_widget]#*:}; \
  173. _zsh_highlight_widget_$cur_widget() { _zsh_highlight_call_widget orig-$cur_widget \"\$@\" }; \
  174. zle -N $cur_widget _zsh_highlight_widget_$cur_widget";;
  175. # Completion widget: override and rebind old one with prefix "orig-".
  176. completion:*) eval "zle -C orig-$cur_widget ${${widgets[$cur_widget]#*:}/:/ }; \
  177. _zsh_highlight_widget_$cur_widget() { _zsh_highlight_call_widget orig-$cur_widget \"\$@\" }; \
  178. zle -N $cur_widget _zsh_highlight_widget_$cur_widget";;
  179. # Builtin widget: override and make it call the builtin ".widget".
  180. builtin) eval "_zsh_highlight_widget_$cur_widget() { _zsh_highlight_call_widget .$cur_widget \"\$@\" }; \
  181. zle -N $cur_widget _zsh_highlight_widget_$cur_widget";;
  182. # Default: unhandled case.
  183. *) echo "zsh-syntax-highlighting: unhandled ZLE widget '$cur_widget'" >&2 ;;
  184. esac
  185. done
  186. }
  187. # Load highlighters from directory.
  188. #
  189. # Arguments:
  190. # 1) Path to the highlighters directory.
  191. _zsh_highlight_load_highlighters()
  192. {
  193. # Check the directory exists.
  194. [[ -d "$1" ]] || {
  195. echo "zsh-syntax-highlighting: highlighters directory '$1' not found." >&2
  196. return 1
  197. }
  198. # Load highlighters from highlighters directory and check they define required functions.
  199. local highlighter highlighter_dir
  200. for highlighter_dir ($1/*/); do
  201. highlighter="${highlighter_dir:t}"
  202. [[ -f "$highlighter_dir/${highlighter}-highlighter.zsh" ]] && {
  203. . "$highlighter_dir/${highlighter}-highlighter.zsh"
  204. type "_zsh_highlight_${highlighter}_highlighter" &> /dev/null &&
  205. type "_zsh_highlight_${highlighter}_highlighter_predicate" &> /dev/null || {
  206. 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
  207. }
  208. }
  209. done
  210. }
  211. # -------------------------------------------------------------------------------------------------
  212. # Setup
  213. # -------------------------------------------------------------------------------------------------
  214. # Try binding widgets.
  215. _zsh_highlight_bind_widgets || {
  216. echo 'zsh-syntax-highlighting: failed binding ZLE widgets, exiting.' >&2
  217. return 1
  218. }
  219. # Resolve highlighters directory location.
  220. _zsh_highlight_load_highlighters "${ZSH_HIGHLIGHT_HIGHLIGHTERS_DIR:-${${0:A}:h}/highlighters}" || {
  221. echo 'zsh-syntax-highlighting: failed loading highlighters, exiting.' >&2
  222. return 1
  223. }
  224. # Reset scratch variables when commandline is done.
  225. _zsh_highlight_preexec_hook()
  226. {
  227. typeset -g _ZSH_HIGHLIGHT_PRIOR_BUFFER=
  228. typeset -gi _ZSH_HIGHLIGHT_PRIOR_CURSOR=
  229. }
  230. autoload -U add-zsh-hook
  231. add-zsh-hook preexec _zsh_highlight_preexec_hook 2>/dev/null || {
  232. echo 'zsh-syntax-highlighting: failed loading add-zsh-hook.' >&2
  233. }
  234. # Initialize the array of active highlighters if needed.
  235. [[ $#ZSH_HIGHLIGHT_HIGHLIGHTERS -eq 0 ]] && ZSH_HIGHLIGHT_HIGHLIGHTERS=(main) || true