safe-paste.plugin.zsh 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. # Code from Mikael Magnusson: https://www.zsh.org/mla/users/2011/msg00367.html
  2. #
  3. # Requires xterm, urxvt, iTerm2 or any other terminal that supports bracketed
  4. # paste mode as documented: https://www.xfree86.org/current/ctlseqs.html
  5. # create a new keymap to use while pasting
  6. bindkey -N paste
  7. # make everything in this keymap call our custom widget
  8. bindkey -R -M paste "^@"-"\M-^?" paste-insert
  9. # these are the codes sent around the pasted text in bracketed
  10. # paste mode.
  11. # do the first one with both -M viins and -M vicmd in vi mode
  12. bindkey '^[[200~' _start_paste
  13. bindkey -M paste '^[[201~' _end_paste
  14. # insert newlines rather than carriage returns when pasting newlines
  15. bindkey -M paste -s '^M' '^J'
  16. zle -N _start_paste
  17. zle -N _end_paste
  18. zle -N zle-line-init _zle_line_init
  19. zle -N zle-line-finish _zle_line_finish
  20. zle -N paste-insert _paste_insert
  21. # switch the active keymap to paste mode
  22. function _start_paste() {
  23. bindkey -A paste main
  24. }
  25. # go back to our normal keymap, and insert all the pasted text in the
  26. # command line. this has the nice effect of making the whole paste be
  27. # a single undo/redo event.
  28. function _end_paste() {
  29. #use bindkey -v here with vi mode probably. maybe you want to track
  30. #if you were in ins or cmd mode and restore the right one.
  31. bindkey -e
  32. LBUFFER+=$_paste_content
  33. unset _paste_content
  34. }
  35. function _paste_insert() {
  36. _paste_content+=$KEYS
  37. }
  38. function _zle_line_init() {
  39. # Tell terminal to send escape codes around pastes.
  40. [[ $TERM == rxvt-unicode || $TERM == xterm || $TERM = xterm-256color || $TERM = screen || $TERM = screen-256color ]] && printf '\e[?2004h'
  41. }
  42. function _zle_line_finish() {
  43. # Tell it to stop when we leave zle, so pasting in other programs
  44. # doesn't get the ^[[200~ codes around the pasted text.
  45. [[ $TERM == rxvt-unicode || $TERM == xterm || $TERM = xterm-256color || $TERM = screen || $TERM = screen-256color ]] && printf '\e[?2004l'
  46. }