JavaHacker
JavaHacker

Reputation: 33

vim output user-defined command to buffer

I try to create a user-defined command in vim that is supposed to return an uuid.

command -range CreateUUID !python3 -c 'import uuid; print(uuid.uuid4())'<cr>

The command works but it just outputs to the terminal.

I have tried

Upvotes: 0

Views: 77

Answers (1)

Matt
Matt

Reputation: 15081

In VimScript commands never return anything, as they are not even considered as expressions. You must declare a function instead. For example,

function! UUID() abort
    python3 import uuid
    return py3eval('str(uuid.uuid4())')
endfunction

:put =UUID()

An alternative is to capture the command's output by using a specialized function like execute() (for an Ex command) or system() (for an external tool):

:put =system('uuidgen')

Yet another thing is "read-space-bang" command (:h :r!), so you can do

:r !python3 -c 'import uuid; print(uuid.uuid4())'

But, 1) again, it only inserts an external tool's stdout, not an Ex-command's output; 2) it's not the way to compose two arbitrary Ex-commands, as "read-space-bang" counts as a single command with a very unique syntax.

Upvotes: 2

Related Questions