简体   繁体   中英

adding a function to <enter> in emacs

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 ?

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.

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.

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)

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM