Does emacs have a built in function for removing trailing spaces in a buffer? I want to remove trailing whitespace at the end of all the lines in a buffer.

  • 2
    Removing them from what? strings? buffer text? Where have you searched for an answer before coming here?
    – Stefan
    Commented Jun 22, 2017 at 16:30
  • Please clarify if you are looking for a function that deletes trailing whitespace from a buffer (as @Ryan's answer addresses), or if you're looking to remove whitespace from a string, or something else.
    – Dan
    Commented Jun 23, 2017 at 13:04
  • delete-horizontal-space ? Commented Jun 26, 2017 at 0:39
  • I am new to emacs and not sure of the appropriate terminology, but from the questions here I believe it must mean trailing spaces in a buffer.
    – vfclists
    Commented Jun 26, 2017 at 2:40
  • Thanks for clarifying! We've reopened the question, although it looks like you've got the answer you were looking for.
    – Dan
    Commented Jun 26, 2017 at 4:39

1 Answer 1


According to the EmacsWiki, M-x delete-trailing-whitespace will eliminate all trailing whitespace in a buffer. In Spacemacs, it is bound to SPC x d w by default

You can do it automatically for all buffers by adding the following to your init.el:

(add-hook 'before-save-hook 'delete-trailing-whitespace)

For future reference, you can search for Emacs functions within Emacs by typing M-x apropos, then typing your query. In this case, M-x apropos <RET> whitespace <RET> provides a list of functions relating to whitespace.

  • 3
    apropos is a nice tip thank you Commented Nov 26, 2020 at 17:08
  • what if I want to avoid this in modes where it has special meaning like in markdown, but apply it in all other modes?
    – xeruf
    Commented Mar 9, 2023 at 21:28

Your Answer

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

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