bui-utils.el 16 KB

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