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.
(let* ((num (random (1+ max))))
(if min (max min num) num)))
Random color
(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.
(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).
(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.
(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))))
(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))
))
Dynamic Dropdown widget
Populating dropdown widget dynamically is a bit tricky. When :value is nil, :void is displayed if (and only if) :children is a list with a single empty string.
:value data-type ;; nil or some value
:void '(item :format "---\n")
(if tags
(mapcar (lambda (a) `(choice-item :value ,a))
tags)
'(""))
))
;; Populate updated tags value
`(choice-item :value ,a))
tags))
(widget-value-set w (car tags))
File permission string
A snippet to convert UNIX file permission (eg. 754) to string (eg. "rwxr-xr--"). Alternatively, if you have the octal number (#o754 or decimal 492), you can use the builtin (file-modes-number-to-symbolic MODE &optional FILETYPE).
(let* ((permission ["---" "--x" "-w-" "-wx" "r--" "r-x" "rw-" "rwx"])
result)
;; Iterate over each of the digits in octal
(mapc (lambda (i)
(setq result (concat result (aref permission (string-to-number (format "%c" i))))))
(number-to-string octal))
result))
Comments
Post a Comment