Insert UUIDs in Vim / Neovim

In my forays with Deequ, I found myself frequently inserting UUIDs into test JSON files. Although Online UUID Generator worked for this purpose, copy-pasta between browser and editor started to feel clunky. Time to create a key mapping in Vim.

I targeted Ctrl+U to insert a UUID, whether in normal or insert mode. My first attempt:

inoremap <c-u> <esc>:read!uuidgen<cr>i
nnoremap <c-u> :read!uuidgen<cr>

Worked moderately well, but of course it behaved as read! does: it inserted the UUID on its own line, after the current line. Since my drive comes primarily from not embarrassing myself in front of Visual Studio Code users, I knew I hadn’t yet found my solution. “Aha!” I thought. “Capital J!”

So my next attempt looked like this:

inoremap <c-u> <esc>:read!uuidgen<cr>kJx9ea
nnoremap <c-u> :read!uuidgen<cr>kJx

Somewhat cryptic, with all those cursor movements, but it seemed to work. And then I tried to add a UUID into an existing JSON that looked something like this:

{
  "id": "",
  "type": "MY_IMPORTANT_TYPE"
}

Which resulted in this:

{
  "id": "",5135efb2-82e7-4c2f-93ab-0d89b7ef95f5
  "type": "MY_IMPORTANT_TYPE"
}

VS Code vultures started circling. Shaken, I found this and remembered the expression register. I landed on this:

inoremap <c-u> <c-r>=trim(system('uuidgen'))<cr>
nnoremap <c-u> i<c-r>=trim(system('uuidgen'))<cr><esc>

C’est magnifique!

I’ve at least matched this, right?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.