Search code examples
vimautocmd

Automatically append current date to file name when saving in Vim


I'm using vim to take notes while reading academic articles. I prefer to have a new text file for each note I've taken, but organizing them becomes tedious.

What I would like to do is set an autocommand to detect if I'm in a certain directory, writing to a newfile and then appened the current date and time to whatever filename I write.

So if I have:

:pwd
/path/to/projects

When I type

:w Notes

I would like vim instead to save the file as "Notes - <CURRENT DATE - TIME >.txt"

I believe it involves declaring something like the following in my vimrc:

autocmd BufNewFile,BufWrite "/path/to/projects/*" <command involving strftime("%Y-%m-%d_%H-%M")>

But I can't figure out what. Any Ideas? I'm using Vim 7.3 on Debian Linux.


Solution

  • You may be looking for something along the lines of:

    function! SaveWithTS(filename) range
        execute "save '" . a:filename . strftime(" - %Y-%m-%d_%H-%M.txt'")
    endfunction
    
    command! -nargs=1 SWT call SaveWithTS( <q-args> )
    

    With the above in your .vimrc, executing :SWT Note will save your file as Note - YYYY-MM-DD_HH-MM.txt. This has the disadvantage of not happening automatically, so you have to remember to use :SWT instead of :w the first time your write your file, but it does let you wait until you are ready to save to decide what your filename should be (i.e. you aren't stuck with Note every time).

    Edit: The above version of SaveWithTS actually saves to the filename with single quotes around it (bad testing on my part). Below is a version that should fix that and also lets you specify an extension to your file (but will default to .txt)

    function! SaveWithTS(filename) range
        let l:extension = '.' . fnamemodify( a:filename, ':e' )
        if len(l:extension) == 1
            let l:extension = '.txt'
        endif
    
        let l:filename = escape( fnamemodify(a:filename, ':r') . strftime(" - %Y-%m-%d_%H-%M") . l:extension, ' ' )
    
        execute "write " . l:filename
    endfunction