Skip to content

Instantly share code, notes, and snippets.

@jordonbiondo
Last active October 10, 2019 18:04
Show Gist options
  • Save jordonbiondo/ae9ef9f1d7d1baf4145a to your computer and use it in GitHub Desktop.
Save jordonbiondo/ae9ef9f1d7d1baf4145a to your computer and use it in GitHub Desktop.
Magit, delete-trailing-whitespace on hunk under point.
(defun jorbi-magit/-line-region-of-section-at-point ()
"If point is in a hunk return a list of info about the hunk.
The info is like (expanded-file-name starting-line number-of-lines-show)"
(let* ((section (magit-current-section))
(context-type (magit-section-context-type section)))
(when (and (member 'hunk context-type))
(let* ((info
(mapcar 'string-to-number
(split-string
(second (split-string
(magit-section-info
(magit-current-section))
"[ @]" t))
",")))
(start-line (car info))
(line-count (or (and (cdr info) (cadr info)) 1)))
(let ((parent (magit-section-parent section)))
(while (and parent
(not (equal (magit-section-type parent)
'diff)))
(setq magit-section-parent parent))
(list (expand-file-name (magit-section-info parent))
start-line
line-count))))))
(defun jorbi-magit/delete-hunk-trailing-whitespace ()
"Run `delete-trailing-whitespace' on the region shown in the unstaged hunk under point.
The cooresponding file will be saved and the magit-status buffer will be refreshed."
(interactive)
(let ((area (jorbi-magit/-line-region-of-section-at-point)))
(if (and area (member 'unstaged (magit-section-context-type (magit-current-section))))
(progn
(destructuring-bind (file start-line total-lines) area
(with-current-buffer (find-file-noselect file)
(save-some-buffers)
(save-excursion
(delete-trailing-whitespace
(progn (goto-char (point-min))
(forward-line (1- start-line))
(point-at-bol))
(progn (forward-line (1- total-lines))
(point-at-eol))))
(save-buffer)))
(magit-refresh))
(message "Must be in a unstaged magit hunk."))))
;; setup a key binding
;; (define-key magit-status-mode-map (kbd "C-c s d") 'jorbi-magit/delete-hunk-trailing-whitespace)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment