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.
2 Answers 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'
-
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.jlconlin– jlconlin2022年07月20日 19:43:11 +00:00Commented Jul 20, 2022 at 19:43
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
.
-
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'
r_31415– r_314152022年07月23日 00:55:49 +00:00Commented Jul 23, 2022 at 0:55