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 (CountX)
  "Insert CountX random hexadecimal digits.
CountX default to 5.
Call `universal-argument' and type a number, then, call this command, for different count.
URL `http://xahlee.info/emacs/emacs/elisp_insert_random_number_string.html'
Version: 2017-08-03 2023-01-13"
  (interactive "P")
  (let (($n (if (numberp CountX) (abs CountX) 5 )))
    (insert (format  (concat "%0" (number-to-string $n) "x" ) (random (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


Elisp Examples

Text Transform Under Cursor

Commands Do thing-at-point

Command to Insert Things

Script Examples

Misc