5

Is there to make Vim create a comment blurb based on the filetype when I open a new file?

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

$ 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 have searched around but I cannot find a solution to do this.

Keith Pinson
  • 7,835
  • 7
  • 61
  • 104
yayu
  • 7,758
  • 17
  • 54
  • 86

3 Answers3

4

You could 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 those in your vimrc.

A potential problem is that the autocmd BufWritePre will append the current time to all lines beginning with:

#Last Modified:
pb2q
  • 58,613
  • 19
  • 146
  • 147
3

This is covered in the vim autocmd help .. in particular you want this

Michael Anderson
  • 70,661
  • 7
  • 134
  • 187
1

This answer is based upon pb2q's, but makes it more extensible. Define a function to do the creation, so you can use it for a variety of comment types:

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

(Note: it is my practice to use the longer forms whenever possible in scripting Vim, unless I am golfing, because I value code readability and normal commands are arcane).

You can then define autocommands such as:

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. That's because I had ''' strings in my file header for the commenting. You can use '# ' or '## ' or whatever tickles your fancy.

You can do something similar with Created.

Community
  • 1
  • 1
Keith Pinson
  • 7,835
  • 7
  • 61
  • 104