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?

Student
  • 103
  • 3

1 Answers1

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.

Phil Hudson
  • 1,741
  • 10
  • 13
  • 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). – Lindydancer Apr 24 '22 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. – Phil Hudson Apr 24 '22 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 Apr 25 '22 at 04: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. – Phil Hudson Apr 25 '22 at 08: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. – Phil Hudson Apr 25 '22 at 08:16
  • Maybe what we really need is some generalized way of tagging anonymous lambdas within hooks so that they don't appear as gibberish, but as soon as you ask that question the answer seems obvious: use the ubiquitous existing symbol function cell. – Phil Hudson Apr 25 '22 at 08:22