org-macro.el 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. ;;; org-macro.el --- Macro Replacement Code for Org Mode
  2. ;; Copyright (C) 2013-2015 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)}}}, {{{property(node-property)}}},
  29. ;; {{{input-file}}} and {{{modification-time(format-string)}}}.
  30. ;; Upon exporting, "ox.el" will also provide {{{author}}}, {{{date}}},
  31. ;; {{{email}}} and {{{title}}} macros.
  32. ;;; Code:
  33. (require 'org-macs)
  34. (declare-function org-element-at-point "org-element" ())
  35. (declare-function org-element-context "org-element" (&optional element))
  36. (declare-function org-element-property "org-element" (property element))
  37. (declare-function org-element-type "org-element" (element))
  38. (declare-function org-remove-double-quotes "org" (s))
  39. (declare-function org-mode "org" ())
  40. (declare-function org-file-contents "org" (file &optional noerror))
  41. (declare-function org-with-wide-buffer "org-macs" (&rest body))
  42. ;;; Variables
  43. (defvar org-macro-templates nil
  44. "Alist containing all macro templates in current buffer.
  45. Associations are in the shape of (NAME . TEMPLATE) where NAME
  46. stands for macro's name and template for its replacement value,
  47. both as strings. This is an internal variable. Do not set it
  48. directly, use instead:
  49. #+MACRO: name template")
  50. (make-variable-buffer-local 'org-macro-templates)
  51. ;;; Functions
  52. (defun org-macro--collect-macros ()
  53. "Collect macro definitions in current buffer and setup files.
  54. Return an alist containing all macro templates found."
  55. (let* (collect-macros ; For byte-compiler.
  56. (collect-macros
  57. (lambda (files templates)
  58. ;; Return an alist of macro templates. FILES is a list of
  59. ;; setup files names read so far, used to avoid circular
  60. ;; dependencies. TEMPLATES is the alist collected so far.
  61. (let ((case-fold-search t))
  62. (org-with-wide-buffer
  63. (goto-char (point-min))
  64. (while (re-search-forward
  65. "^[ \t]*#\\+\\(MACRO\\|SETUPFILE\\):" nil t)
  66. (let ((element (org-element-at-point)))
  67. (when (eq (org-element-type element) 'keyword)
  68. (let ((val (org-element-property :value element)))
  69. (if (equal (org-element-property :key element) "MACRO")
  70. ;; Install macro in TEMPLATES.
  71. (when (string-match
  72. "^\\(.*?\\)\\(?:\\s-+\\(.*\\)\\)?\\s-*$" val)
  73. (let* ((name (match-string 1 val))
  74. (template (or (match-string 2 val) ""))
  75. (old-cell (assoc name templates)))
  76. (if old-cell (setcdr old-cell template)
  77. (push (cons name template) templates))))
  78. ;; Enter setup file.
  79. (let ((file (expand-file-name
  80. (org-remove-double-quotes val))))
  81. (unless (member file files)
  82. (with-temp-buffer
  83. (org-mode)
  84. (insert (org-file-contents file 'noerror))
  85. (setq templates
  86. (funcall collect-macros (cons file files)
  87. templates)))))))))))
  88. templates))))
  89. (funcall collect-macros nil nil)))
  90. (defun org-macro-initialize-templates ()
  91. "Collect macro templates defined in current buffer.
  92. Templates are stored in buffer-local variable
  93. `org-macro-templates'. In addition to buffer-defined macros, the
  94. function installs the following ones: \"property\",
  95. \"time\". and, if the buffer is associated to a file,
  96. \"input-file\" and \"modification-time\"."
  97. (let* ((templates (org-macro--collect-macros))
  98. (update-templates
  99. (lambda (cell)
  100. (let ((old-template (assoc (car cell) templates)))
  101. (if old-template (setcdr old-template (cdr cell))
  102. (push cell templates))))))
  103. ;; Install hard-coded macros.
  104. (mapc update-templates
  105. (list (cons "property"
  106. "(eval (save-excursion
  107. (let ((l \"$2\"))
  108. (when (org-string-nw-p l)
  109. (condition-case _
  110. (let ((org-link-search-must-match-exact-headline t))
  111. (org-link-search l nil nil t))
  112. (error
  113. (error \"Macro property failed: cannot find location %s\"
  114. l)))))
  115. (org-entry-get nil \"$1\" 'selective)))")
  116. (cons "time" "(eval (format-time-string \"$1\"))")))
  117. (let ((visited-file (buffer-file-name (buffer-base-buffer))))
  118. (when (and visited-file (file-exists-p visited-file))
  119. (mapc update-templates
  120. (list (cons "input-file" (file-name-nondirectory visited-file))
  121. (cons "modification-time"
  122. (format "(eval (format-time-string \"$1\" '%s))"
  123. (prin1-to-string
  124. (nth 5 (file-attributes visited-file)))))))))
  125. (setq org-macro-templates templates)))
  126. (defun org-macro-expand (macro templates)
  127. "Return expanded MACRO, as a string.
  128. MACRO is an object, obtained, for example, with
  129. `org-element-context'. TEMPLATES is an alist of templates used
  130. for expansion. See `org-macro-templates' for a buffer-local
  131. default value. Return nil if no template was found."
  132. (let ((template
  133. ;; Macro names are case-insensitive.
  134. (cdr (assoc-string (org-element-property :key macro) templates t))))
  135. (when template
  136. (let ((value (replace-regexp-in-string
  137. "\\$[0-9]+"
  138. (lambda (arg)
  139. (or (nth (1- (string-to-number (substring arg 1)))
  140. (org-element-property :args macro))
  141. ;; No argument: remove place-holder.
  142. ""))
  143. template nil 'literal)))
  144. ;; VALUE starts with "(eval": it is a s-exp, `eval' it.
  145. (when (string-match "\\`(eval\\>" value)
  146. (setq value (eval (read value))))
  147. ;; Return string.
  148. (format "%s" (or value ""))))))
  149. (defun org-macro-replace-all (templates &optional finalize keywords)
  150. "Replace all macros in current buffer by their expansion.
  151. TEMPLATES is an alist of templates used for expansion. See
  152. `org-macro-templates' for a buffer-local default value.
  153. If optional arg FINALIZE is non-nil, raise an error if a macro is
  154. found in the buffer with no definition in TEMPLATES.
  155. Optional argument KEYWORDS, when non-nil is a list of keywords,
  156. as strings, where macro expansion is allowed."
  157. (save-excursion
  158. (goto-char (point-min))
  159. (let ((properties-regexp
  160. (format "\\`EXPORT_%s\\+?\\'" (regexp-opt keywords)))
  161. record)
  162. (while (re-search-forward "{{{[-A-Za-z0-9_]" nil t)
  163. (let* ((datum (save-match-data (org-element-context)))
  164. (type (org-element-type datum))
  165. (macro
  166. (cond
  167. ((eq type 'macro) datum)
  168. ;; In parsed keywords and associated node properties,
  169. ;; force macro recognition.
  170. ((or (and (eq type 'keyword)
  171. (member (org-element-property :key datum) keywords))
  172. (and (eq type 'node-property)
  173. (org-string-match-p
  174. properties-regexp
  175. (org-element-property :key datum))))
  176. (save-restriction
  177. (narrow-to-region (match-beginning 0) (line-end-position))
  178. (org-element-map (org-element-parse-buffer) 'macro
  179. #'identity nil t))))))
  180. (when macro
  181. (let* ((value (org-macro-expand macro templates))
  182. (begin (org-element-property :begin macro))
  183. (signature (list begin
  184. macro
  185. (org-element-property :args macro))))
  186. ;; Avoid circular dependencies by checking if the same
  187. ;; macro with the same arguments is expanded at the same
  188. ;; position twice.
  189. (cond ((member signature record)
  190. (error "Circular macro expansion: %s"
  191. (org-element-property :key macro)))
  192. (value
  193. (push signature record)
  194. (delete-region
  195. begin
  196. ;; Preserve white spaces after the macro.
  197. (progn (goto-char (org-element-property :end macro))
  198. (skip-chars-backward " \t")
  199. (point)))
  200. ;; Leave point before replacement in case of
  201. ;; recursive expansions.
  202. (save-excursion (insert value)))
  203. (finalize
  204. (error "Undefined Org macro: %s; aborting"
  205. (org-element-property :key macro)))))))))))
  206. (defun org-macro-escape-arguments (&rest args)
  207. "Build macro's arguments string from ARGS.
  208. ARGS are strings. Return value is a string with arguments
  209. properly escaped and separated with commas. This is the opposite
  210. of `org-macro-extract-arguments'."
  211. (let ((s ""))
  212. (dolist (arg (reverse args) (substring s 1))
  213. (setq s
  214. (concat
  215. ","
  216. (replace-regexp-in-string
  217. "\\(\\\\*\\),"
  218. (lambda (m)
  219. (concat (make-string (1+ (* 2 (length (match-string 1 m)))) ?\\)
  220. ","))
  221. ;; If a non-terminal argument ends on backslashes, make
  222. ;; sure to also escape them as they will be followed by
  223. ;; a comma.
  224. (concat arg (and (not (equal s ""))
  225. (string-match "\\\\+\\'" arg)
  226. (match-string 0 arg)))
  227. nil t)
  228. s)))))
  229. (defun org-macro-extract-arguments (s)
  230. "Extract macro arguments from string S.
  231. S is a string containing comma separated values properly escaped.
  232. Return a list of arguments, as strings. This is the opposite of
  233. `org-macro-escape-arguments'."
  234. ;; Do not use `org-split-string' since empty strings are
  235. ;; meaningful here.
  236. (split-string
  237. (replace-regexp-in-string
  238. "\\(\\\\*\\),"
  239. (lambda (str)
  240. (let ((len (length (match-string 1 str))))
  241. (concat (make-string (/ len 2) ?\\)
  242. (if (zerop (mod len 2)) "\000" ","))))
  243. s nil t)
  244. "\000"))
  245. (provide 'org-macro)
  246. ;;; org-macro.el ends here