做过开源项目的童鞋可能会知道,在很多开源项目中会有专门的脚本来检查代码风格。其中包括行尾是否有多余的空白字符,是否使用使用tab,每一行是否超过了指定的宽度等等。这些问题通常在敲代码的时候并不容易看出来,等到要提交代码的时候才发现问题。稍微搜索了一下发现在emacs中有一个很有用的whitespace插件可以解决这个问题。
whitespace可以针对设置的规则对上面提到的问题进行高亮显示,效果如下:
whitespace具体可以找到的问题包括tab, 空格混用;行尾多余的空白字符;文件结束前的空白字符;超过指定长度的行等等。可以通过设置whitespace-style来指定需要提示哪些问题。在我的配置中使用了如下配置:
1 2 3 4 5 6 7 | ;; deal with white spaces (require 'whitespace) (global-whitespace-mode) (setq whitespace-style '(face trailing tabs lines lines-tail empty space-after-tab space-before-tab)) (add-hook 'before-save-hook 'delete-trailing-whitespace) |
默认的whitespace-style把整个buffer被搞得有点乱糟糟的,因此我把不是很需要的部分都去掉了,只剩下检测行尾空白、tab等少数几个问题。对于行尾的多余字符而言,一个个删除也是很麻烦的事情。所以我直接用delete-trailing-whitespace在保存的时候把它们都干掉了。
不过在这里whitespace会和行号有一点点冲突。通常为了显示行号都会打开linum-mode,行号会是右边对其的数字。whitespace会认为行号前面的空白字符是问题字符而高亮显示,搞得非常难看。为了解决这个问题可以用下面代码对linum进行设置:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | ;; Show line number (require 'linum) (global-linum-mode t) (setq column-number-mode t) (setq line-number-node t) (setq linum-format "%5d ") (add-hook 'linum-before-numbering-hook (lambda () (let ((w (+ (length (number-to-string (count-lines (point-min) (point-max)) )) 2) )) (setq linum-format `(lambda (line) (propertize (concat (truncate-string-to-width "" (- ,w (length (number-to-string line))) nil ?x2007) (number-to-string line)) 'face 'linum)))))) |
这是从emacs wiki上面抄过来的一段代码,用了一个特殊的unicode字符x2007来设置行号的格式,既能达到右端对其的效果又不会被whitespace误杀。







近期评论