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?

lumpynose
  • 111
  • 3

1 Answers1

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

Arch Stanton
  • 1,525
  • 9
  • 22
  • Great, thanks Arch! Why did you put a pound sign in front of the single quotes? I've never seen that before – lumpynose Jan 29 '21 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 https://endlessparentheses.com/get-in-the-habit-of-using-sharp-quote.html, https://www.gnu.org/software/emacs/manual/html_node/elisp/Anonymous-Functions.html and `C-h f function RET`. – Arch Stanton Jan 29 '21 at 20:40
  • Ok, thanks. I also found this: https://stackoverflow.com/questions/3325499/why-is-used-before-lambda-in-common-lisp – lumpynose Jan 29 '21 at 20:45