org-macro.el 13 KB

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