VIM 文件自动添加头部注释的方法

一种 vim 创建文件时自动添加头部注释的方法

修改 /etc/vimrc~/.vimrc,在文件最后添加以下内容:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
" 当新建 .h .c .hpp .cpp .mk .sh等文件时自动调用SetTitle 函数
autocmd BufNewFile *.[ch],*.hpp,*.cpp,Makefile,*.mk,*.sh exec ":call SetTitle()"
" 加入注释
func SetComment()
call setline(1,"/*================================================================")
call append(line("."), "* Copyright (C) ".strftime("%Y")." IEucd Inc. All rights reserved.")
call append(line(".")+1, "* ")
call append(line(".")+2, "* 文件名称:".expand("%:t"))
call append(line(".")+3, "* 创 建 者:SongTL, songtianlun@comleader.com.cn")
call append(line(".")+4, "* 创建日期:".strftime("%Y年%m月%d日"))
call append(line(".")+5, "* 描 述:")
call append(line(".")+6, "*")
call append(line(".")+7, "================================================================*/")
call append(line(".")+8, "")
call append(line(".")+9, "")
endfunc
" 加入shell,Makefile注释
func SetComment_sh()
call setline(3, "#================================================================")
call setline(4, "# Copyright (C) ".strftime("%Y")." IEucd Inc. All rights reserved.")
call setline(5, "# ")
call setline(6, "# 文件名称:".expand("%:t"))
call setline(7, "# 创 建 者:SongTL, songtianlun@comleader.com.cn")
call setline(8, "# 创建日期:".strftime("%Y年%m月%d日"))
call setline(9, "# 描 述:")
call setline(10, "#")
call setline(11, "#================================================================")
call setline(12, "")
call setline(13, "")
endfunc
" 定义函数SetTitle,自动插入文件头
func SetTitle()
if &filetype == 'make'
call setline(1,"")
call setline(2,"")
call SetComment_sh()

elseif &filetype == 'sh'
call setline(1,"#!/system/bin/sh")
call setline(2,"")
call SetComment_sh()

else
call SetComment()
if expand("%:e") == 'hpp'
call append(line(".")+10, "#ifndef _".toupper(expand("%:t:r"))."_H")
call append(line(".")+11, "#define _".toupper(expand("%:t:r"))."_H")
call append(line(".")+12, "#ifdef __cplusplus")
call append(line(".")+13, "extern \"C\"")
call append(line(".")+14, "{")
call append(line(".")+15, "#endif")
call append(line(".")+16, "")
call append(line(".")+17, "#ifdef __cplusplus")
call append(line(".")+18, "}")
call append(line(".")+19, "#endif")
call append(line(".")+20, "#endif //".toupper(expand("%:t:r"))."_H")

elseif expand("%:e") == 'h'
call append(line(".")+10, "#pragma once")
elseif &filetype == 'c'
call append(line(".")+10,"#include \"".expand("%:t:r").".h\"")
elseif &filetype == 'cpp'
call append(line(".")+10, "#include \"".expand("%:t:r").".h\"")
endif
endif
endfun

使用效果:

https://cdn-imagehost.frytea.com/images/archives/20200720192515.png

参考文献


VIM 文件自动添加头部注释的方法
https://www.frytea.com/post/20211103141338.html
作者
Tianlun Song
发布于
2021年11月3日
更新于
2024年6月10日
许可协议