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).

ideasman42
  • 8,375
  • 1
  • 28
  • 105

2 Answers2

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.

ideasman42
  • 8,375
  • 1
  • 28
  • 105
  • 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 Jul 13 '22 at 00:19
  • @db48x thanks for pointing this out, a VCS agnostic way to access the current branch name would definitely be preferred. Updated answer. – ideasman42 Jul 13 '22 at 02: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))))))
Tobias
  • 32,569
  • 1
  • 34
  • 75