I'd like to be able to mark a region in a text buffer, hit an F-key, and have the contents of the region copied into the MacOS clipboard. From the shell you can do this by piping the text into the pbcopy command, but I have no idea how to write a defun to do that. Can anyone help? I'm using GNU Emacs 29.3 installed on macOS 14.4.1 by homebrew in terminal and not a GUI.
2 Answers
The function is already in emacs it is clipboard-kill-ring-save -
I have bound that to cmdC where I have bound the cmd key ⌘ to super.
This does keep the kill-ring and the clipboard in sync
(setq mac-function-modifier 'hyper mac-option-modifier 'meta mac-command-modifier 'super) ; using bind-key from use-package rather than define-key (bind-key "s-c" #'clipboard-kill-ring-save) (bind-key "s-x" #'clipboard-kill-region) (bind-key "s-v" #'clipboard-yank) There are also packages which do a similar binding but separate out the kill-ring and the OS clipboard e.g. simpleclip
- Doesn't work for me: I mark out a region, Type M-x clipboard-kill-ring-save. There's a message that the command completed, and the region becomes unhighlighted. But when I switch to a different Mac application and do CMD-v, the prior contents of the Mac clipboard gets pasted. I should note that I'm running emacs inside iterm2; i.e. not Emacs.app or similar.Chap– Chap2024-04-23 17:14:42 +00:00Commented Apr 23, 2024 at 17:14
- 1That matters a lot and needs to be in your question. Basically no way then. Why not use a GUI emacs if you want to integrate with macOSmmmmmm– mmmmmm2024-04-23 18:28:13 +00:00Commented Apr 23, 2024 at 18:28
- If there is a way for a defun to pipe the region text to a command (namely
pbcopy), that would be enough.Chap– Chap2024-04-23 19:36:11 +00:00Commented Apr 23, 2024 at 19:36
Two useful answers I found:
https://emacs.stackexchange.com/a/20892/2147 https://emacs.stackexchange.com/a/20426/2147
I modified the second solution as follows:
(defun pbcopy () (interactive) (let ((deactivate-mark t)) (call-process-region (point) (mark) "pbcopy") (setq mark-active nil) ;; I prefer to unset region afterward (message "Copied"))) ;; feedback And then,
(keymap-global-set "<f3>" 'pbcopy) I don't have any trouble using CMD+v to paste into emacs at point, so I didn't bother to implement pbpaste.
Tested in both Terminal.app and iTerm.app.
(global-set-key [f2] 'kill-ring-save)?