org-macro.el 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  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. (if (org-in-commented-heading-p) (outline-next-heading)
  67. (let ((element (org-element-at-point)))
  68. (when (eq (org-element-type element) 'keyword)
  69. (let ((val (org-element-property :value element)))
  70. (if (equal (org-element-property :key element) "MACRO")
  71. ;; Install macro in TEMPLATES.
  72. (when (string-match
  73. "^\\(.*?\\)\\(?:\\s-+\\(.*\\)\\)?\\s-*$"
  74. val)
  75. (let* ((name (match-string 1 val))
  76. (template (or (match-string 2 val) ""))
  77. (old-cell (assoc name templates)))
  78. (if old-cell (setcdr old-cell template)
  79. (push (cons name template) templates))))
  80. ;; Enter setup file.
  81. (let ((file (expand-file-name
  82. (org-remove-double-quotes val))))
  83. (unless (member file files)
  84. (with-temp-buffer
  85. (org-mode)
  86. (insert (org-file-contents file 'noerror))
  87. (setq templates
  88. (funcall collect-macros
  89. (cons file files)
  90. templates))))))))))))
  91. templates))))
  92. (funcall collect-macros nil nil)))
  93. (defun org-macro-initialize-templates ()
  94. "Collect macro templates defined in current buffer.
  95. Templates are stored in buffer-local variable
  96. `org-macro-templates'. In addition to buffer-defined macros, the
  97. function installs the following ones: \"property\",
  98. \"time\". and, if the buffer is associated to a file,
  99. \"input-file\" and \"modification-time\"."
  100. (let* ((templates (org-macro--collect-macros))
  101. (update-templates
  102. (lambda (cell)
  103. (let ((old-template (assoc (car cell) templates)))
  104. (if old-template (setcdr old-template (cdr cell))
  105. (push cell templates))))))
  106. ;; Install hard-coded macros.
  107. (mapc (lambda (cell) (funcall update-templates cell))
  108. (list (cons "property" "(eval (org-entry-get nil \"$1\" 'selective))")
  109. (cons "time" "(eval (format-time-string \"$1\"))")))
  110. (let ((visited-file (buffer-file-name (buffer-base-buffer))))
  111. (when (and visited-file (file-exists-p visited-file))
  112. (mapc (lambda (cell) (funcall update-templates cell))
  113. (list (cons "input-file" (file-name-nondirectory visited-file))
  114. (cons "modification-time"
  115. (format "(eval (format-time-string \"$1\" '%s))"
  116. (prin1-to-string
  117. (nth 5 (file-attributes visited-file)))))))))
  118. (setq org-macro-templates templates)))
  119. (defun org-macro-expand (macro templates)
  120. "Return expanded MACRO, as a string.
  121. MACRO is an object, obtained, for example, with
  122. `org-element-context'. TEMPLATES is an alist of templates used
  123. for expansion. See `org-macro-templates' for a buffer-local
  124. default value. Return nil if no template was found."
  125. (let ((template
  126. ;; Macro names are case-insensitive.
  127. (cdr (assoc-string (org-element-property :key macro) templates t))))
  128. (when template
  129. (let ((value (replace-regexp-in-string
  130. "\\$[0-9]+"
  131. (lambda (arg)
  132. (or (nth (1- (string-to-number (substring arg 1)))
  133. (org-element-property :args macro))
  134. ;; No argument: remove place-holder.
  135. ""))
  136. template nil 'literal)))
  137. ;; VALUE starts with "(eval": it is a s-exp, `eval' it.
  138. (when (string-match "\\`(eval\\>" value)
  139. (setq value (eval (read value))))
  140. ;; Return string.
  141. (format "%s" (or value ""))))))
  142. (defun org-macro-replace-all (templates &optional finalize)
  143. "Replace all macros in current buffer by their expansion.
  144. TEMPLATES is an alist of templates used for expansion. See
  145. `org-macro-templates' for a buffer-local default value.
  146. If optional arg FINALIZE is non-nil, raise an error if a macro is
  147. found in the buffer with no definition in TEMPLATES."
  148. (save-excursion
  149. (goto-char (point-min))
  150. (let (record)
  151. (while (re-search-forward "{{{[-A-Za-z0-9_]" nil t)
  152. (let ((object (org-element-context)))
  153. (when (eq (org-element-type object) 'macro)
  154. (let* ((value (org-macro-expand object templates))
  155. (begin (org-element-property :begin object))
  156. (signature (list begin
  157. object
  158. (org-element-property :args object))))
  159. ;; Avoid circular dependencies by checking if the same
  160. ;; macro with the same arguments is expanded at the same
  161. ;; position twice.
  162. (if (member signature record)
  163. (error "Circular macro expansion: %s"
  164. (org-element-property :key object))
  165. (cond (value
  166. (push signature record)
  167. (delete-region
  168. begin
  169. ;; Preserve white spaces after the macro.
  170. (progn (goto-char (org-element-property :end object))
  171. (skip-chars-backward " \t")
  172. (point)))
  173. ;; Leave point before replacement in case of recursive
  174. ;; expansions.
  175. (save-excursion (insert value)))
  176. (finalize
  177. (error "Undefined Org macro: %s; aborting"
  178. (org-element-property :key object))))))))))))
  179. (defun org-macro-escape-arguments (&rest args)
  180. "Build macro's arguments string from ARGS.
  181. ARGS are strings. Return value is a string with arguments
  182. properly escaped and separated with commas. This is the opposite
  183. of `org-macro-extract-arguments'."
  184. (let ((s ""))
  185. (dolist (arg (reverse args) (substring s 1))
  186. (setq s
  187. (concat
  188. ","
  189. (replace-regexp-in-string
  190. "\\(\\\\*\\),"
  191. (lambda (m)
  192. (concat (make-string (1+ (* 2 (length (match-string 1 m)))) ?\\)
  193. ","))
  194. ;; If a non-terminal argument ends on backslashes, make
  195. ;; sure to also escape them as they will be followed by
  196. ;; a comma.
  197. (concat arg (and (not (equal s ""))
  198. (string-match "\\\\+\\'" arg)
  199. (match-string 0 arg)))
  200. nil t)
  201. s)))))
  202. (defun org-macro-extract-arguments (s)
  203. "Extract macro arguments from string S.
  204. S is a string containing comma separated values properly escaped.
  205. Return a list of arguments, as strings. This is the opposite of
  206. `org-macro-escape-arguments'."
  207. ;; Do not use `org-split-string' since empty strings are
  208. ;; meaningful here.
  209. (split-string
  210. (replace-regexp-in-string
  211. "\\(\\\\*\\),"
  212. (lambda (str)
  213. (let ((len (length (match-string 1 str))))
  214. (concat (make-string (/ len 2) ?\\)
  215. (if (zerop (mod len 2)) "\000" ","))))
  216. s nil t)
  217. "\000"))
  218. (provide 'org-macro)
  219. ;;; org-macro.el ends here