We have a convention that every commit message begins with an issue number.

I'd like to be able to programmatically insert the issue number part (computed by a separate function) into the commit window of Magit, when it first opens (that is, on pressing C C).

How do I best do it? Where to look?

UPDATE: Here's what I'm currently using.

(defun my-extract-branch-tag (branch-name)
  (let ((TICKET-PATTERN "\\(?:[[:alpha:]]+-\\)?\\([[:alpha:]]+-[[:digit:]]+\\)-.*"))
    (when (string-match-p TICKET-PATTERN branch-name)
       (s-upcase (replace-regexp-in-string TICKET-PATTERN "[\\1] " branch-name)))))

(defun my-git-commit-insert-branch ()
  (insert (my-extract-branch-tag (magit-get-current-branch))))

(add-hook 'git-commit-setup-hook 'my-git-commit-insert-branch)

For a branch name like <username>-foo-123-<explanatory part> it produces [FOO-123] in the first line of the commit message, to allow easy ticket auto-linking in Jira.


3 Answers 3


There is a git-commit-setup-hook that can be used to prepare the commit message buffer. Here comes a short example:

(defun my-git-commit-setup ()
  (insert "#123 "))

(add-hook 'git-commit-setup-hook 'my-git-commit-setup)

So glad to find this older, but very helpful answer by @wasamasa:

On a gitflow-based branching model, (feature-)branches created by Bitbucket based on Jira issues (which are always in the form UPPERCASEALPHA-DIGITS), i use this to automatically insert the current issue number:

(let ((ISSUEKEY "[[:upper:]]+-[[:digit:]]+"))
 (when (string-match-p ISSUEKEY (magit-get-current-branch))
    (concat ".*?\\(" ISSUEKEY "\\).*")
    "- \\1: "

To keep things really simple you could just invoke magit-commit with equivalent git arguments to accomplish the same thing:

(magit-commit `("--edit" ,(format "--message=%d: " 1234)))

Adding that command as an action to the popup with something like the following might help streamline your git workflow:

(defun my/read-issue-id ()
  "Return an issue ID default to the issue ID you are currently working on."
  ;; Or maybe completing-read w/unwrapping logic to extract the ID from a supplied list of issues...
   "Issue ID: "
   ;; Check your org-clock or make some REST request or something and use that as a default:

(defun my/issue-commit (issue-id)
  "Make a commit with a message starting with ISSUE-ID."
  (interactive (list (my/read-issue-id)))
  (magit-commit (append `("-e" ,(format "--message=%d: " issue-id))

(magit-define-popup-action 'magit-commit-popup ?I "'Issue' commit" #'my/issue-commit)

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.