问题
I'd like to add a before-save-hook where I can do some operations for just the lines that have changed since the last save. For e.g., remove trailing whitespace, check indentation, etc.. I don't want to do this for an entire file, and I am aware that there are individual options for each of these(just to remove trailing whitespace for all changed lines, etc..), but I'd like something generic so that I can add more stuff to it. I imagine there is something where I can either get the list of line numbers changed, or a get-first-changed-line(), get-next-changed-line() type of functions.
回答1:
use highlight-changes-mode machinery
You could use highlight-changes-mode
and then iterate over the text property hilit-chg
set by it using next-single-property-change
.
E.g.,
(with-current-buffer "my-buffer-name"
(let ((beg (point-min)) end)
(while (setq end (next-single-property-change beg 'hilit-chg))
(setq beg (next-single-property-change end 'hilit-chg))
(message "[[%s]]" (buffer-substring-no-properties end beg)))))
will produce the following:
[[
these are my changes
]]
[[ and here]]
[[
here are more changes
]]
in the *Messages*
buffer (and in the echo area).
full implementation example
ws-butler uses this mechanism to trim spaces at EOL on save for modified lines.
来源:https://stackoverflow.com/questions/14131492/how-to-perform-operations-on-changed-lines-in-emacs-before-save