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