compile 时只保存项目内的文件

Jiacai Liu

发布: 2022-10-30   更新: 2022-10-30   标签: programming compile

文章目录

Emacs 中有一个非常好用的 compile 模块,可以非常方便的编译代码、运行测试等。不熟悉的读者可以参考: Compiling and running scripts in Emacs - Mastering Emacs

有一点比较烦人的是,

每次执行 compile 时,如果有已经修改,但是还未保存的文件,它都会在 minibuffer 中提示。

这样做的初衷是可以理解的,如果修改的文件没有保存,编译会用老的文件。问题是,所有未保存的文件都会提示,这就有些过分了,最好是能控制在项目内,之外的文件就不要再提示了。

幸好,compile 模块提供了一个选项用来控制提示那些文件: compilation-save-buffers-predicate

实现方式如下:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
(defvar my/compile-project-root nil)
(defvar my/compile-file nil)
(defun my/update-compile-dir (cmd &optional comint)
  (if-let* ((pr (project-current))
            (root (project-root pr)))
	  (setq my/compile-project-root (file-truename root))
	(progn
	  (setq my/compile-project-root nil)
	  (setq my/compile-file (file-truename (buffer-file-name))))))

(advice-add 'compile :before 'my/update-compile-dir)

(defun my/file-in-project? ()
  "检查当前 buffer 是否属于当前项目,如果当前目录不属于任何项目,直接返回 `nil'"
  (if my/compile-project-root
	  (string-prefix-p my/compile-project-root
					   (file-truename (buffer-file-name)))
	(string-equal my/compile-file (file-truename (buffer-file-name)))))
(setq compilation-save-buffers-predicate 'my/file-in-project?)

思路就是在执行 compile 前记录下当前文件所属的项目,之后就判断当前未修改的文件是否在之内就好了。

需要注意一点,当 compile 的当前目录不属于任何项目时,这时候只会提醒当前文件是否需要保存。

参考



收听方式

反馈