automatically beautify source code with emacs

前两天接了一个任务——统一代码缩进格式。

要求不算高,确保没有TAB键并缩进四格。问题是几十个文件,总得有点手段才行,谁让咱是懒惰的程序员呢!尝试了indent和astyle,都不甚理想,indent主要是处理C,而我们用C++,astyle号称也能处理C++和Java,却把bit field当成了label。最后还是决定用emacs,毕竟它有c++-mode。

写了两个脚本——reindent.sh和reindent.el。reindent.sh是驱动程序;reindent.el则完成缩进工作,它必须放在emacs的load path里面,比如可以放在/usr/share/emacs/site-lisp/,放在当前目录或使用显式路径都是没有用的。

reindent.sh的内容如下:

#!/bin/bash

set -o verbose

for d in dir_a dir_b/subdir_c; do
   for f in `find $d -iname "*.[hc]"`; do
      emacs --no-site-file --batch $f -l reindent
   done
done

reindent.el的文件内容如下:

(add-hook 'c++-mode-hook '(lambda()
      (setq indent-tabs-mode nil)
      (c-set-style "stroustrup")
      (c-set-offset 'case-label 4)
      (c-set-offset 'inline-open 0)
      (c-set-offset 'cpp-define-intro 0)
      (c-set-offset 'func-decl-cont 0)))
(c++-mode)
(indent-region (point-min) (point-max))
(untabify (point-min) (point-max))
(save-buffer)

其中包括了一些根据特定项目需要而做的定制和hack,详见CC Mode手册

3 thoughts on “automatically beautify source code with emacs

  1. 匿名 says:

    版主

    我是一个emacs,linux爱好者,有个 emacs命令,以前试过,现在想不起来了。在网上搜了好几天没找到。没办法只好向版主求救了。
    问题:如何固定光标滚动屏幕?就是上下滚动时,光标不要动。(行很长并且各行长短不一时,光标跳来跳去,太不方便了)

    请版主百忙中解救。谢谢!

  2. 匿名 says:

    ;; scroll functions
    (defun hold-line-scroll-up()
    “Scroll the page with the cursor in the same line”
    (interactive)
    (let ((next-screen-context-lines
    (count-lines
    (window-start) (window-end)
    )
    ))
    (scroll-up)
    ))
    (defun hold-line-scroll-down()
    “Scroll the page with the cursor in the same line”
    (interactive)
    (let ((next-screen-context-lines
    (count-lines
    (window-start) (window-end)
    )
    ))
    (scroll-down)
    ))
    (global-set-key (kbd “M-n”) ‘hold-line-scroll-up)
    (global-set-key (kbd “M-p”) ‘hold-line-scroll-down)

回复 匿名 取消回复

您的电子邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据