vim自动添加和更新文件注释信息

这里利用vim的脚本功能为C/C++文件自动添加日期、版权等说明信息。同样的方法可用于Python等类型的文件处理。

1. 自动添加文件头

首先新建一个文件c_header.vim

:insert
/*********************************************************
 * File Name:
 * Purpose:
 * Creation Date:
 * Last Modified:
 * Created By: [email protected]
 *********************************************************/

#include  "util/stdafx.h"
.

然后在~/.vimrc中添加bufnewfile事件回调:

autocmd bufnewfile *.c,*.cpp,*.h  so ~/config/c_header.vim
autocmd bufnewfile *.c,*.cpp,*.h exe "1,6g/File Name:.*/s//File Name: " .expand("%")
autocmd bufnewfile *.c,*.cpp,*.h exe "1,6g/Creation Date:.*/s//Creation Date: " .strftime("%Y-%m-%d")
autocmd bufnewfile *.h exe "1,9g/^#include.*/s//#pragma once/"

2. 自动更新文件最后修改日期

~/.vimrc中添加bufwriteprefilewritepre事件:

autocmd Bufwritepre,filewritepre *.c,*.h,*.cpp execute "normal ma"
autocmd Bufwritepre,filewritepre *.c,*.h,*.cpp exe "1,6g/Last Modified:.*/s/Last Modified:.*/Last Modified: " .strftime("%Y-%m-%d")
autocmd bufwritepost,filewritepost *.c,*.h,*.cpp execute "normal `a"

3. 处理老文件

假设之前有些文件没有经过上述脚本的处理,现在需新添加文件头,可以按照以下步骤操作。

首先:新建一个c_header_for_exist_file.vim文件:

:normal ma
:normal gg
:insert
/***************************************************************
 * File Name:
 * Purpose:
 * Creation Date:
 * Last Modified:
 * Created By: [email protected]
 ****************************************************************/

.
:1,6s/File Name:.*/\='File Name: ' . expand("%")
:1,6s/Creation Date:.*/\='Creation Date: ' .strftime("%Y-%m-%d")

:normal `a

对于单个文件,用vim打开后运行:source c_header_for_exist_file.vim即可。

如果有很多文件需要处理,此时可用vimargdo功能。

首先打开vim,然后用args命令打开所有需要处理的文件:

:args *.cpp *.h

然后用argdo运行命令即可:

:argdo source c_header_for_exist_file.vim
Copyright © zhiqiang.org 2016 all right reserved,powered by Gitbook该文件修订时间: 2016-08-03 01:06:06

results matching ""

    No results matching ""