Emacs: Insert Random Number/Hex/String

By Xah Lee. Date: . Last updated: .

This page shows emacs lisp commands to insert random {number, string, hexadecimal}.

First, in your emacs init file, you should change the random seed, like this:

(random t) ; seed random number

Else, every emacs restart, the sequence of random will be the same.

Insert Random Number

(defun xah-insert-random-number (NUM)
  "Insert NUM random digits.
NUM default to 5.
Call `universal-argument' before for different count.
URL `http://ergoemacs.org/emacs/elisp_insert_random_number_string.html'
Version 2017-05-24"
  (interactive "P")
  (let (($charset "1234567890" )
        ($baseCount 10))
    (dotimes (_ (if (numberp NUM) (abs NUM) 5 ))
      (insert (elt $charset (random $baseCount))))))

Insert Random Hexadecimal

(defun xah-insert-random-hex (NUM)
  "Insert NUM random hexadecimal digits.
NUM default to 5.
Call `universal-argument' before for different count.
URL `http://ergoemacs.org/emacs/elisp_insert_random_number_string.html'
Version 2017-08-03"
  (interactive "P")
  (let (($n (if (numberp NUM) (abs NUM) 5 )))
    (insert (format  (concat "%0" (number-to-string $n) "x" ) (random (1- (expt 16 $n)))))))

Insert Random String

(defun xah-insert-random-string (NUM)
  "Insert a random alphanumerics string of length 5.
The possible chars are 0 to 9, and a to z (lower case).
Call `universal-argument' before for different count.
URL `http://ergoemacs.org/emacs/elisp_insert_random_number_string.html'
Version 2017-05-24"
  (interactive "P")
  (let* (($charset "1234567890abcdefghijklmnopqrstuvwxyz")
         ($baseCount (length $charset)))
    (dotimes (_ (if (numberp NUM) (abs NUM) 5))
      (insert (elt $charset (random $baseCount))))))

Insert Random UUID

Elisp: Insert Random UUID

O emacs! ♥

Thanks to Teemu Likonen 〔tliko…@iki.fi〕 for improvement.

Liket it? Put $5 at patreon. Or Buy Xah Emacs Tutorial. Thanks.