How can I construct a vim keymapping that inserts the current date?

3

I'm trying to create a vim keymapping that will initiate the creation of a new file, with the name of the file prefixed with the current date, waiting for me to finish typing the filename.

Put more precisely, I want to hit <Leader>n, and have vim enter for me in the command line:

:new 2014-08-05- ... waiting for me to complete the filename and hit <CR>.

How can I do this? I've tried this, but it didn't do quite what I expected, as it just echo-ed the date. How can I get vim to dynamically insert characters into the command line? Am I missing something simple?

function! NewNotesFile()
    echon ":new " . strftime("%F")
endfunction

nnoremap <Leader>n :call NewNotesFile()<CR>

Andrew Ferrier

Posted 2014-08-05T07:28:09.827

Reputation: 1 604

Answers

4

There are two ways. You can just insert the result of an expression to the command-line via :help c_CTRL-R:

:nnoremap <Leader>n :new <C-r>=strftime('%F')<CR>

This mapping mirrors how you would do it interactively. Alternatively, you can evaluate the right-hand side of the mapping via a :help map-expr:

:nnoremap <expr> <Leader>n ':new ' . strftime('%F')

Ingo Karkat

Posted 2014-08-05T07:28:09.827

Reputation: 19 513

Hello. I tried the first, but it doesn't quite work. I should have been clearer; I don't want to insert the <CR>, as I want to leave the cursor in place to finish off the filename manually. But when I remove it, it just opens a command-line and inserts the literal text =strftime('%F'). Am I doing something wrong? – Andrew Ferrier – 2014-08-05T12:01:32.140

The second doesn't work either; I just get the error "Unknown mark". – Andrew Ferrier – 2014-08-05T12:02:34.597

Correction, the second does work; I made a typo. – Andrew Ferrier – 2014-08-05T12:03:39.893

I've considered that (in the first mapping, too); the <CR> is just to conclude the <C-r>= expression. Try it out! – Ingo Karkat – 2014-08-05T12:41:18.770

Huh. Just tried the first one again and it worked this time. I guess I'm just typo-prone. Sorry! Thanks for the help in figuring this out, I just learnt about <expr> in mappings :) – Andrew Ferrier – 2014-08-06T10:33:36.163

3

Using c_CTRL-\_e (it’s a help tag, so see :h c_CTRL-\_e if something seems unclear) for instance:

nnoremap <Leader>n :<C-\>e"new " . strftime("%F")<CR>

Dmitry Alexandrov

Posted 2014-08-05T07:28:09.827

Reputation: 984

I find @Ingo Karkat's second example slightly clearer, but this definitely works too, thanks. – Andrew Ferrier – 2014-08-06T10:34:32.747