Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate a random 5 letter+number string at cursor-point. (all lower-case)

Tags:

emacs

elisp

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.

like image 696
smilingbuddha Avatar asked Dec 10 '22 17:12

smilingbuddha


2 Answers

(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)
like image 160
Brian Malehorn Avatar answered Jan 18 '23 15:01

Brian Malehorn


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)))))))
like image 42
jch Avatar answered Jan 18 '23 14:01

jch