How to perform operations on changed lines in Emacs before-save?

依然范特西╮ 提交于 2019-12-06 05:11:25

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!