org-macro.el 15 KB

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