Is there a way to easily copy the current branch name in Magit via M-x? At the moment I open the status pop up magit-status and copy the name from there.

Best & thanks for your help!

  • I think your question is too open ended and is unclear where exactly you are copying to. That will give an indication of the right solution, which ever you decide to accept. – Emacs User Feb 7 '17 at 14:24
  • Sorry for that, I liked your answer too, but the other one was more what I was looking for, I'll rewrite it the question – Cesc Feb 7 '17 at 18:07

You can use (magit-get-current-branch) and wrap that in a interactive command. Something like this should work:

(defun magit-add-current-buffer-to-kill-ring ()
  "Show the current branch in the echo-area and add it to the `kill-ring'."
  (let ((branch (magit-get-current-branch)))
    (if branch
        (progn (kill-new branch)
               (message "%s" branch))
      (user-error "There is not current branch"))))
| improve this answer | |
  • Thanks for your help! I was looking for function I could call via I can call it via M-x, but tried it inside ielm and works awesome, so if I understand it correctly now I need to wrap this function and make it interactive. – Cesc Feb 7 '17 at 10:30
  • I've added a command to my answer. – tarsius Feb 7 '17 at 12:15
  • Hey, just wanted to post back what I wrote but I saw you wrote the solution for me including error handling. My pleasure to learn from this, thanks once again – Cesc Feb 7 '17 at 15:28

You already have the right approach. But if you're looking for a command, this extracts the branch name

ALT+! git rev-parse --abbrev-ref HEAD

Where ALT+! is the shell-command.

If you are on Mac OS X (though you did not mention what OS you are using), copy to the clipboard, assuming that is where you want to copy to:

ALT+! git rev-parse --abbrev-ref HEAD | pbcopy

To paste back, use the usual OS Cmd-v to paste it back.

If on the other hand, you just want to copy to other parts of magit or emacs, then use one of any number of magit functions to find the branch name. As tarsus has pointed out use (magit-get-current-branch). But you still have to M-w the name to insert it someplace else. That's why your first instinct was the right one: takes the least number of keystrokes.

| improve this answer | |
  • 1
    Thanks for your help, I think I'll stay with (magit-get-current-branch) – Cesc Feb 7 '17 at 11:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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