org-macro.el 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. ;;; org-macro.el --- Macro Replacement Code for Org -*- lexical-binding: t; -*-
  2. ;; Copyright (C) 2013-2022 Free Software Foundation, Inc.
  3. ;; Author: Nicolas Goaziou <n.goaziou@gmail.com>
  4. ;; Keywords: outlines, hypermedia, calendar, wp
  5. ;; This file is part of GNU Emacs.
  6. ;; GNU Emacs is free software: you can redistribute it and/or modify
  7. ;; it under the terms of the GNU General Public License as published by
  8. ;; the Free Software Foundation, either version 3 of the License, or
  9. ;; (at your option) any later version.
  10. ;; GNU Emacs is distributed in the hope that it will be useful,
  11. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. ;; GNU General Public License for more details.
  14. ;; You should have received a copy of the GNU General Public License
  15. ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
  16. ;;; Commentary:
  17. ;; Macros are expanded with `org-macro-replace-all', which relies
  18. ;; internally on `org-macro-expand'.
  19. ;; Default templates for expansion are stored in the buffer-local
  20. ;; variable `org-macro-templates'. This variable is updated by
  21. ;; `org-macro-initialize-templates', which recursively calls
  22. ;; `org-macro--collect-macros' in order to read setup files.
  23. ;; Argument in macros are separated with commas. Proper escaping rules
  24. ;; are implemented in `org-macro-escape-arguments' and arguments can
  25. ;; be extracted from a string with `org-macro-extract-arguments'.
  26. ;; Along with macros defined through #+MACRO: keyword, default
  27. ;; templates include the following hard-coded macros:
  28. ;; {{{time(format-string)}}},
  29. ;; {{{property(node-property)}}},
  30. ;; {{{input-file}}},
  31. ;; {{{modification-time(format-string)}}},
  32. ;; {{{n(counter,action}}}.
  33. ;; Upon exporting, "ox.el" will also provide {{{author}}}, {{{date}}},
  34. ;; {{{email}}} and {{{title}}} macros.
  35. ;;; Code:
  36. (require 'cl-lib)
  37. (require 'org-macs)
  38. (require 'org-compat)
  39. (declare-function org-collect-keywords "org" (keywords &optional unique directory))
  40. (declare-function org-element-at-point "org-element" ())
  41. (declare-function org-element-context "org-element" (&optional element))
  42. (declare-function org-element-copy "org-element" (datum))
  43. (declare-function org-element-macro-parser "org-element" ())
  44. (declare-function org-element-parse-secondary-string "org-element" (string restriction &optional parent))
  45. (declare-function org-element-property "org-element" (property element))
  46. (declare-function org-element-restriction "org-element" (element))
  47. (declare-function org-element-type "org-element" (element))
  48. (declare-function org-entry-get "org" (pom property &optional inherit literal-nil))
  49. (declare-function org-file-contents "org" (file &optional noerror nocache))
  50. (declare-function org-in-commented-heading-p "org" (&optional no-inheritance))
  51. (declare-function org-link-search "ol" (s &optional avoid-pos stealth))
  52. (declare-function org-mode "org" ())
  53. (declare-function vc-backend "vc-hooks" (f))
  54. (declare-function vc-call "vc-hooks" (fun file &rest args) t)
  55. (declare-function vc-exec-after "vc-dispatcher" (code &optional success))
  56. (defvar org-link-search-must-match-exact-headline)
  57. ;;; Variables
  58. (defvar-local org-macro-templates nil
  59. "Alist containing all macro templates in current buffer.
  60. Associations are in the shape of (NAME . TEMPLATE) where NAME
  61. stands for macro's name and template for its replacement value,
  62. both as strings. This is an internal variable. Do not set it
  63. directly, use instead:
  64. #+MACRO: name template")
  65. ;;; Functions
  66. (defun org-macro--makeargs (template)
  67. "Compute the formal arglist to use for TEMPLATE."
  68. (let ((max 0) (i 0))
  69. (while (string-match "\\$\\([0-9]+\\)" template i)
  70. (setq i (match-end 0))
  71. (setq max (max max (string-to-number (match-string 1 template)))))
  72. (let ((args '(&rest _)))
  73. (if (< max 1) args ;Avoid `&optional &rest', refused by Emacs-26!
  74. (while (> max 0)
  75. (push (intern (format "$%d" max)) args)
  76. (setq max (1- max)))
  77. (cons '&optional args)))))
  78. (defun org-macro--set-templates (templates)
  79. "Set template for the macro NAME.
  80. VALUE is the template of the macro. The new value override the
  81. previous one, unless VALUE is nil. Return the updated list."
  82. (let ((new-templates nil))
  83. (pcase-dolist (`(,name . ,value) templates)
  84. (let ((old-definition (assoc name new-templates)))
  85. (when (and (stringp value) (string-match-p "\\`(eval\\>" value))
  86. ;; Pre-process the evaluation form for faster macro expansion.
  87. (let* ((args (org-macro--makeargs value))
  88. (body
  89. (condition-case nil
  90. ;; `value' is of the form "(eval ...)" but we
  91. ;; don't want this to mean to pass the result to
  92. ;; `eval' (which would cause double evaluation),
  93. ;; so we strip the `eval' away with `cadr'.
  94. (cadr (read value))
  95. (error
  96. (user-error "Invalid definition for macro %S" name)))))
  97. (setq value (eval (macroexpand-all `(lambda ,args ,body)) t))))
  98. (cond ((and value old-definition) (setcdr old-definition value))
  99. (old-definition)
  100. (t (push (cons name (or value "")) new-templates)))))
  101. new-templates))
  102. (defun org-macro--collect-macros ()
  103. "Collect macro definitions in current buffer and setup files.
  104. Return an alist containing all macro templates found."
  105. (let ((templates
  106. `(("author" . ,(org-macro--find-keyword-value "AUTHOR" t))
  107. ("email" . ,(org-macro--find-keyword-value "EMAIL"))
  108. ("title" . ,(org-macro--find-keyword-value "TITLE" t))
  109. ("date" . ,(org-macro--find-date)))))
  110. (pcase (org-collect-keywords '("MACRO"))
  111. (`(("MACRO" . ,values))
  112. (dolist (value values)
  113. (when (string-match "^\\(\\S-+\\)[ \t]*" value)
  114. (let ((name (match-string 1 value))
  115. (definition (substring value (match-end 0))))
  116. (push (cons name definition) templates))))))
  117. templates))
  118. (defun org-macro-initialize-templates (&optional default)
  119. "Collect macro templates defined in current buffer.
  120. DEFAULT is a list of globally available templates.
  121. Templates are stored in buffer-local variable `org-macro-templates'.
  122. In addition to buffer-defined macros, the function installs the
  123. following ones: \"n\", \"author\", \"email\", \"keyword\",
  124. \"time\", \"property\", and, if the buffer is associated to
  125. a file, \"input-file\" and \"modification-time\"."
  126. (require 'org-element)
  127. (org-macro--counter-initialize) ;for "n" macro
  128. (setq org-macro-templates
  129. (nconc
  130. ;; Install user-defined macros. Local macros have higher
  131. ;; precedence than global ones.
  132. (org-macro--set-templates (append default (org-macro--collect-macros)))
  133. ;; Install file-specific macros.
  134. (let ((visited-file (buffer-file-name (buffer-base-buffer))))
  135. (and visited-file
  136. (file-exists-p visited-file)
  137. (list
  138. `("input-file" . ,(file-name-nondirectory visited-file))
  139. `("modification-time" .
  140. ,(let ((modtime (file-attribute-modification-time
  141. (file-attributes visited-file))))
  142. (lambda (arg1 &optional arg2 &rest _)
  143. (format-time-string
  144. arg1
  145. (or (and (org-string-nw-p arg2)
  146. (org-macro--vc-modified-time visited-file))
  147. modtime))))))))
  148. ;; Install generic macros.
  149. '(("keyword" . (lambda (arg1 &rest _)
  150. (org-macro--find-keyword-value arg1 t)))
  151. ("n" . (lambda (&optional arg1 arg2 &rest _)
  152. (org-macro--counter-increment arg1 arg2)))
  153. ("property" . (lambda (arg1 &optional arg2 &rest _)
  154. (org-macro--get-property arg1 arg2)))
  155. ("time" . (lambda (arg1 &rest _)
  156. (format-time-string arg1)))))))
  157. (defun org-macro-expand (macro templates)
  158. "Return expanded MACRO, as a string.
  159. MACRO is an object, obtained, for example, with
  160. `org-element-context'. TEMPLATES is an alist of templates used
  161. for expansion. See `org-macro-templates' for a buffer-local
  162. default value. Return nil if no template was found."
  163. (let ((template
  164. ;; Macro names are case-insensitive.
  165. (cdr (assoc-string (org-element-property :key macro) templates t))))
  166. (when template
  167. (let* ((value
  168. (if (functionp template)
  169. (apply template (org-element-property :args macro))
  170. (replace-regexp-in-string
  171. "\\$[0-9]+"
  172. (lambda (m)
  173. (or (nth (1- (string-to-number (substring m 1)))
  174. (org-element-property :args macro))
  175. ;; No argument: remove place-holder.
  176. ""))
  177. template nil 'literal))))
  178. ;; Force return value to be a string.
  179. (format "%s" (or value ""))))))
  180. (defun org-macro-replace-all (templates &optional keywords)
  181. "Replace all macros in current buffer by their expansion.
  182. TEMPLATES is an alist of templates used for expansion. See
  183. `org-macro-templates' for a buffer-local default value.
  184. Optional argument KEYWORDS, when non-nil is a list of keywords,
  185. as strings, where macro expansion is allowed.
  186. Return an error if a macro in the buffer cannot be associated to
  187. a definition in TEMPLATES."
  188. (org-with-wide-buffer
  189. (goto-char (point-min))
  190. (let ((properties-regexp (format "\\`EXPORT_%s\\+?\\'"
  191. (regexp-opt keywords)))
  192. record)
  193. (while (re-search-forward "{{{[-A-Za-z0-9_]" nil t)
  194. (unless (save-match-data (org-in-commented-heading-p))
  195. (let* ((datum (save-match-data (org-element-context)))
  196. (type (org-element-type datum))
  197. (macro
  198. (cond
  199. ((eq type 'macro) datum)
  200. ;; In parsed keywords and associated node
  201. ;; properties, force macro recognition.
  202. ((or (and (eq type 'keyword)
  203. (member (org-element-property :key datum) keywords))
  204. (and (eq type 'node-property)
  205. (string-match-p properties-regexp
  206. (org-element-property :key datum))))
  207. (save-excursion
  208. (goto-char (match-beginning 0))
  209. (org-element-macro-parser))))))
  210. (when macro
  211. (let* ((key (org-element-property :key macro))
  212. (value (org-macro-expand macro templates))
  213. (begin (org-element-property :begin macro))
  214. (signature (list begin
  215. macro
  216. (org-element-property :args macro))))
  217. ;; Avoid circular dependencies by checking if the same
  218. ;; macro with the same arguments is expanded at the
  219. ;; same position twice.
  220. (cond ((member signature record)
  221. (error "Circular macro expansion: %s" key))
  222. (value
  223. (push signature record)
  224. (delete-region
  225. begin
  226. ;; Preserve white spaces after the macro.
  227. (progn (goto-char (org-element-property :end macro))
  228. (skip-chars-backward " \t")
  229. (point)))
  230. ;; Leave point before replacement in case of
  231. ;; recursive expansions.
  232. (save-excursion (insert value)))
  233. ;; Special "results" macro: if it is not defined,
  234. ;; simply leave it as-is. It will be expanded in
  235. ;; a second phase.
  236. ((equal key "results"))
  237. (t
  238. (error "Undefined Org macro: %s; aborting"
  239. (org-element-property :key macro))))))))))))
  240. (defun org-macro-escape-arguments (&rest args)
  241. "Build macro's arguments string from ARGS.
  242. ARGS are strings. Return value is a string with arguments
  243. properly escaped and separated with commas. This is the opposite
  244. of `org-macro-extract-arguments'."
  245. (let ((s ""))
  246. (dolist (arg (reverse args) (substring s 1))
  247. (setq s
  248. (concat
  249. ","
  250. (replace-regexp-in-string
  251. "\\(\\\\*\\),"
  252. (lambda (m)
  253. (concat (make-string (1+ (* 2 (length (match-string 1 m)))) ?\\)
  254. ","))
  255. ;; If a non-terminal argument ends on backslashes, make
  256. ;; sure to also escape them as they will be followed by
  257. ;; a comma.
  258. (concat arg (and (not (equal s ""))
  259. (string-match "\\\\+\\'" arg)
  260. (match-string 0 arg)))
  261. nil t)
  262. s)))))
  263. (defun org-macro-extract-arguments (s)
  264. "Extract macro arguments from string S.
  265. S is a string containing comma separated values properly escaped.
  266. Return a list of arguments, as strings. This is the opposite of
  267. `org-macro-escape-arguments'."
  268. ;; Do not use `org-split-string' since empty strings are
  269. ;; meaningful here.
  270. (split-string
  271. (replace-regexp-in-string
  272. "\\(\\\\*\\),"
  273. (lambda (str)
  274. (let ((len (length (match-string 1 str))))
  275. (concat (make-string (/ len 2) ?\\)
  276. (if (zerop (mod len 2)) "\000" ","))))
  277. s nil t)
  278. "\000"))
  279. ;;; Helper functions and variables for internal macros
  280. (defun org-macro--get-property (property location)
  281. "Find PROPERTY's value at LOCATION.
  282. PROPERTY is a string. LOCATION is a search string, as expected
  283. by `org-link-search', or the empty string."
  284. (save-excursion
  285. (when (org-string-nw-p location)
  286. (condition-case _
  287. (let ((org-link-search-must-match-exact-headline t))
  288. (org-link-search location nil t))
  289. (error
  290. (error "Macro property failed: cannot find location %s" location))))
  291. (org-entry-get nil property 'selective)))
  292. (defun org-macro--find-keyword-value (name &optional collect)
  293. "Find value for keyword NAME in current buffer.
  294. Return value associated to the keywords named after NAME, as
  295. a string, or nil. When optional argument COLLECT is non-nil,
  296. concatenate values, separated with a space, from various keywords
  297. in the buffer."
  298. (org-with-point-at 1
  299. (let ((regexp (format "^[ \t]*#\\+%s:" (regexp-quote name)))
  300. (case-fold-search t)
  301. (result nil))
  302. (catch :exit
  303. (while (re-search-forward regexp nil t)
  304. (let ((element (org-element-at-point)))
  305. (when (eq 'keyword (org-element-type element))
  306. (let ((value (org-element-property :value element)))
  307. (if (not collect) (throw :exit value)
  308. (setq result (concat result " " value)))))))
  309. (and result (org-trim result))))))
  310. (defun org-macro--find-date ()
  311. "Find value for DATE in current buffer.
  312. Return value as a string."
  313. (let* ((value (org-macro--find-keyword-value "DATE"))
  314. (date (org-element-parse-secondary-string
  315. value (org-element-restriction 'keyword))))
  316. (if (and (consp date)
  317. (not (cdr date))
  318. (eq 'timestamp (org-element-type (car date))))
  319. (format "(eval (if (org-string-nw-p $1) %s %S))"
  320. (format "(org-timestamp-format '%S $1)"
  321. (org-element-copy (car date)))
  322. value)
  323. value)))
  324. (defun org-macro--vc-modified-time (file)
  325. (save-window-excursion
  326. (when (vc-backend file)
  327. (let ((buf (get-buffer-create " *org-vc*"))
  328. (case-fold-search t)
  329. date)
  330. (unwind-protect
  331. (progn
  332. (vc-call print-log (list file) buf nil nil 1)
  333. (with-current-buffer buf
  334. (vc-exec-after
  335. (lambda ()
  336. (goto-char (point-min))
  337. (when (re-search-forward "Date:?[ \t]*" nil t)
  338. (let ((time (parse-time-string
  339. (buffer-substring
  340. (point) (line-end-position)))))
  341. (when (cl-some #'identity time)
  342. (setq date (apply #'encode-time time))))))))
  343. (let ((proc (get-buffer-process buf)))
  344. (while (and proc (accept-process-output proc .5 nil t)))))
  345. (kill-buffer buf))
  346. date))))
  347. (defvar org-macro--counter-table nil
  348. "Hash table containing counter value per name.")
  349. (defun org-macro--counter-initialize ()
  350. "Initialize `org-macro--counter-table'."
  351. (setq org-macro--counter-table (make-hash-table :test #'equal)))
  352. (defun org-macro--counter-increment (name &optional action)
  353. "Increment counter NAME.
  354. NAME is a string identifying the counter.
  355. When non-nil, optional argument ACTION is a string.
  356. If the string is \"-\", keep the NAME counter at its current
  357. value, i.e. do not increment.
  358. If the string represents an integer, set the counter to this number.
  359. Any other non-empty string resets the counter to 1."
  360. (let ((name-trimmed (if (stringp name) (org-trim name) ""))
  361. (action-trimmed (when (org-string-nw-p action)
  362. (org-trim action))))
  363. (puthash name-trimmed
  364. (cond ((not (org-string-nw-p action-trimmed))
  365. (1+ (gethash name-trimmed org-macro--counter-table 0)))
  366. ((string= "-" action-trimmed)
  367. (gethash name-trimmed org-macro--counter-table 1))
  368. ((string-match-p "\\`[0-9]+\\'" action-trimmed)
  369. (string-to-number action-trimmed))
  370. (t 1))
  371. org-macro--counter-table)))
  372. (provide 'org-macro)
  373. ;;; org-macro.el ends here