org-macro.el 15 KB

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