Emacs: Insert Random UUID πŸ“œ

By Xah Lee. Date: . Last updated: .

Here's a emacs command to insert a UUID.

put this in your Emacs Init File:

(defun xah-new-uuid-elisp ()
  "return a UUID string.
done by pure elisp.
URL `http://xahlee.info/emacs/emacs/elisp_generate_uuid.html'
Created: 2026-02-28
Version: 2026-02-28"
  ;; 2011-11-18 this command is with help by Christopher Wellons.
  ;; and editted Hideki Saito further to generate all valid variants for "N" in xxxxxxxx-xxxx-Mxxx-Nxxx-xxxxxxxxxxxx format.
  ;; 2026-02-28 todo. using md5 does not seem good.
  (let ((xstr (md5 (format "%s%s%s%s%s%s%s%s%s%s"
                           (user-uid)
                           (emacs-pid)
                           (system-name)
                           (user-full-name)
                           (current-time)
                           (emacs-uptime)
                           (garbage-collect)
                           (buffer-string)
                           (random)
                           (recent-keys)))))
    (format "%s-%s-4%s-%s%s-%s"
            (substring xstr 0 8)
            (substring xstr 8 12)
            (substring xstr 13 16)
            (format "%x" (+ 8 (random 4)))
            (substring xstr 17 20)
            (substring xstr 20 32))))
(defun xah-new-uuid ()
  "return a UUID string.
This commands calls β€œuuidgen” on MacOS, Linux, and calls PowelShell on Microsoft Windows.

URL `http://xahlee.info/emacs/emacs/elisp_generate_uuid.html'
Created: 2026-02-28
Version: 2026-02-28"
  (interactive)
  (cond
   ((eq system-type 'windows-nt)

    (shell-command-to-string "PowerShell -Command [guid]::NewGuid().toString()"))
   ((eq system-type 'darwin)
    (shell-command-to-string "uuidgen"))
   ((eq system-type 'gnu/linux)
    (shell-command-to-string "uuidgen"))
   (t
    (xah-new-uuid-elisp))))
(defun xah-insert-uuid ()
  "Insert a UUID.
This commands calls β€œuuidgen” on MacOS, Linux, and calls PowelShell on Microsoft Windows.

URL `http://xahlee.info/emacs/emacs/elisp_generate_uuid.html'
Created: 2020-06-04
Version: 2026-02-28"
  (interactive)
  (insert (xah-new-uuid)))

Thanks to Christopher Wellons γ€”http://nullprogram.com/〕 , Hideki Saito https://web.archive.org/web/20230206153224/https://hideki.hclippr.com/2014/02/02/on-generating-uuid/ . And [Yuri Khan https://plus.google.com/+YuriKhan/posts], Jon Snader http://irreal.org/blog/ for discussion about UUID.

Emacs, Insert Random ID