Vim中自动在程序起始处添加版权和作者信息

在编写程序的时候,经常需要在程序开始写上程序的简要介绍和作者信息,如下:

这种信息,除了文件名和修改时间可能经常发生变化外,其他基本不变,可以在程序开始自动加入,方法就是在家目录下的.vimrc中写入:

map <F4> :call TitleDet()<cr>
function AddTitle()
    call append(0,"#!/usr/bin/env bash")
    call append(1,"# ******************************************************")
    call append(2,"# Author       : 90Zeng")
    call append(3,"# Last modified: ".strftime("%Y-%m-%d %H:%M"))
    call append(4,"# Email        : omezengjl@gmail.com")
    call append(5,"# Filename     : ".expand("%:t"))
    call append(6,"# Description  : ")
    call append(7,"# ******************************************************")
    echohl WarningMsg | echo "Successful in adding copyright." | echohl None
endf
 
function UpdateTitle()
     normal m'
     execute '/# Last modified/s@:.*$@=strftime(":	%Y-%m-%d %H:%M")@'
     normal ''
     normal mk
     execute '/# Filename/s@:.*$@=":	".expand("%:t")@'
     execute "noh"
     normal 'k
     echohl WarningMsg | echo "Successful in updating the copyright." | echohl None
endfunction

function TitleDet()
    let n=1
    while n < 10
        let line = getline(n)
        if line =~ '^#s*S*LastsmodifiedS*.*$'
            call UpdateTitle()
            return
        endif
        let n = n + 1
    endwhile
    call AddTitle()
endfunction
View Code

 

 

保存之后,vi test.sh,在norm 模式下按下F4即可,效果如下:

假如下一时刻,我们将文件名称改为了test2.sh,然后需要更新上面的信息,只需要:mv test.sh test2.sh, 然后vim test2.sh,F4,会自动更新修改时间和文件名称

如果我们经常需要写的python文件,那么在.vimrc中修改相应的字符即可,如下:

效果如下:

网上已经有插件实现了上述功能(http://www.vim.org/scripts/script.php?script_id=2902),但是对于安装插件不方便的场景,可以自己手动编写上述代码

参考:Vim在源代码中自动添加作者信息

原文地址:https://www.cnblogs.com/90zeng/p/vim_authorinfo.html