Copy/Paste in Emacs

  |   Source

CREATED: <2012-01-30>

UPDATED: <2014-08-23 Sat>

See http://www.emacswiki.org/emacs/CopyAndPaste for discussion.

1 Prepare

For Emacs console version under Linux, xsel is required.

For Emacs GUI version on any OS, NO external tool is needed.

For Emacs under Cygwin, you need install its package "cygutils-extra".

For Emacs console version under OS X, NO external tool is needed.

2 Solution

This solution works reliably at any environment.

Insert below code into ~/.emacs. Use 'M-x yank-to-x-clipboard' to copy, 'M-x paste-from-xclipboard' to paste.

(setq *is-a-mac* (eq system-type 'darwin))
(setq *cygwin* (eq system-type 'cygwin) )
(setq *linux* (or (eq system-type 'gnu/linux) (eq system-type 'linux)) )
(defun copy-to-x-clipboard ()
  (interactive)
  (if (region-active-p)
      (progn
        (cond
         ((and (display-graphic-p) x-select-enable-clipboard)
          (x-set-selection 'CLIPBOARD (buffer-substring (region-beginning) (region-end))))
         (t (shell-command-on-region (region-beginning) (region-end)
                                     (cond
                                      (*cygwin* "putclip")
                                      (*is-a-mac* "pbcopy")
                                      (*linux* "xsel -ib")))
            ))
        (message "Yanked region to clipboard!")
        (deactivate-mark))
        (message "No region active; can't yank to clipboard!")))

(defun paste-from-x-clipboard()
  (interactive)
  (cond
   ((and (display-graphic-p) x-select-enable-clipboard)
    (insert (x-get-selection 'CLIPBOARD)))
   (t (shell-command
       (cond
        (*cygwin* "getclip")
        (*is-a-mac* "pbpaste")
        (t "xsel -ob"))
       1))
   ))

(defun my/paste-in-minibuffer ()
  (local-set-key (kbd "M-y") 'paste-from-x-clipboard)
  )

(add-hook 'minibuffer-setup-hook 'my/paste-in-minibuffer)

3 Advanced Tips

3.1 Clipboard manager

Clipboard manager is handy sometimes.

I suggest parcellite at Linux, ditto under windows.

Here is my parcellite setup ($HOME/.config/parcellite/parcelliterc):

[rc]
use_copy=true
use_primary=true
synchronize=true
save_history=true
history_limit=64
hyperlinks_only=false
confirm_clear=false
single_line=true
reverse_history=false
item_length=50
ellipsize=2
history_key=<Super>Y
actions_key=
menu_key=
history_pos=false
history_x=1
history_y=1
case_search=false
type_search=false
data_size=0
ignore_whiteonly=false
trim_wspace_begend=false
trim_newline=false

3.2 Remote clipboard

Use below command to ssh the Linux server. Then you can share the clipboard between the server and your local computer seamlessly. No furthe setup needed.

ssh -X -C -c blowfish-cbc,arcfour $@

Comments powered by Disqus