bui-utils.el 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. ;;; bui-utils.el --- General utility functions -*- lexical-binding: t -*-
  2. ;; Copyright © 2014-2016 Alex Kost <alezost@gmail.com>
  3. ;; This program is free software; you can redistribute it and/or modify
  4. ;; it under the terms of the GNU General Public License as published by
  5. ;; the Free Software Foundation, either version 3 of the License, or
  6. ;; (at your option) any later version.
  7. ;;
  8. ;; This program is distributed in the hope that it will be useful,
  9. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. ;; GNU General Public License for more details.
  12. ;;
  13. ;; You should have received a copy of the GNU General Public License
  14. ;; along with this program. If not, see <http://www.gnu.org/licenses/>.
  15. ;;; Commentary:
  16. ;; This file provides auxiliary functions for "bui.el" package.
  17. ;;; Code:
  18. (require 'cl-lib)
  19. (require 'dash)
  20. (defcustom bui-true-string "Yes"
  21. "String used if the value of a parameter is t."
  22. :type 'string
  23. :group 'bui)
  24. (defcustom bui-false-string "No"
  25. "String used if the value of a boolean parameter is nil."
  26. :type 'string
  27. :group 'bui)
  28. (defcustom bui-empty-string "—"
  29. "String used if the value of a non-boolean parameter is nil."
  30. :type 'string
  31. :group 'bui)
  32. (defcustom bui-list-separator ", "
  33. "String used to seprate list values."
  34. :type 'string
  35. :group 'bui)
  36. (defcustom bui-time-format "%F %T"
  37. "String used to format time values.
  38. For possible formats, see `format-time-string'."
  39. :type 'string
  40. :group 'bui)
  41. ;;; String utils
  42. (defun bui-get-string (value &optional face)
  43. "Convert VALUE into a string and return it.
  44. VALUE can be an expression of any type.
  45. If VALUE is t/nil, it is replaced with
  46. `bui-true-string'/`bui-empty-string'.
  47. If VALUE is list, its elements are concatenated using
  48. `bui-list-separator'.
  49. If FACE is non-nil, propertize returned string with this FACE."
  50. (let ((str (cond
  51. ((stringp value) value)
  52. ((null value) bui-empty-string)
  53. ((eq t value) bui-true-string)
  54. ((numberp value) (number-to-string value))
  55. ((listp value) (mapconcat #'bui-get-string
  56. value
  57. bui-list-separator))
  58. (t (prin1-to-string value)))))
  59. (if (and value face)
  60. (propertize str 'font-lock-face face)
  61. str)))
  62. (defmacro bui-get-non-nil (&optional value &rest body)
  63. "Return `bui-empty-string' if VALUE is nil, evaluate BODY otherwise."
  64. (declare (indent 1) (debug t))
  65. `(if (null ,value)
  66. bui-empty-string
  67. ,@body))
  68. (defmacro bui-insert-non-nil (&optional value &rest body)
  69. "Insert `bui-empty-string' if VALUE is nil, evaluate BODY otherwise."
  70. (declare (indent 1) (debug t))
  71. `(if (null ,value)
  72. (insert bui-empty-string)
  73. ,@body))
  74. (defun bui-get-time-string (time)
  75. "Return formatted time string from TIME using `bui-time-format'.
  76. TIME can be either a time value (list), a number of seconds, or a
  77. time string."
  78. (let ((time (cond ((listp time) time)
  79. ((numberp time) (seconds-to-time time))
  80. ((stringp time) (date-to-time time))
  81. (t (error "Unknown time format: %S" time)))))
  82. (format-time-string bui-time-format time)))
  83. (defun bui-get-one-line (str)
  84. "Return one-line string from a multi-line STR."
  85. (replace-regexp-in-string "\n" " " str))
  86. (defun bui-get-filled-string (str column)
  87. "Return string by filling STR to COLUMN."
  88. (with-temp-buffer
  89. (insert str)
  90. (let ((fill-column column))
  91. (fill-region (point-min) (point-max)))
  92. (buffer-string)))
  93. (defun bui-split-string (str &optional column)
  94. "Split string STR by lines and return a list of the resulting strings.
  95. If COLUMN is non-nil, fill STR to this column."
  96. (let ((str (if column
  97. (bui-get-filled-string str column)
  98. str)))
  99. (split-string str "\n *" t)))
  100. ;;; Inserting text
  101. (defcustom bui-indent 2
  102. "Number of spaces used to indent various parts of inserted text."
  103. :type 'integer
  104. :group 'bui-info)
  105. (defun bui-get-indent (&optional level)
  106. "Return `bui-indent' \"multiplied\" by LEVEL (1 by default) spaces."
  107. (make-string (* bui-indent (or level 1)) ?\s))
  108. (defun bui-insert-indent (&optional level)
  109. "Insert `bui-indent' spaces LEVEL times (1 by default)."
  110. (insert (bui-get-indent level)))
  111. ;; `bui-newline' exists because `newline' does too much.
  112. (defun bui-newline (&optional n)
  113. "Insert N (1 by default) number of newlines at point."
  114. (--dotimes (or n 1)
  115. (insert "\n")))
  116. (defmacro bui-with-indent (indent &rest body)
  117. "Evaluate BODY and indent inserted text by INDENT number of spaces."
  118. (declare (indent 1) (debug t))
  119. (let ((region-beg-var (make-symbol "region-beg"))
  120. (indent-var (make-symbol "indent")))
  121. `(let ((,region-beg-var (point))
  122. (,indent-var ,indent))
  123. ,@body
  124. (unless (zerop ,indent-var)
  125. (indent-rigidly ,region-beg-var (point) ,indent-var)))))
  126. (defun bui-format-insert (value &optional face format)
  127. "Convert VALUE into a string and insert it at point.
  128. If FACE is non-nil, propertize VALUE with FACE.
  129. If FORMAT is non-nil, format VALUE with FORMAT."
  130. (let ((str (bui-get-string value face)))
  131. (insert (if format
  132. (format format str)
  133. str))))
  134. (cl-defun bui-mapinsert (function sequence separator &key indent column)
  135. "Like `mapconcat' but for inserting text.
  136. Apply FUNCTION to each element of SEQUENCE, and insert SEPARATOR
  137. at point between each FUNCTION call.
  138. If INDENT is non-nil, it should be a number of spaces used to
  139. indent each line of the inserted text.
  140. If COLUMN is non-nil, it should be a column number which
  141. shouldn't be exceeded by the inserted text."
  142. (pcase sequence
  143. (`(,first . ,rest)
  144. (let* ((indent (or indent 0))
  145. (max-column (and column (- column indent))))
  146. (bui-with-indent indent
  147. (funcall function first)
  148. (dolist (element rest)
  149. (let ((before-sep-pos (and column (point))))
  150. (insert separator)
  151. (let ((after-sep-pos (and column (point))))
  152. (funcall function element)
  153. (when (and column
  154. (> (current-column) max-column))
  155. (save-excursion
  156. (delete-region before-sep-pos after-sep-pos)
  157. (goto-char before-sep-pos)
  158. (bui-newline)))))))))))
  159. (defun bui-split-insert (value &optional face column separator)
  160. "Convert VALUE into a string, split it and insert at point.
  161. If FACE is non-nil, propertize returned string with this FACE.
  162. If COLUMN is non-nil and result string is a one-line string
  163. longer than COLUMN, split it into several short lines.
  164. Separate inserted lines with SEPARATOR."
  165. (bui-insert-non-nil value
  166. (let ((strings (bui-split-string (bui-get-string value) column)))
  167. (bui-mapinsert (lambda (str)
  168. (bui-format-insert str face))
  169. strings
  170. (or separator "")))))
  171. ;;; Files and URLs
  172. (defcustom bui-find-file-function #'find-file
  173. "Function used to find a file.
  174. The function is called by `bui-find-file' with a file name as a
  175. single argument."
  176. :type '(choice (function-item find-file)
  177. (function-item org-open-file)
  178. (function :tag "Other function"))
  179. :group 'bui)
  180. (defun bui-find-file (file)
  181. "Find FILE (using `bui-find-file-function') if it exists."
  182. (if (file-exists-p file)
  183. (funcall bui-find-file-function file)
  184. (message "File '%s' does not exist." file)))
  185. ;;; Symbols, keywords, plists
  186. (defun bui-keyword->symbol (keyword)
  187. "Transform KEYWORD into symbol (without leading ':')."
  188. (intern (substring (symbol-name keyword) 1)))
  189. (defun bui-symbol-if-bound (symbol)
  190. "Return SYMBOL if its value is not void, otherwise return nil."
  191. (and (boundp symbol) symbol))
  192. (defun bui-make-symbol (&rest symbols)
  193. "Return symbol by appending SYMBOLS separating them with '-'."
  194. (intern (mapconcat #'symbol-name symbols "-")))
  195. (defun bui-symbol-title (symbol)
  196. "Return SYMBOL's name, a string.
  197. This is like `symbol-name', but fancier."
  198. (if (eq symbol 'id)
  199. "ID"
  200. (let ((str (replace-regexp-in-string "-" " " (symbol-name symbol))))
  201. (concat (capitalize (substring str 0 1))
  202. (substring str 1)))))
  203. (defmacro bui-plist-let (args varlist &rest body)
  204. "Parse ARGS, bind variables from VARLIST and eval BODY.
  205. Find keyword values in ARGS, bind them to variables according to
  206. VARLIST, then evaluate BODY.
  207. ARGS is a keyword/value property list.
  208. Each element of VARLIST has a form:
  209. (SYMBOL KEYWORD [DEFAULT-VALUE])
  210. SYMBOL is a varible name. KEYWORD is a symbol that will be
  211. searched in ARGS for an according value. If the value of KEYWORD
  212. does not exist, bind SYMBOL to DEFAULT-VALUE or nil.
  213. The rest arguments (that present in ARGS but not in VARLIST) will
  214. be bound to `%foreign-args' variable.
  215. Example:
  216. (bui-plist-let '(:two 8 :great ! :bui is)
  217. ((one :one 1)
  218. (two :two 2)
  219. (foo :smth))
  220. (list one two foo %foreign-args))
  221. => (1 8 nil (:bui is :great !))"
  222. (declare (indent 2))
  223. (let ((args-var (make-symbol "args")))
  224. `(let (,@(mapcar (lambda (spec)
  225. (pcase-let ((`(,name ,_ ,val) spec))
  226. (list name val)))
  227. varlist)
  228. (,args-var ,args)
  229. %foreign-args)
  230. (while ,args-var
  231. (pcase ,args-var
  232. (`(,key ,val . ,rest-args)
  233. (cl-case key
  234. ,@(mapcar (lambda (spec)
  235. (pcase-let ((`(,name ,key ,_) spec))
  236. `(,key (setq ,name val))))
  237. varlist)
  238. (t (setq %foreign-args
  239. (cl-list* key val %foreign-args))))
  240. (setq ,args-var rest-args))))
  241. ,@body)))
  242. (defun bui-map-plist (function plist)
  243. "Apply FUNCTION to each keyword/value pair from PLIST.
  244. Return a list of the results."
  245. ;; (cl-loop for lst on plist by #'cddr
  246. ;; collect
  247. ;; (let ((key (car lst))
  248. ;; (val (cadr lst)))
  249. ;; (funcall function key val)))
  250. ;; Use recursion (and `pcase') instead of the above variant as it is
  251. ;; more clean and it should be OK for plists as they are not too big.
  252. (pcase plist
  253. (`(,key ,val . ,rest)
  254. (cons (funcall function key val)
  255. (bui-map-plist function rest)))))
  256. ;;; Alist procedures
  257. (defmacro bui-define-alist-accessor (name assoc-fun)
  258. "Define NAME function to access alist values using ASSOC-FUN."
  259. `(defun ,name (alist &rest keys)
  260. ,(format "Return value from ALIST by KEYS using `%s'.
  261. ALIST is alist of alists of alists ... which can be consecutively
  262. accessed with KEYS."
  263. assoc-fun)
  264. (if (or (null alist) (null keys))
  265. alist
  266. (apply #',name
  267. (cdr (,assoc-fun (car keys) alist))
  268. (cdr keys)))))
  269. (bui-define-alist-accessor bui-assq-value assq)
  270. (bui-define-alist-accessor bui-assoc-value assoc)
  271. ;;; Misc
  272. (defun bui-fill-column ()
  273. "Return fill column for the current window."
  274. (min (window-width) fill-column))
  275. (defun bui-filter (list &rest predicates)
  276. "Apply PREDICATES to all elements from LIST.
  277. Return a list of elements which satisfy all the PREDICATES."
  278. (if (null predicates)
  279. list
  280. (-filter (lambda (element)
  281. (--every? (funcall it element) predicates))
  282. list)))
  283. (defun bui-copy-as-kill (string &optional no-message?)
  284. "Put STRING into `kill-ring'.
  285. If NO-MESSAGE? is non-nil, do not display a message about it."
  286. (kill-new string)
  287. (unless no-message?
  288. (message "'%s' has been added to kill ring." string)))
  289. (defmacro bui-define-groups (name &rest args)
  290. "Define `NAME' and `NAME-faces' customization groups.
  291. NAME should be a symbol.
  292. Remaining arguments (ARGS) should have a form [KEYWORD VALUE] ...
  293. Optional keywords:
  294. - `:parent-group' - name of a parent custom group.
  295. - `:parent-faces-group' - name of a parent custom faces group.
  296. - `:group-doc' - docstring of the `NAME' group.
  297. - `:faces-group-doc' - docstring of the `NAME-faces' group."
  298. (declare (indent 1))
  299. (let* ((name-str (symbol-name name))
  300. (faces-name (intern (concat name-str "-faces"))))
  301. (bui-plist-let args
  302. ((parent-group :parent-group 'bui)
  303. (parent-faces-group :parent-faces-group 'bui-faces)
  304. (group-doc :group-doc
  305. (format "Settings for '%s' buffers."
  306. name-str))
  307. (faces-group-doc :faces-group-doc
  308. (format "Faces for '%s' buffers."
  309. name-str)))
  310. `(progn
  311. (defgroup ,name nil
  312. ,group-doc
  313. :group ',parent-group)
  314. (defgroup ,faces-name nil
  315. ,faces-group-doc
  316. :group ',name
  317. :group ',parent-faces-group)))))
  318. (cl-defun bui-inherit-defvar-clause (symbol parent &key group
  319. (value nil value-bound?))
  320. "Return `defvar' clause for SYMBOL inheriting it from PARENT symbol.
  321. Take docstring and value (unless VALUE is specified) from PARENT.
  322. If custom GROUP is non-nil and PARENT symbol has custom type,
  323. return `defcustom' clause instead."
  324. (let* ((val (if value-bound?
  325. value
  326. (symbol-value parent)))
  327. (val-null? (and value-bound? (null value)))
  328. (doc (documentation-property parent 'variable-documentation))
  329. (doc (if val-null?
  330. (concat doc (format "\nIf nil, use `%S'." parent))
  331. doc))
  332. (type (and group (get parent 'custom-type)))
  333. (type (if (and val-null?
  334. type
  335. (not (eq type 'boolean)))
  336. `(choice ,type (const nil))
  337. type)))
  338. (if type
  339. `(defcustom ,symbol ,val ,doc
  340. :type ',type
  341. :group ',group)
  342. `(defvar ,symbol ,val ,doc))))
  343. (defvar bui-utils-font-lock-keywords
  344. (eval-when-compile
  345. `((,(rx "(" (group (or "bui-with-indent"
  346. "bui-get-non-nil"
  347. "bui-insert-non-nil"
  348. "bui-plist-let"
  349. "bui-define-groups"))
  350. symbol-end)
  351. . 1))))
  352. (font-lock-add-keywords 'emacs-lisp-mode bui-utils-font-lock-keywords)
  353. (provide 'bui-utils)
  354. ;;; bui-utils.el ends here