1

I commonly will have a long list of ids that I will need to convert into a tuple for a SQL query or perhaps to create a array in python/javascript. Here is the command I've written to format a list of ids into a tuple and paste it back into the system clipboard:

nnoremap & "*pV']J:s/ /,/g<cr>i(<c-o>$)<esc>V"*y

How could this be converted into a function? I tried starting but I couldn't even get past the first thing of "paste from clipboard", for example:

func FormatInput ()
    call execute("\"*p") " how to get this to execute properly with the leading `"` ?
endfunc

While the above one-line might be sufficient for now, I'd like to add things like "quote strings" if the first item is not a digit and stuff like that.

1
  • 1
    execute() works in command-mode; p is a Normal mode command. See :h :normal
    – Matt
    Jun 13 '20 at 10:01
2

Use :normal! for the parts that should be executed in Normal mode.

If they include special key codes such as <C-o> or <Esc>, then use :execute so you can use a double quoted string with \<...> sequences for the :normal! command.

Putting it all together:

function! FormatInput()
    normal! "*pV']J
    s/ /,/g
    execute "normal! i(\<c-o>$)\<esc>V\"*y"
endfunction
nnoremap <silent> & :call FormatInput()<CR>
3
  • 1
    And for those that prefer ex when possible: put * (the visual join is unavoidable unfortunately), s/^/(/ | s/$/)/ | yank *
    – D. Ben Knoble
    Jun 13 '20 at 12:52
  • @Filbranden -- thanks, why did you use normal! on the first line and then execute "normal..." on the third? Is that because of the <c-o>?
    – David542
    Jun 14 '20 at 2:38
  • @David542 Yes. Like I mentioned a few lines above, if you need special key codes then you need to use :execute to be able to add them using escapes in a string. :map and friends expand those key codes themselves, that's why that's not needed there.
    – filbranden
    Jun 14 '20 at 2:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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