Emacs (post v21) includes a function to delete trailing whitespace from a file. How would I make delete-trailing-whitespace
available in the Magit staging area (from magit-status
) so that I can remove trailing whitespace from individual hunks or entire files?
How can I remove trailing whitespace from a hunk in Magit?
Asked Answered
This is Sean's snippet, adjusted for Magit v2:
(defun my-magit-delete-trailing-whitespace-from-file ()
"Remove whitespace from the current file."
(interactive)
(save-excursion
(magit-diff-visit-file-worktree (magit-file-at-point))
(delete-trailing-whitespace)
(save-buffer)
(kill-buffer))
(magit-refresh))
Thanks for the update. Is there any way to limit this to the hunk? Does the overlay in magit-status have any information about where the hunk comes from? If so, you could use that information to narrow before deleting the whitespace. –
Pa
For a hunk section
(magit-section-value (magit-current-section))
would return something like ("(defun module-rebuild ()" "-73,6" "+73,8")
. –
Finnic Thanks @tarsius's for your great trick! I managed to tweak it to remove just trailing whitespaces for the line at point. This requires the 'ws-trim' package installed.
(defun my-magit-delete-trailing-whitespace ()
"Remove whitespace from the current file."
(interactive)
(save-excursion
(magit-diff-visit-file-worktree (magit-file-at-point))
(ws-trim-line nil)
(save-buffer)
(kill-buffer))
(magit-refresh))
(add-hook 'magit-status-mode-hook
(lambda ()
(local-set-key [deletechar] 'my-magit-delete-trailing-whitespace)))
I'm binding the delete key since that isn't used for anything useful in magit-status-mode
.
© 2022 - 2024 — McMap. All rights reserved.
magit
. My guess that you could edit the diffs does not look good. This sort of works withediff
-patching but not with git. So, I will delete my answer. I am very sorry about that. – Balikpapan(add-hook 'before-save-hook 'delete-trailing-whitespace)
? – Judijudicable