3

I'd like to know the current branch I'm in (in elisp), is there a generic function that returns the name of the current branch?

From looking into vc-mode mode-line logic it seems this relies on private functionality.

Is there a generic way to access the current branch in Emacs? (Using git but via vc this might work for other version control systems too).

2 Answers 2

0

The current GIT branch can be accessed using (car (vc-git-branches)) which always returns the current branch first.

However this uses a relatively slow method which accesses all branches. Currently the most direct way to access this is with a private function:
(vc-git--symbolic-ref (buffer-file-name))


Note that a VCS agnostic function would be preferred but as far as I know this doesn't exist.

2
  • 2
    Note that vc-mode works across many types of version control systems, and not all of them have branches. You should probably at least check to see if the buffer is in a git repository before calling vc-git functions.
    – db48x
    Commented Jul 13, 2022 at 0:19
  • @db48x thanks for pointing this out, a VCS agnostic way to access the current branch name would definitely be preferred. Updated answer.
    – ideasman42
    Commented Jul 13, 2022 at 2:34
0

You can issue the git-command git branch --show-current directly with vc-git-command:

(defun git+-branch (&optional buffer)
  "Return Git branch for file of BUFFER.
BUFFER defaults to the current buffer."
  (let ((fn (buffer-file-name (or buffer (current-buffer)))))
    (with-temp-buffer 
      (and (eq (vc-backend fn)
           'Git)
       (eq (vc-git-command t 0 fn "branch" "--show-current") 0)
       (buffer-substring-no-properties (point-min) (line-end-position 0))))))

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.