org-macro.el 16 KB

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