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?
1 Answer
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.)
-
Great, thanks Arch! Why did you put a pound sign in front of the single quotes? I've never seen that before 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
. Jan 29, 2021 at 20:40 -
Ok, thanks. I also found this: stackoverflow.com/questions/3325499/… Jan 29, 2021 at 20:45