org-macro.el 12 KB

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