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(":\t%Y-%m-%d %H:%M")@'
     normal ''
     normal mk
     execute '/# Filename/s@:.*$@\=":\t".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*Last\smodified\S*.*$'
            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在源代碼中自動添加作者信息


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM