1

I often create new files with the name of today's date. So, I would like to make this a command that calls the shell date command. The date command I use is:

date +%Y-%m-%d-%B%d).md

I tried to call this same shell command from within Vim with this custom command in my .vimrc:

command Post e !date +%Y-%m-%d-%B%d.md

But that doesn't work because % means the current filename in Vim and the desired filename isn't created.

asked Jul 20, 2022 at 15:57

2 Answers 2

2

You can use the built-in :help strftime() function instead of the date command. This makes the command a little bit more portable and, since the function is evaluated before :edit is executed, you don't get the unwanted side-effects of :help cmdline-special.

:command! Post execute 'edit ' .. strftime('%Y-%m-%d-%B%d') .. '.md'
answered Jul 20, 2022 at 17:24
1
  • This is great! I'm not much of a vim-scripter so I wasn't familiar with the builtin strftime. Thanks for opening my eyes to this. Commented Jul 20, 2022 at 19:43
1

I agree that @romainl idea of using builtin functions is a better approach than just delegating in the shell. For the sake of displaying how would it be to open (:edit) a file name resulting of a shell command would be something like this:

:command! Post execute 'let file=system("date +\\%Y-\\%m-\\%d-\\%B\\%d.md") | normal! :e ' .. file .. '^M'
  • You need to quote the '%' with double \.
  • You need to invoke the shell command before calling the :edit command, if you do something like: execute "normal! :e !date +%Y-%m-%d-%B%d.md" the date command will not be evaluate but just verboten pasted to :edit.
answered Jul 20, 2022 at 17:43
1
  • Good point, but there was no need to call system and double escaping. This is enough: command! -buffer Post execute '.!date +\%Y-\%m-\%d-\%B\%d\).md' Commented Jul 23, 2022 at 0:55

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.