org-macro.el 17 KB

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