Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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>
share|improve this question

2 Answers 2

up vote 4 down vote accepted

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')
share|improve this answer
    
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 Aug 5 '14 at 12:01
    
The second doesn't work either; I just get the error "Unknown mark". –  Andrew Ferrier Aug 5 '14 at 12:02
    
Correction, the second does work; I made a typo. –  Andrew Ferrier Aug 5 '14 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! –  Ingo Karkat Aug 5 '14 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 :) –  Andrew Ferrier Aug 6 '14 at 10:33

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>
share|improve this answer
    
I find @Ingo Karkat's second example slightly clearer, but this definitely works too, thanks. –  Andrew Ferrier Aug 6 '14 at 10:34

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.