Creating Automated Documents in Vim

Should Vim create comment based on file type when opening a new file?

I am new to Vim. Here is the functionality I'm looking for. When I do this:

$ vim hello.py

I want the file to start with:

#Date Created: 24 May 2012
#Last Modified: (This is optional, really)
#Summary: (enter short summary of program here) 
#Author: My Name
#License: ...

etc .. I searched around, but I can not find a solution for this.

+5
source share
3 answers

You can do this without skeleton files using the following:

 autocmd BufNewFile *.py exe "normal O#Date Created: " . strftime("%d %b %Y") . "\r#Last Modified:\r#Summary:\r#Author:\r#License:\r"
 autocmd BufWritePre *.py exe "%s/^#Last Modified:.*$/#Last Modified: " . strftime("%d %b %Y (%T)") . "/e"

Put them in your vimrc.

A potential problem is that it autocmd BufWritePrewill add the current time to all lines , starting with:

#Last Modified:
+4
source

This is described in vim autocmd help .. specifically you want this

+3
source

pb2q, . , :

function UpdateModifiedTime(comment)
    let savedPosition = getpos(".")
    call cursor(1, 1)
    let modified = a:comment . 'Modified:'
    if search(modified, 'e') > 0
        execute 'substitute/' . modified . '.*/' . modified . ' ' . strftime('%b %d, %Y %T') . '/'
    endif
    call setpos(".", savedPosition)
endfunction

(: , , Vim, golfing, , ).

Then you can define auto commands, for example:

autocmd BufWrite *.sh,*.ksh,*.bash       call UpdateModifiedTime('## ')
autocmd BufWrite *.vim                   call UpdateModifiedTime('" ')
autocmd BufWrite *.py                    call UpdateModifiedTime('')
autocmd BufWrite *.c                     call UpdateModifiedTime('// ')

Note that I gave an empty comment character for Python. This is because I had lines '''in the file header for comments. You can use '# 'either '## 'or everything that tickles your imagination.

You can do something similar with Created.

+1
source

All Articles