2

In my .vimrc I have the following, which in Vim Visual mode inserts an unique alphanumeric string.

vnoremap <leader>u :!pwgen -A 8 1<CR>

For convenience, I want to do the same thing in Vim Insert mode: something like this (not working: .vimrc):

iabbrev uuid `pwgen -A 8 1`

where the abbreviation uuid (or :uid: or similar) triggers the BASH pwgen command (e.g replacing uuid with moh6sei5).


Edit

Per the comment immediately following mentioning Defining linux command inside vim abbreviations

the issue is that strtime (there) is a native Vim function (:h strftime), whereas pwgen is a BASH function. In .vimrc:

  • works:

    iabbrev xxx <C-r>=strftime('%c')<CR>
    " Sun 02 Oct 2022 11:03:58 AM PDT
    
  • does not work:

    iabbrev uidd <C-r>=pwgen -A 8 1<CR>
    iabbrev uidd <C-r>=!pwgen -A 8 1<CR>
    iabbrev uidd <C-r>=`pwgen -A 8 1`<CR>
    ...
    
Victoria Stuart
  • 4,610
  • 2
  • 44
  • 37
  • 1
    Does this answer your question? [Defining linux command inside vim abbreviations](https://stackoverflow.com/questions/57338955/defining-linux-command-inside-vim-abbreviations) – Andy Lester Oct 02 '22 at 17:44
  • Thank you for the suggestion; in response please see edit to Question, above. I am also using `SnipMate`, but I find that package to be dated and buggy, so I am trying to move away from it (or alternatives: `UltiSnips`, ...) – Victoria Stuart Oct 02 '22 at 18:10

2 Answers2

3
inoreabbrev <expr> uuid system('pwgen -A 8 1')->trim()

Breakdown:

  • <expr> tells Vim that the right hand side of the abbreviation is to be evaluated as a Vim expression.
  • Since pwgen is an external command, you need :help system() to capture its output.
  • External commands often end with a newline character so you need to :help trim() it.
romainl
  • 186,200
  • 21
  • 280
  • 313
1

This works, .vimrc:

inoremap <F3> <c-r>=trim(system('pwgen -A 8 1'))<cr>

Test: Insert mode, typing apple <F3> banana gives apple ipav7lier banana, where <F3> is that key. Each <F3> keypress inserts a UID.


Victoria Stuart
  • 4,610
  • 2
  • 44
  • 37