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?

  • 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 '19 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 '19 at 20:02
  • Down-voted due to the lack of any response to multiple requests for clarification, in order to prevent the question being automatically bumped in future. – phils Nov 6 '19 at 4:40

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 '19 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 '19 at 17:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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