org-macro.el 14 KB

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