0

I have configured git to use emacs as editor for writing commit messages (with (start-server) in my init.el). I now want to put a template message (e.g. Bug #1234:) on top of the commit message buffer (so that it's on top of every commit message). How can I detect the opened commit buffer to insert my template string on top of it?

1 Answer 1

1

You'll want to adapt this to your needs:

(add-hook 'server-visit-hook
          (defun my/git-commit-preflight ()
            (when (search-forward "# Changes to be committed:")
              (goto-char (point-min))
              (insert "Bug #1234: "))))

Note the use of defun rather than anonymous lambda. This results in a tractable, human-readable server-visit-hook.

6
  • 1
    From the documentation of defun: "The return value is undefined.". Hence, it would be better to define the function separately and add it as (add-hook 'server-visit-hook #'my/git-commit-preflight). Commented Apr 24, 2022 at 19:06
  • In theory. In practice, it works. Try it. You'll have noticed many times as you eval-defun that the defun's symbol appears in the echo area. Commented Apr 24, 2022 at 20:14
  • 1
    The trouble is that if it is undefined, then no matter what is being returned now, it can change later, which will result in difficult-to-debug breakage.
    – NickD
    Commented Apr 25, 2022 at 4:21
  • You're right, of course. So... use at your own risk. I'm confident enough that in fact this will a) never change and b) in the superlatively improbable eventuality that it does, what will be returned will be a 100% compatible function object, that I'm prepared to rely on it, and to recommend it to others without reservation or qualification. Commented Apr 25, 2022 at 8:08
  • BTW, while your recommendation for a stand-alone top-level defun is safe both now and in the future, clear, and tractable -- that's a lot of pros -- there is one con: my way makes it clear that the function being defined has no other purpose and expects to have no other callers apart from its use in the hook. Of course at the language level there is no such distinction, and the function can indeed be called elsewhere; but this formatting makes it clear what the intent is. I consider that a significant readability and comprehension advantage. Commented Apr 25, 2022 at 8:16

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.