2

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"
  (interactive)
  (backward-char)
  (when (member (thing-at-point 'word) '("function"))
    (progn
      (save-excursion (insert "  " "end"))
      (forward-char))))
(defun spacep ()
  (if (and (derived-mode-p 'lua-mode)(member (char-before) '(13 32)))
      (put-end)))
(defun mein-lua-mode-hook ()
  "Tastaturanbindungen fuer das Lua-Mode"
  ;;; some other things come here
  (add-hook 'post-self-insert-hook 'spacep))

Update I have corrected my code.Now it works only in lua mode but i can type space only if the last word is function. I now the problem is the spacep but how can i correct it?

  • 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. – stardiviner Feb 4 '18 at 6:21
1

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)))
    (put-end)))
  • great! Now i am wondering why it only reacts on space (char-code 32) but not with return (13). Do you have any idea? – amirt Feb 3 '18 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 Feb 3 '18 at 16:19
1

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

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

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.