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-insert-random-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'
Version: 2020-06-04 2023-05-13"
  (interactive)
  (cond
   ((eq system-type 'windows-nt)
    (shell-command "pwsh.exe -Command [guid]::NewGuid().toString()" t))
   ((eq system-type 'darwin) ; Mac
    (shell-command "uuidgen" t))
   ((eq system-type 'gnu/linux)
    (shell-command "uuidgen" t))
   (t
    ;; code here by Christopher Wellons, 2011-11-18.
    ;; and editted Hideki Saito further to generate all valid variants for "N" in xxxxxxxx-xxxx-Mxxx-Nxxx-xxxxxxxxxxxx format.
    (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)))))
      (insert (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)))))))

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.

Call PowerShell for UUID

Here's a example of how to call a PowerShell Core command.

;; on Microsoft Windows 10, call PowerShell Core to generate UUID
(shell-command "pwsh.exe -Command [guid]::NewGuid().toString()" t)
;; on macOS, call PowerShell Core to generate UUID
(shell-command "pwsh -Command '[guid]::NewGuid().toString()'" t)

Emacs, Insert Random ID