There are certain file types that when I create an empty file I'd like some text auto-inserted into the file. For example, in both Bash and Python scripts I want a comment at the head of the file about when the file was first created and the file's purpose. It occurred to me recently that I could do this with Vim, at least for anything not Bash (Bash, or anything without a file extension, is difficult because Vim can't identify the filetype until after you've started editing the file). But it occurred to me that it should be relatively easy to pre-fill a reStructuredText file for this blog. So this is my current ~/.vim/ftplugin/rst.vim:
noremap <buffer> <silent> k gk noremap <buffer> <silent> j gj let curFileSize = getfsize(@%) " getfsize(...) returns -1 for "file not found": if (curFileSize==0) || (curFileSize==-1) let intro = [":title: Your Title Here"] " Use rst's preferred format for the time: call add (intro, ":date: " . strftime("%Y-%m-%d %H:%M")) call add (intro, ":tags: comma, separated, list") call add (intro, ":category: unknown") call add (intro, ":slug: generated-file-title") call add (intro, ":author: Giles Orr") call add (intro, ":status: draft") call add (intro, ":summary: short summary of page contents") call add (intro, ".. (inserted from ~/.vim/ftplugin/rst.vim, 'u' deletes)") call add (intro, "") call add (intro, "Content of the page in reStructuredText.") let failed = append(0, intro) if (failed) " Don't know when this would happen: echo "Unable to prep file!" else " vim doesn't seem to notice file changes applied by a script: let &modified = 1 endif endif
For files in the ftplugin/ folder to work, you'll need a "
filetype plugin indent on" line (or at least "
filetype plugin on") in your ~/.vimrc. The first two lines above have nothing to do with the pre-fill, but are great with rst files with their massively long and multi-wrapped lines.
getfsize(@%) gets us the size of the current file: if it's "0" (empty) or "-1" (because the file doesn't exist), pre-fill the file with the included text. "intro" is a Vimscript list, which I'm populating one element at a time for easier editing. To get today's date and time I use
strftime("%Y-%m-%d %H:%M") - this is the same time format as Unix strftime, so "man strftime" is your friend. The call to
append(0, intro) tries to insert each element of the "intro" list as a line at position "0". Finally, because vim doesn't seem to recognize programmatic insertion of code as a modification of the file, we
let &modified = 1.
See also the update to this post.