org-macro.el 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  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" "(eval (org-entry-get nil \"$1\" 'selective))")
  106. (cons "time" "(eval (format-time-string \"$1\"))")))
  107. (let ((visited-file (buffer-file-name (buffer-base-buffer))))
  108. (when (and visited-file (file-exists-p visited-file))
  109. (mapc update-templates
  110. (list (cons "input-file" (file-name-nondirectory visited-file))
  111. (cons "modification-time"
  112. (format "(eval (format-time-string \"$1\" '%s))"
  113. (prin1-to-string
  114. (nth 5 (file-attributes visited-file)))))))))
  115. (setq org-macro-templates templates)))
  116. (defun org-macro-expand (macro templates)
  117. "Return expanded MACRO, as a string.
  118. MACRO is an object, obtained, for example, with
  119. `org-element-context'. TEMPLATES is an alist of templates used
  120. for expansion. See `org-macro-templates' for a buffer-local
  121. default value. Return nil if no template was found."
  122. (let ((template
  123. ;; Macro names are case-insensitive.
  124. (cdr (assoc-string (org-element-property :key macro) templates t))))
  125. (when template
  126. (let ((value (replace-regexp-in-string
  127. "\\$[0-9]+"
  128. (lambda (arg)
  129. (or (nth (1- (string-to-number (substring arg 1)))
  130. (org-element-property :args macro))
  131. ;; No argument: remove place-holder.
  132. ""))
  133. template nil 'literal)))
  134. ;; VALUE starts with "(eval": it is a s-exp, `eval' it.
  135. (when (string-match "\\`(eval\\>" value)
  136. (setq value (eval (read value))))
  137. ;; Return string.
  138. (format "%s" (or value ""))))))
  139. (defun org-macro-replace-all (templates &optional finalize keywords)
  140. "Replace all macros in current buffer by their expansion.
  141. TEMPLATES is an alist of templates used for expansion. See
  142. `org-macro-templates' for a buffer-local default value.
  143. If optional arg FINALIZE is non-nil, raise an error if a macro is
  144. found in the buffer with no definition in TEMPLATES.
  145. Optional argument KEYWORDS, when non-nil is a list of keywords,
  146. as strings, where macro expansion is allowed."
  147. (save-excursion
  148. (goto-char (point-min))
  149. (let ((properties-regexp
  150. (format "\\`EXPORT_%s\\+?\\'" (regexp-opt keywords)))
  151. record)
  152. (while (re-search-forward "{{{[-A-Za-z0-9_]" nil t)
  153. (let* ((datum (save-match-data (org-element-context)))
  154. (type (org-element-type datum))
  155. (macro
  156. (cond
  157. ((eq type 'macro) datum)
  158. ;; In parsed keywords and associated node properties,
  159. ;; force macro recognition.
  160. ((or (and (eq type 'keyword)
  161. (member (org-element-property :key datum) keywords))
  162. (and (eq type 'node-property)
  163. (org-string-match-p
  164. properties-regexp
  165. (org-element-property :key datum))))
  166. (save-restriction
  167. (narrow-to-region (match-beginning 0) (line-end-position))
  168. (org-element-map (org-element-parse-buffer) 'macro
  169. #'identity nil t))))))
  170. (when macro
  171. (let* ((value (org-macro-expand macro templates))
  172. (begin (org-element-property :begin macro))
  173. (signature (list begin
  174. macro
  175. (org-element-property :args macro))))
  176. ;; Avoid circular dependencies by checking if the same
  177. ;; macro with the same arguments is expanded at the same
  178. ;; position twice.
  179. (cond ((member signature record)
  180. (error "Circular macro expansion: %s"
  181. (org-element-property :key macro)))
  182. (value
  183. (push signature record)
  184. (delete-region
  185. begin
  186. ;; Preserve white spaces after the macro.
  187. (progn (goto-char (org-element-property :end macro))
  188. (skip-chars-backward " \t")
  189. (point)))
  190. ;; Leave point before replacement in case of
  191. ;; recursive expansions.
  192. (save-excursion (insert value)))
  193. (finalize
  194. (error "Undefined Org macro: %s; aborting"
  195. (org-element-property :key macro)))))))))))
  196. (defun org-macro-escape-arguments (&rest args)
  197. "Build macro's arguments string from ARGS.
  198. ARGS are strings. Return value is a string with arguments
  199. properly escaped and separated with commas. This is the opposite
  200. of `org-macro-extract-arguments'."
  201. (let ((s ""))
  202. (dolist (arg (reverse args) (substring s 1))
  203. (setq s
  204. (concat
  205. ","
  206. (replace-regexp-in-string
  207. "\\(\\\\*\\),"
  208. (lambda (m)
  209. (concat (make-string (1+ (* 2 (length (match-string 1 m)))) ?\\)
  210. ","))
  211. ;; If a non-terminal argument ends on backslashes, make
  212. ;; sure to also escape them as they will be followed by
  213. ;; a comma.
  214. (concat arg (and (not (equal s ""))
  215. (string-match "\\\\+\\'" arg)
  216. (match-string 0 arg)))
  217. nil t)
  218. s)))))
  219. (defun org-macro-extract-arguments (s)
  220. "Extract macro arguments from string S.
  221. S is a string containing comma separated values properly escaped.
  222. Return a list of arguments, as strings. This is the opposite of
  223. `org-macro-escape-arguments'."
  224. ;; Do not use `org-split-string' since empty strings are
  225. ;; meaningful here.
  226. (split-string
  227. (replace-regexp-in-string
  228. "\\(\\\\*\\),"
  229. (lambda (str)
  230. (let ((len (length (match-string 1 str))))
  231. (concat (make-string (/ len 2) ?\\)
  232. (if (zerop (mod len 2)) "\000" ","))))
  233. s nil t)
  234. "\000"))
  235. (provide 'org-macro)
  236. ;;; org-macro.el ends here