14

I want to generate 10 random numbers in the buffer.

In Emacs I would do:

<start macro>(random limit) <eval lisp><newline><end macro> to define the macro,

and 9 <execute macro> to generate it 10 times.

Is there a way I can do this in vim?

kenorb
  • 155,785
  • 88
  • 678
  • 743
Frison Alexander
  • 3,228
  • 2
  • 29
  • 32

2 Answers2

29

is this ok for you?

:r! echo $RANDOM

then

9@:

if you have certain programming language env available on your OS, you can eval those statement too.

Kent
  • 189,393
  • 32
  • 233
  • 301
  • Know of an equivalent in gVim? – Jeff Dec 06 '13 at 22:05
  • @Jeff That works on gVim. I was on windows, so replaced $random with %random%. Rest just worked – Frison Alexander Dec 06 '13 at 22:08
  • I was trying this on windows but the command in the answer didn't work. So, I opened up vim inside cygwin and then it worked. – user674669 Apr 17 '16 at 00:43
  • @user674669 of course it won't work on windows, because there is no `$RANDOM` sys env on windows. `:!` will execute external command. Just like there is no `du, ls, readlink, cp ...` on windows. Well cygwin I don't have much experience.. – Kent Apr 18 '16 at 09:17
  • In addition, you could use `:r!echo $(($RANDOM \% 5 + 1))` to get a value between 1 and 6. Tweak values accordingly to get other ranges. – squirl Feb 04 '17 at 13:25
11

Vim doesn't offer native random generator, however if you have vim compiled with Python, the following method will append a random digit at the end of your line:

:py import vim, random; vim.current.line += str(random.randint(0, 9))

Note: To check if your vim supports Python, try: :echo has('python') (1 for yes).

You can also use shell which offers $RANDOM variable as Kent suggested (works with bash/ksh/zsh) which returns a pseudorandom (0-32767), in example:

:put =system('echo $RANDOM')

or:

:r! od -An -td -N1 /dev/urandom

On Windows, you've to have Cygwin/MSYS/SUA installed, or use %RANDOM% variable as Carpetsmoker suggested.

If you don't have access to shell and Python, as for workaround, you use last few digits from the current timestamp, in example:

:put =reltimestr(reltime())[-2:]

Note: If you're using it quite often, write a simple function which will return reltimestr(reltime())[-4:].

Note: Above methods returns only a pseudorandom integer which should not be used to generate an encryption key.


To add more random numbers please press @: to repeat the command again. Or prefix with number (like 10@:) to add much more of random numbers separated by new lines.


Related:

Community
  • 1
  • 1
kenorb
  • 155,785
  • 88
  • 678
  • 743