org-macro.el 15 KB

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