Emacs: Insert Random Number or String πŸš€

By Xah Lee. Date: . Last updated: .

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

Set Random Seed

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 (CountX)
  "Insert CountX random digits.
CountX default to 3.
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-05-24 2022-04-02"
  (interactive "P")
  (let ((xcharset "1234567890")
        (xbaseCount 10)
        (xcount (if (numberp CountX) (abs CountX) 3)))
    (dotimes (_ xcount)
      (insert (elt xcharset (random xbaseCount))))))

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 ((xn (if (numberp CountX) (abs CountX) 5 )))
    (insert (format  (concat "%0" (number-to-string xn) "x" ) (random (expt 16 xn))))))

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 a e i o u, 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* ((xcharset "BCDFGHJKMNPQRSTVWXYZbcdfghjkmnpqrstvwxyz23456789")
         (xbaseCount (length xcharset)))
    (dotimes (_ (if (numberp NUM) (abs NUM) 5))
      (insert (elt xcharset (random xbaseCount))))))

O emacs! β™₯

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

Emacs, Insert Random ID