By default, Emacs evil-mode
removes newly inserted spaces when exiting insert mode. However, some users may find this disruptive to their workflow. This is particularly true for those who edit file formats where trailing spaces are significant or who simply prefer to manage whitespace manually.
To prevent the automatic removal of trailing spaces when leaving insert mode, add the following Elisp code to the Emacs init file:
(with-eval-after-load 'evil
(defun my-evil-disable-remove-spaces ()
"Disable automatic removal of trailing spaces in `evil-mode'."
(setq-local evil-maybe-remove-spaces nil))
(add-hook 'evil-insert-state-entry-hook #'my-evil-disable-remove-spaces))
Code language: Lisp (lisp)
The function above sets the evil-maybe-remove-spaces variable to nil when entering insert mode, preventing the evil-maybe-remove-spaces function from deleting whitespace after leaving insert mode.
The evil-insert-state function, which Evil uses to switch to insert mode, behaves as follows:
- When entering insert mode: It sets the evil-maybe-remove-spaces variable to t.
- When exiting insert mode, it calls the evil-maybe-remove-spaces function, which removes trailing spaces if the evil-maybe-remove-spaces variable is set to t. Because the my-evil-disable-remove-spaces function above sets the evil-maybe-remove-spaces variable to nil when entering insert mode, it prevents the evil-maybe-remove-spaces function from deleting whitespace after leaving insert mode.
If you want to compare the behavior before and after the function above, use whitespace-mode. This mode visually highlights different types of whitespace characters, such as spaces, tabs, and newlines, making it easier to see the differences.
Customizing evil-mode
with the simple piece of Elisp code above can prevent the automatic removal of trailing spaces when exiting insert mode. This adjustment allows for better control over whitespace in files.