这里利用vim的脚本功能为 C/C++ 文件自动添加日期、版权等说明信息。同样的方法可用于 Python 等类型的文件处理。
1. 自动添加文件头
首先新建一个文件c_header.vim
:insert/********************************************************** File Name:* Purpose:* Creation Date:* Last Modified:* Created By: zhangzq@citics.com*********************************************************/#include "util/stdafx.h".
然后在~/.vimrc中添加bufnewfile事件回调:
autocmd bufnewfile *.c,*.cpp,*.h so ~/config/c_header.vimautocmd 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中添加bufwritepre和filewritepre事件:
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: zhangzq@citics.com****************************************************************/.: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即可。
如果有很多文件需要处理,此时可用vim的argdo功能。
首先打开vim,然后用args命令打开所有需要处理的文件:
:args *.cpp *.h
然后用argdo运行命令即可:
:argdo source c_header_for_exist_file.vim
https://zhangzq.gitbooks.io/notes/content/md/vim-auto-add-header.html
