In python mode when I'm done with an inner indented block I hit return, then backspace to return to the previous indentation and then another return so that there's a blank line before I start the code following that indented block. This leaves a blank line that has only tabs or spaces. I try and find them and remove the tabs and spaces with M-\ but it would be more convenient if there was a save file hook that would find all of them and do this cleanup. Is there something that does that?

  • Sounds like the very popular github.com/lewang/ws-butler package would more or less do what you describe.
    – Hubisan
    Jan 29, 2021 at 20:48
  • @Hubisan Thanks. Arch Stanton's suggestion does exactly what I want.
    – lumpynose
    Jan 30, 2021 at 1:03

1 Answer 1


Call delete-trailing-whitespace from before-save-hook:

(defun my-python-mode-setup ()
  (add-hook 'before-save-hook #'delete-trailing-whitespace nil 'local)
  ;; Maybe this could be helpful too
  (local-set-key (kbd "RET") #'reindent-then-newline-and-indent))
(add-hook 'python-mode-hook #'my-python-mode-setup)

This setting makes delete-trailing-whitespace run on save but only in in Python Mode buffers. The binding makes RET reindent the current line (which should remove all indentation in an empty line) before making a new one.

(You can set delete-trailing-lines to nil to suppress the deletion of trailing empty lines, if you want.)


Your Answer

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

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