December 4, 2010

Integrate Emacs with the Mac OS X Clipboard

Mac OS X includes a terminal version of Emacs. There are a few GUI versions if you're looking for an XEmacs equivalent, but that's another article. Integrating Emacs and your clipboard isn't too difficult, and once it's finished, you'll be able to copy and paste in to and out of Emacs.

You're going to need to open a terminal to edit this file since it's hidden by default. In the ultimate irony let's use Emacs to edit it's own file. After opening the terminal window, type cd to make sure you're in your home directory. Then type emacs .emacs. Enter the code shown below, then save and exit Emacs.

(defun mac-copy ()
(shell-command-to-string "pbpaste"))

(defun mac-paste (text &optional push)
(let ((process-connection-type nil))
(let ((proc (start-process "pbcopy" "*Messages*" "pbcopy")))
(process-send-string proc text)
(process-send-eof proc))))

(setq interprogram-cut-function 'mac-paste)
(setq interprogram-paste-function 'mac-copy)

Next time your start Emacs you'll have copy and paste. The shortcut keys are still the same, so C-k will cut a line of text, then if you go to Firefox and press CMD-v, it will paste the text from Emacs. It works both ways with all applications. The secret is the pbpaste and pbcopy applications. These are Mac applications that interact with the terminal and clipboard, we're just adding this code in so that Emacs knows to use them to interact with the clipboard.

1 comment: