Elisp Snippets

Some useful Elisp snippets.

Random number

Generate a random number between min and  max positive integers. 

Note: We are adding 1 to max to make it an inclusive range.

(defun random-num (max &optional min)
  (let* ((num (random (1+ max))))
    (if min (max min num) num)))
 
 

Random color


 

(defun random-color-rgb ()
  (list (random 256) (random 256) (random 256)))

(defun random-color-html ()
  (apply #'format "#%02x%02x%02x" (random-color-rgb)))
 

Random face color

Generate a random valid color for a font face.

(defun random-color-face ()
  (let* ((colors (defined-colors))
     (n (length colors)))
    (nth (random n) colors)))
 
 

HTML Text

HTML uses HTML entities for special characters. e.g. & entity for & (ampersand).

;; Buffer text to HTML Text
(xml-escape-string STRING)
 
;; HTML Text to buffer text
(xml-substitute-special STRING)
 
 

Symbol Selector

Linux Biolinum Keyboard Font

Symbol Fonts provide symbols corresponding to Unicode codepoints. select-symbol command below will allow you to select a symbol (or character glyphs) from fonts installed in the system. 

Note: Not all codepoints are mapped in a Font. Use different start values to inspect symbols in different ranges. For instance, in the image above, the start value is #xe170.

(defun facemenu-select-font-family (&optional text)
  (interactive)
  (let* ((text (format " (%s)" (or text "OIly10")))
         (completion-extra-properties
          `(:annotation-function (lambda (a)
                                   (propertize ,text 'face
                                               `(:family a :background "grey"
                                                         ))))))
    (completing-read "Font family: " (font-family-list))))
 
(defun select-symbol ()
  (interactive)
  (let* ((family (facemenu-select-font-family))
         (size 400)
         (start (read-number "Start: " 32))
         (glyphs nil)
         g)
    (dotimes (i 256)
      (push (with-temp-buffer
              (insert-char (+ i start))
              (put-text-property (point-min) (point-max)
                                 'face `(:family ,family :height ,size))
              (buffer-string))
            glyphs))
    (setq g (completing-read "Glyph: " glyphs))
    (insert g)
    ))
 

 

 

Comments

Popular posts from this blog

GNU Emacs as a Comic Book Reader

Data Visualization with GNU Emacs

Mozilla Readability in GNU Emacs