1

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?

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

1 Answer 1

4

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

3
  • Great, thanks Arch! Why did you put a pound sign in front of the single quotes? I've never seen that before
    – lumpynose
    Commented Jan 29, 2021 at 20:06
  • I don't know the reason in depth, what I know is that it tells the byte-compiler that what follows should be a function, so it can optimize it, or raise an error if it isn't. Actually I'm not sure one needs to use it in his init file if they don't byte-compile the init. I do it because I see it as a good practice. See endlessparentheses.com/…, gnu.org/software/emacs/manual/html_node/elisp/… and C-h f function RET. Commented Jan 29, 2021 at 20:40
  • Ok, thanks. I also found this: stackoverflow.com/questions/3325499/…
    – lumpynose
    Commented Jan 29, 2021 at 20:45

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.