10

I use :r !uuidgen frequently to insert a new uuid into the buffer. This works, but I am generally attempting to insert the uuid between quotes, and :r !uuidgen prints the uuid on a new line.

To get around this issue, I am currently using a simple keymap:

nnoremap <C-u> mm:r!uuidgen<CR>dW"_dd`mp

This macro sets the mark mm, inserts the uuid r!uuidgen, deletes the inserted uuid dW, deletes the extra line "_dd, goes back to the mark BACKTICKm, and finally paste the uuid p.

Is there a way to :r right after the cursor without this macro/keybinding that wastes a register?

  • 1
    SU question, also with workarounds like this one. – muru Feb 16 '15 at 20:09
8

You can use the expression register "= and system():

<C-r>=system("uuidgen | tr -d '\n'")<CR>

It would look like that in an insert mode mapping:

inoremap <key> <C-r>=system("uuidgen | tr -d '\n'")<CR>

or, with an expression mapping:

inoremap <expr> <key> system("uuidgen \| tr -d '\n'")
5

From insert mode, you can hit Ctrl-R, and then type:

=system('uuidgen')

Note that this will add a trailing newline, because that's what uuidgen outputs; to fix this, we could use:

=system('uuidgen')[:-2]

To remove the newline.

From :help i_CTRL-R:

Insert the contents of a register. Between typing CTRL-R and the second character, '"' will be displayed to indicate that you are expected to enter the name of a register.

[..]

'=' the expression register: you are prompted to enter an expression (see expression)

To bind this to Ctrl-u like your example, you can use:

nnoremap <C-u> i<C-r>=system('uuidgen')[:-2]<CR><Esc>
2

One more, with :python:

:py import uuid, vim; vim.command(':normal i' + str(uuid.uuid1()))

You could map as:

:inoremap <key> <esc>:py import uuid, vim; vim.command(':normal a' + str(uuid.uuid1()))<cr>a

The UUIDs are generated by the Python UUID module.

  • 1
    This is a rather twisted way to go about, though. – muru Feb 16 '15 at 20:41
0

This is perhaps less preferable than using a pure-vim solution, however, if you use a snippet manager such as Ultisnips then you could try adding a snippet such as the following:

snippet uuid "insert new uuid" w
`uuidgen`
endsnippet

This way you can type uuid and hit your expand trigger in insert-mode and uuid will be replaced with the output of the relevant shell command. This, of course, can be easily adapted for other commands and expanded upon in powerful ways as outlined in the Ultisnips docs.

Your Answer

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