I have written a functionality that inserts the word end at end of blocks in a lua major mode. How i do it is to check if a space character has been typed, if yes is the word before the space for example function, if yes print the end. Now adding my funcionality to post-self-insert-hook will change its hooks-list in all modes and buffers. How can i specify it to happen only in lua-mode?

Here is my code in my init.el:

(add-hook 'lua-mode-hook 'mein-lua-mode-hook)
(defun put-end ()
  "print end of blocks"
  (when (member (thing-at-point 'word) '("function"))
      (save-excursion (insert "  " "end"))
(defun spacep ()
  (if (and (derived-mode-p 'lua-mode)(member (char-before) '(13 32)))
(defun mein-lua-mode-hook ()
  "Tastaturanbindungen fuer das Lua-Mode"
  ;;; some other things come here
  (add-hook 'post-self-insert-hook 'spacep))
  • 1
    You can use add-function, it provides a way to affect buffer locally. Check out its docstring with [C-h f add-function]. This could be an option. Commented Feb 4, 2018 at 6:21

2 Answers 2


That's what the local argument to add-hook is for. I.e. use

(add-hook 'post-self-insert-hook #'spacep nil 'local)

To have it affect only one mode, have the function test the current mode and do nothing if it is not (derived-mode-p THE-MODE). In your case, e.g.:

(defun spacep ()
  (when (and (derived-mode-p 'lua-mode)
             (member (char-before) '(13 32)))
  • great! Now i am wondering why it only reacts on space (char-code 32) but not with return (13). Do you have any idea?
    – user12021
    Commented Feb 3, 2018 at 16:07
  • 1
    Put your cursor after the character that you think is ^M (13) and hit C-u C-x =. I think you'll see that it's not 13. It's likely a newline char (10, not 13).
    – Drew
    Commented Feb 3, 2018 at 16:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.