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>

2 Answers 2

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')
5
  • 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? Commented Aug 5, 2014 at 12:01
  • The second doesn't work either; I just get the error "Unknown mark". Commented Aug 5, 2014 at 12:02
  • Correction, the second does work; I made a typo. Commented Aug 5, 2014 at 12:03
  • I've considered that (in the first mapping, too); the <CR> is just to conclude the <C-r>= expression. Try it out! Commented Aug 5, 2014 at 12:41
  • 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 :) Commented Aug 6, 2014 at 10:33
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>
1
  • I find @Ingo Karkat's second example slightly clearer, but this definitely works too, thanks. Commented Aug 6, 2014 at 10:34

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .