1

This function inserts the current date and time on the line after the cursor:

function! InsertDate()
    put = strftime('%FT%T%z')
endfunction

I'd like to insert the date and time on the current line after the cursor instead.

I thought it would be as simple as:

function! InsertDate()
    normal "=strftime('%FT%T%z')<CR>p
endfunction

But that doesn't insert anything. I don't understand why.

I also thought this should work:

function! InsertDate()
    normal a<C-R>=strftime('%FT%T%z')
endfunction

But that inserts <C-R>=strftime('%FT%T%z') literally.

I thought maybe I needed to add <CR> or <CR><Esc> to the end but it made no difference.

What am I missing?

1

1 Answer 1

1

I would do:

function! InsertDate()
    execute "normal! \"=strftime('%FT%T%z')\<CR>p"
endfunction

Your tentative were good but the normal argument do not interpret the <CR> code. In the solution I propose I use the \<CR> expansion within " strings.

9
  • Thanks, that works. I eventually came up with execute "normal i\<C-R>=strftime('%FT%T%z')\<CR>", which is more verbose but does the same. Apr 26, 2023 at 21:16
  • Thanks for the feedback :-) Apr 27, 2023 at 3:23
  • I would do it differently. Make InsertDate() return just the date, and if you need to insert it, just use :put =InsertDate() or from insert mode: i<c-r>=InsertDate()<cr> which I think is easier to use Apr 27, 2023 at 6:37
  • 1
    yes of course, put is linewise. What I was trying to say is, you could use the InsertDate() function in any way you like, add it in insert mode after the cursor, or just put it into a line below or just echo the current date at the command line. The function is flexible enough and is not bound to be only used in one single way. Apr 27, 2023 at 7:00
  • 1
    Prefer normal!
    – D. Ben Knoble
    Apr 28, 2023 at 21:23

Your Answer

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

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