Reputation: 819
I wanted to add (delete-trailing-whitespace) with my enter.
I can't find what gives and hence I can't bind it to my new function.
How can I achieve this ?
Upvotes: 0
Views: 134
Reputation: 74460
How about just removing whitespace from the lines you are pressing RET on?
(defun delete-whitespace-on-this-line-then-newline ()
"before doing a newline, remove any trailing whitespace on this line"
(interactive)
(save-match-data
(save-excursion
(beginning-of-line)
(when (re-search-forward "\\s-+$" (line-end-position) t)
(replace-match ""))))
(newline))
It's not as good an answer as Jesus Ramos's, but it's kind of what you're asking for.
Upvotes: 3
Reputation: 73324
Take a look at this answer, and its comments:
https://stackoverflow.com/a/14164500/324105
I use ws-trim
to automatically remove trailing whitespace only from lines which I edit (which is a more robust solution to what I believe you are wanting to achieve with your key binding for enter).
event_jr also mentions ws-butler
, which does something similar, but only removes the trailing whitespace when you save (still only from lines which you have edited).
Upvotes: 2
Reputation: 23266
Personally I don't recommend binding it to the enter key as that can happen quite often and may be slow, instead I use
(add-hook 'before-save-hook 'delete-trailing-whitespace)
This just removes all the trailing whitespace when you save the file instead of each time you hit a key.
If you still want to bind it then see @ataylor's answer instead.
Upvotes: 8
Reputation: 66099
Keys have to be bound to commands, so first define a command that does what you want:
(defun delete-trailing-whitespace-newline ()
(interactive)
(delete-trailing-whitespace)
(newline))
The defun needs an interactive form at the top level to be a command. Then bind the key to the command:
(global-set-key (kbd "RET") 'delete-trailing-whitespace-newline)
Upvotes: 2