sudo.plugin.zsh 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. # ------------------------------------------------------------------------------
  2. # Description
  3. # -----------
  4. #
  5. # sudo or sudoedit will be inserted before the command
  6. #
  7. # ------------------------------------------------------------------------------
  8. # Authors
  9. # -------
  10. #
  11. # * Dongweiming <ciici123@gmail.com>
  12. # * Subhaditya Nath <github.com/subnut>
  13. # * Marc Cornellà <github.com/mcornella>
  14. #
  15. # ------------------------------------------------------------------------------
  16. __sudo-replace-buffer() {
  17. local old=$1 new=$2 space=${2:+ }
  18. if [[ ${#LBUFFER} -le ${#old} ]]; then
  19. RBUFFER="${space}${BUFFER#$old }"
  20. LBUFFER="${new}"
  21. else
  22. LBUFFER="${new}${space}${LBUFFER#$old }"
  23. fi
  24. }
  25. sudo-command-line() {
  26. [[ -z $BUFFER ]] && LBUFFER="$(fc -ln -1)"
  27. # Save beginning space
  28. local WHITESPACE=""
  29. if [[ ${LBUFFER:0:1} = " " ]]; then
  30. WHITESPACE=" "
  31. LBUFFER="${LBUFFER:1}"
  32. fi
  33. # Get the first part of the typed command and check if it's an alias to $EDITOR
  34. # If so, locally change $EDITOR to the alias so that it matches below
  35. if [[ -n "$EDITOR" ]]; then
  36. local cmd="${${(Az)BUFFER}[1]}"
  37. if [[ "${aliases[$cmd]} " = (\$EDITOR|$EDITOR)\ * ]]; then
  38. local EDITOR="$cmd"
  39. fi
  40. fi
  41. if [[ -n $EDITOR && $BUFFER = $EDITOR\ * ]]; then
  42. __sudo-replace-buffer "$EDITOR" "sudoedit"
  43. elif [[ -n $EDITOR && $BUFFER = \$EDITOR\ * ]]; then
  44. __sudo-replace-buffer "\$EDITOR" "sudoedit"
  45. elif [[ $BUFFER = sudoedit\ * ]]; then
  46. __sudo-replace-buffer "sudoedit" "$EDITOR"
  47. elif [[ $BUFFER = sudo\ * ]]; then
  48. __sudo-replace-buffer "sudo" ""
  49. else
  50. LBUFFER="sudo $LBUFFER"
  51. fi
  52. # Preserve beginning space
  53. LBUFFER="${WHITESPACE}${LBUFFER}"
  54. }
  55. zle -N sudo-command-line
  56. # Defined shortcut keys: [Esc] [Esc]
  57. bindkey -M emacs '\e\e' sudo-command-line
  58. bindkey -M vicmd '\e\e' sudo-command-line
  59. bindkey -M viins '\e\e' sudo-command-line