0

If i want to run function when buffer "k" is saved, is there a better way to do this, then just using add hook and checking buffers name in function?

We're looking for long answers that provide some explanation and context. Don't just give a one-line answer; explain why your answer is right, ideally with citations. Answers that don't include explanations may be removed.

  • 1
    Define "better"? What kind of difference are you looking for? What are your criteria/expectations? The question is vague so far, and so risks being closed as too broad. – Drew Feb 8 at 19:33
  • Can you add more information to your post, such as what you exactly want to accomplish (at least a rough description of what your function is supposed to do, whether the buffer is expected to be pointed to a particular file)? – DoMiNeLa10 Feb 8 at 20:02
0

You do not need to check the buffer name. Just add the hook buffer-locally. See the doc of add-hook:

The optional fourth argument, LOCAL, if non-nil, says to modify the hooks buffer-local value rather than its global value. This makes the hook buffer-local, and it makes t a member of the buffer-local value. That acts as a flag to run the hook functions of the global value as well as in the local value.

The fourth argument with value t says that the hook is buffer-local:

(add-hook 'after-save-hook #'your-function nil t)
  • Wouldn't that require 1) the hook be added locally within that specific buffer and 2) the buffer to currently exist? How would you define that in init.el? I suppose you could use file variables, but then that's clutter in the source file. Or do something like (let* ((buff (get-buffer "name"))) (if buff (with-current-buffer buff (add-hook 'after-save-hook #'your-function nil t)) (message "That buffer DNE"))) – Lorem Ipsum Feb 8 at 17:27
  • 1
    @LoremIpsum I understand the question such that he has already the buffer. Maybe the buffer has a special major mode and he can add the hook function there. – Tobias Feb 8 at 17:32

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.