org-macro.el 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. ;;; org-macro.el --- Macro Replacement Code for Org Mode
  2. ;; Copyright (C) 2013-2014 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 (lambda (cell) (funcall update-templates cell))
  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 (lambda (cell) (funcall update-templates cell))
  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)
  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. (save-excursion
  146. (goto-char (point-min))
  147. (let (record)
  148. (while (re-search-forward "{{{[-A-Za-z0-9_]" nil t)
  149. (let ((object (org-element-context)))
  150. (when (eq (org-element-type object) 'macro)
  151. (let* ((value (org-macro-expand object templates))
  152. (begin (org-element-property :begin object))
  153. (signature (list begin
  154. object
  155. (org-element-property :args object))))
  156. ;; Avoid circular dependencies by checking if the same
  157. ;; macro with the same arguments is expanded at the same
  158. ;; position twice.
  159. (if (member signature record)
  160. (error "Circular macro expansion: %s"
  161. (org-element-property :key object))
  162. (cond (value
  163. (push signature record)
  164. (delete-region
  165. begin
  166. ;; Preserve white spaces after the macro.
  167. (progn (goto-char (org-element-property :end object))
  168. (skip-chars-backward " \t")
  169. (point)))
  170. ;; Leave point before replacement in case of recursive
  171. ;; expansions.
  172. (save-excursion (insert value)))
  173. (finalize
  174. (error "Undefined Org macro: %s; aborting."
  175. (org-element-property :key object))))))))))))
  176. (defun org-macro-escape-arguments (&rest args)
  177. "Build macro's arguments string from ARGS.
  178. ARGS are strings. Return value is a string with arguments
  179. properly escaped and separated with commas. This is the opposite
  180. of `org-macro-extract-arguments'."
  181. (let ((s ""))
  182. (dolist (arg (reverse args) (substring s 1))
  183. (setq s
  184. (concat
  185. ","
  186. (replace-regexp-in-string
  187. "\\(\\\\*\\),"
  188. (lambda (m)
  189. (concat (make-string (1+ (* 2 (length (match-string 1 m)))) ?\\)
  190. ","))
  191. ;; If a non-terminal argument ends on backslashes, make
  192. ;; sure to also escape them as they will be followed by
  193. ;; a comma.
  194. (concat arg (and (not (equal s ""))
  195. (string-match "\\\\+\\'" arg)
  196. (match-string 0 arg)))
  197. nil t)
  198. s)))))
  199. (defun org-macro-extract-arguments (s)
  200. "Extract macro arguments from string S.
  201. S is a string containing comma separated values properly escaped.
  202. Return a list of arguments, as strings. This is the opposite of
  203. `org-macro-escape-arguments'."
  204. ;; Do not use `org-split-string' since empty strings are
  205. ;; meaningful here.
  206. (split-string
  207. (replace-regexp-in-string
  208. "\\(\\\\*\\),"
  209. (lambda (str)
  210. (let ((len (length (match-string 1 str))))
  211. (concat (make-string (/ len 2) ?\\)
  212. (if (zerop (mod len 2)) "\000" ","))))
  213. s nil t)
  214. "\000"))
  215. (provide 'org-macro)
  216. ;;; org-macro.el ends here