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://xahlee.info/emacs/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://xahlee.info/emacs/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: 2 to 9, upcase or lowercase English alphabet but no vowels, no L l and no 0 1.
Call `universal-argument' before for different count.

URL `http://xahlee.info/emacs/emacs/elisp_insert_random_number_string.html'
Version 2018-08-03 2022-09-26"
  (interactive "P")
  (let* (($charset "BCDFGHJKMNPQRSTVWXYZbcdfghjkmnpqrstvwxyz23456789")
         ($baseCount (length $charset)))
    (dotimes (_ (if (numberp NUM) (abs NUM) 5))
      (insert (elt $charset (random $baseCount))))))

O emacs! ♥

Thanks to Teemu Likonen [tliko…@iki.fi] for improvement.

Emacs, Insert Random ID

ErgoEmacs mascot-s276x226
Buy Xah Emacs Tutorial

Elisp Examples

Text Transform Under Cursor

Commands Do thing-at-point

Command to Insert Things

Script Examples

Misc