I have been using UUID for several different things now, and I have been using uuidgen program available on Linux.
Since I use Emacs, I wanted to better way of generating UUID right from Emacs.
Ergoemacs has good coverage about it back in 2011 about it.
There is a example that uses the uuidgen program:
(defun insert-random-uuid () (interactive) (shell-command "uuidgen" t))
The above pretty much solves problems for generating UUID, but I wanted to have a solution that generates UUID inside Emacs, just in case it’s needed.
The example codes, Ergoemacs have posted seems to the job, however, I’ve noticed the original piece of code fixed the first character of the fourth segment character “a” (which actually generates a valid UUID, as this character needs to be either 8, 9, A, or B. I’ve modified this code slightly to generate one of those characters instead of it being always “a” which would be the following.
;; by Christopher Wellons. 2011-11-18. Editted by Xah Lee. ;; Edited by Hideki Saito further to generate all valid variants for "N" ;; in xxxxxxxx-xxxx-Mxxx-Nxxx-xxxxxxxxxxxx format. (defun insert-uuid-internal () "Insert a UUID. This uses a simple hashing of variable data." (interactive) (let ((myStr (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 myStr 0 8) (substring myStr 8 12) (substring myStr 13 16) (format "%x" (+ 8 (random 4))) (substring myStr 17 20) (substring myStr 20 32)))))
Also one thing to note is that it’s generally better to use uuidgen where available, as it generates one from /dev/urandom, which tied to various random number sources — although, for the scope of generating uuid, it may not that be critical as likelihood of collision would still be low.