I wrote a hydra today (I think my very first one) - I always do Meta-| pbcopy after doing a C-x h, so why not let hydra help out:

     (kbd "C-x h")
     (defhydra hydra-my-mark-whole-buffer
       (:body-pre (mark-whole-buffer))
       ("h" mark-whole-buffer "this was not needed")
       ("p" my-pbcopy "Meta-| pbcopy")))
    ;; https://emacs.stackexchange.com/a/13177
    (defun my-pbcopy (beg end)
      (interactive "r")
      (message (if (zerop (shell-command-on-region beg end "pbcopy")) "copied" "copy failed")))

(btw I'm always in emacsclient -nw mode)

Anyway, I'd like two more things:

  • not lose the point/position
  • if a region was marked before calling the hydra, if should stay that way after pbcopy has been done.

How can I tweak my code to do that?

1 Answer 1


In general, if you want to run a command but maintain the initial point, you would wrap the function in (save-excursion ...)

From the documentation: https://www.gnu.org/software/emacs/manual/html_node/eintr/save_002dexcursion.html:

In Emacs Lisp programs used for editing, the save-excursion function is very common. It saves the location of point, executes the body of the function, and then restores point to its previous position if its location was changed. Its primary purpose is to keep the user from being surprised and disturbed by unexpected movement of point.

  • thank you, along with save-excursion, i ended up adding a '(deactivate-mark)' and a hydra ':exit t' to the final solution Commented Apr 4, 2021 at 18:37
  • Awesome. Glad to see alternative ways to tackle the same problem. Commented Apr 5, 2021 at 11:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.