Programmatically Inserting Text and Variables with Vimscript

This is an update to a previous blog post about precisely the same subject. You should read that first for this to make sense.

I've updated with the insertion of a ":modified:" tag (even though Pelican doesn't seem to use it with my current installation - I like to have it myself), and added a check to update that tag whenever an RST file is edited.

" Use rst's preferred format for the time:
let now = strftime("%Y-%m-%d %H:%M")

" if the file is empty (0 length) or doesn't exist, prep it
" (getfsize(...) returns -1 for "file not found"):

let curFileSize = getfsize(@%)
if (curFileSize==0) || (curFileSize==-1)
    let intro  = [":title: Your Title Here"]
    call add (intro, ":date: " . now)
    call add (intro, ":modified: " . now)
    call add (intro, ":tags: comma, separated, list")
    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, "")
    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
else
    " This updates the ":modified:" field to
    " the current date.  Search the first ten lines for ":modified:" at the
    " beginning of the line.  If found, replace with new date.

    execute "1,10/^:modified:/s/:modified:.*/:modified: " . now . "/"
    let &modified = 1
    echom ":modified: field updated, 'u' to undo"
endif

call IsSingleBuffer("colo nightsky")

This also adds a function to determine if this is a single buffer, and if it is, it sets the colour scheme. Otherwise it leaves it alone. This is stored in ~/.vim/plugin/IsSingleBuffer.vim (everything in the ~/.vim/plugin/ folder is auto-loaded when vim starts):

" From http://superuser.com/questions/345520/vim-number-of-total-buffers ,
" to determine if there are files already open.  I don't understand it, but
" it definitely works better than grabbing "bufnr('$')" ...  Basically: do
" this "cmd" if there's only one buffer open.

function IsSingleBuffer(cmd)
    if ! (len(filter(range(1, bufnr('$')), 'buflisted(v:val)')) > 1 )
        execute a:cmd
    endif
endfunction

That link: http://superuser.com/questions/345520/vim-number-of-total-buffers (Pelican doesn't want to do linking in a code block). I call this from most of my ~/.vim/ftplugin/ files to set the colour scheme, but it could be used for other commands meant to be applied to a single buffer only.

See this update for an improvement to the updating of the ":modified:" date.