sudo.plugin.zsh 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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. #
  13. # ------------------------------------------------------------------------------
  14. sudo-command-line() {
  15. [[ -z $BUFFER ]] && LBUFFER="$(fc -ln -1)"
  16. # Save beginning space
  17. local WHITESPACE=""
  18. if [[ ${LBUFFER:0:1} == " " ]] ; then
  19. WHITESPACE=" "
  20. LBUFFER="${LBUFFER:1}"
  21. fi
  22. if [[ -n $EDITOR && $BUFFER == $EDITOR\ * ]]; then
  23. if [[ ${#LBUFFER} -le ${#EDITOR} ]]; then
  24. RBUFFER=" ${BUFFER#$EDITOR }"
  25. LBUFFER="sudoedit"
  26. else
  27. LBUFFER="sudoedit ${LBUFFER#$EDITOR }"
  28. fi
  29. elif [[ $BUFFER == sudoedit\ * ]]; then
  30. if [[ ${#LBUFFER} -le 8 ]]; then
  31. RBUFFER=" ${BUFFER#sudoedit }"
  32. LBUFFER="$EDITOR"
  33. else
  34. LBUFFER="$EDITOR ${LBUFFER#sudoedit }"
  35. fi
  36. elif [[ $BUFFER == sudo\ * ]]; then
  37. if [[ ${#LBUFFER} -le 4 ]]; then
  38. RBUFFER="${BUFFER#sudo }"
  39. LBUFFER=""
  40. else
  41. LBUFFER="${LBUFFER#sudo }"
  42. fi
  43. else
  44. LBUFFER="sudo $LBUFFER"
  45. fi
  46. # Preserve beginning space
  47. LBUFFER="${WHITESPACE}${LBUFFER}"
  48. }
  49. zle -N sudo-command-line
  50. # Defined shortcut keys: [Esc] [Esc]
  51. bindkey -M emacs '\e\e' sudo-command-line
  52. bindkey -M vicmd '\e\e' sudo-command-line
  53. bindkey -M viins '\e\e' sudo-command-line