4
votes

I am using Emacs 24.5 (inside Spacemacs). I'd like to be able to generate a random 5 character string wherever my cursor inside emacs is by just pressing a single key, say F2.

A typical random string would be jb2nx with all letters always being lower-case. The seed values for randomg number generation at emacs's startup should always be different to stop emacs from generating the same sequence of random strings when it is opened up the next time.

NOTE:

I need this feature, to insert a unique word at point, to use it as a bookmark. This way I can open up to the line containing the random string from Org-mode e.g.

[[file:some-code-file::jb2nx][This line in the code-file]] 

would be a line in my Org file. whereas jb2nx would be placed inside a comment on the line being referenced in the code file.

I don't want to reference the line number directly after :: since, line numbers can change while editing the code file.

3
I recommend you do a hash on current-time. It is promised to be unique. - tom

3 Answers

9
votes
(defun random-alnum ()
  (let* ((alnum "abcdefghijklmnopqrstuvwxyz0123456789")
         (i (% (abs (random)) (length alnum))))
    (substring alnum i (1+ i))))

(defun random-5-letter-string ()
  (interactive)
  (insert 
   (concat 
    (random-alnum)
    (random-alnum)
    (random-alnum)
    (random-alnum)
    (random-alnum))))

(global-set-key (kbd "<f2>") 'random-5-letter-string)
2
votes

While Brian's solution is fine, I personally prefer working directly in a buffer rather than generating an intermediary string:

(defun insert-random-five ()
  (interactive)
  (dotimes (_ 5)
    (insert
     (let ((x (random 36)))
       (if (< x 10) (+ x ?0) (+ x (- ?a 10)))))))
2
votes

Extending Brian's answer, if you just need a random string without inserting it and with configurable length:

(defun random-string (n)
  "Generate a slug of n random alphanumeric characters.

Inefficient implementation; don't use for large n."
  (if (= 0 n)
      ""
    (concat (random-alnum) (random-string (1- n)))))