3

I'm trying to create a dynamic line to execute, currently I have

execute a:modes[i] .'noremap <silent> <buffer> '. l:key .' <Esc>:call HardModeEcho(g:HardMode_hardmodeMsg)<CR>'

I'd like that to be something like

execute sprintf( 
  "%snoremap <silent> <buffer> %s <ESC>:call HardModeEcho(g:HardMode_hardmodeMsg)<CR>",
  a:modes[i],
  l:key
)

Actually it needs to get even more complex. But, I'd like to start with that. Is there any such functionality in vimscript?

Martin Tournoij
  • 62,054
  • 25
  • 192
  • 271
Evan Carroll
  • 1,304
  • 14
  • 39

1 Answers1

8

Somewhat surprisingly, it's printf(), which behaves like sprintf() in most other languages.

I wasn't 100% sure what the name was from the top of my head; I found this by just entering :help printf :-) I also find :help function-list to be invaluable when VimScript-ing.

Also see: How do I navigate to topics in Vim's documentation?.

D. Ben Knoble
  • 26,070
  • 3
  • 29
  • 65
Martin Tournoij
  • 62,054
  • 25
  • 192
  • 271
  • printf and sprintf aren't the same in any language that I know of, that's interesting. printf doesn't print, it returns a formatted string. I did try, :help sprintf, and I looked for it on Google. Didn't know about function-list – Evan Carroll May 02 '17 at 17:28
  • 1
    Yeah, it's a bit unusual @EvanCarroll, but it makes sense. For a printf function to print, you would have to use :call printf(..), which is exactly the same length as :echo printf(..). Not really much value in having such a function, so might as well return a string. Arguably, sprintf() would have made been a better name, but OTOH printf() saves us one character of typing ;-) – Martin Tournoij May 02 '17 at 17:36
  • Ah, because :call on a string in void-context is echo. Perhaps that makes some degree of sense, but you don't see that kind of stuff in other languages. Forgive the simple question. I'm just trying to write a quick patch for hardmode. – Evan Carroll May 02 '17 at 17:42