1 ;;; org-macro.el --- Macro Replacement Code for Org Mode
3 ;; Copyright (C) 2013-2015 Free Software Foundation, Inc.
5 ;; Author: Nicolas Goaziou <n.goaziou@gmail.com>
6 ;; Keywords: outlines, hypermedia, calendar, wp
8 ;; This file is part of GNU Emacs.
10 ;; GNU Emacs is free software: you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;; Macros are expanded with `org-macro-replace-all', which relies
26 ;; internally on `org-macro-expand'.
28 ;; Default templates for expansion are stored in the buffer-local
29 ;; variable `org-macro-templates'. This variable is updated by
30 ;; `org-macro-initialize-templates', which recursively calls
31 ;; `org-macro--collect-macros' in order to read setup files.
33 ;; Argument in macros are separated with commas. Proper escaping rules
34 ;; are implemented in `org-macro-escape-arguments' and arguments can
35 ;; be extracted from a string with `org-macro-extract-arguments'.
37 ;; Along with macros defined through #+MACRO: keyword, default
38 ;; templates include the following hard-coded macros:
39 ;; {{{time(format-string)}}}, {{{property(node-property)}}},
40 ;; {{{input-file}}} and {{{modification-time(format-string)}}}.
42 ;; Upon exporting, "ox.el" will also provide {{{author}}}, {{{date}}},
43 ;; {{{email}}} and {{{title}}} macros.
49 (declare-function org-element-at-point
"org-element" ())
50 (declare-function org-element-context
"org-element" (&optional element
))
51 (declare-function org-element-map
"org-element"
52 (data types fun
&optional info first-match no-recursion
54 (declare-function org-element-parse-buffer
"org-element"
55 (&optional granularity visible-only
))
56 (declare-function org-element-property
"org-element" (property element
))
57 (declare-function org-element-type
"org-element" (element))
58 (declare-function org-file-contents
"org" (file &optional noerror
))
59 (declare-function org-mode
"org" ())
60 (declare-function org-remove-double-quotes
"org" (s))
61 (declare-function org-with-wide-buffer
"org-macs" (&rest body
))
65 (defvar org-macro-templates nil
66 "Alist containing all macro templates in current buffer.
67 Associations are in the shape of (NAME . TEMPLATE) where NAME
68 stands for macro's name and template for its replacement value,
69 both as strings. This is an internal variable. Do not set it
70 directly, use instead:
72 #+MACRO: name template")
73 (make-variable-buffer-local 'org-macro-templates
)
78 (defun org-macro--collect-macros ()
79 "Collect macro definitions in current buffer and setup files.
80 Return an alist containing all macro templates found."
81 (let* (collect-macros ; For byte-compiler.
83 (lambda (files templates
)
84 ;; Return an alist of macro templates. FILES is a list of
85 ;; setup files names read so far, used to avoid circular
86 ;; dependencies. TEMPLATES is the alist collected so far.
87 (let ((case-fold-search t
))
89 (goto-char (point-min))
90 (while (re-search-forward
91 "^[ \t]*#\\+\\(MACRO\\|SETUPFILE\\):" nil t
)
92 (let ((element (org-element-at-point)))
93 (when (eq (org-element-type element
) 'keyword
)
94 (let ((val (org-element-property :value element
)))
95 (if (equal (org-element-property :key element
) "MACRO")
96 ;; Install macro in TEMPLATES.
98 "^\\(.*?\\)\\(?:\\s-+\\(.*\\)\\)?\\s-*$" val
)
99 (let* ((name (match-string 1 val
))
100 (template (or (match-string 2 val
) ""))
101 (old-cell (assoc name templates
)))
102 (if old-cell
(setcdr old-cell template
)
103 (push (cons name template
) templates
))))
105 (let ((file (expand-file-name
106 (org-remove-double-quotes val
))))
107 (unless (member file files
)
110 (insert (org-file-contents file
'noerror
))
112 (funcall collect-macros
(cons file files
)
115 (funcall collect-macros nil nil
)))
117 (defun org-macro-initialize-templates ()
118 "Collect macro templates defined in current buffer.
119 Templates are stored in buffer-local variable
120 `org-macro-templates'. In addition to buffer-defined macros, the
121 function installs the following ones: \"property\",
122 \"time\". and, if the buffer is associated to a file,
123 \"input-file\" and \"modification-time\"."
124 (let* ((templates (org-macro--collect-macros))
127 (let ((old-template (assoc (car cell
) templates
)))
128 (if old-template
(setcdr old-template
(cdr cell
))
129 (push cell templates
))))))
130 ;; Install hard-coded macros.
131 (mapc update-templates
132 (list (cons "property"
133 "(eval (save-excursion
135 (when (org-string-nw-p l)
137 (let ((org-link-search-must-match-exact-headline t))
138 (org-link-search l nil t))
140 (error \"Macro property failed: cannot find location %s\"
142 (org-entry-get nil \"$1\" 'selective)))")
143 (cons "time" "(eval (format-time-string \"$1\"))")))
144 (let ((visited-file (buffer-file-name (buffer-base-buffer))))
145 (when (and visited-file
(file-exists-p visited-file
))
146 (mapc update-templates
147 (list (cons "input-file" (file-name-nondirectory visited-file
))
148 (cons "modification-time"
149 (format "(eval (format-time-string \"$1\" '%s))"
151 (nth 5 (file-attributes visited-file
)))))))))
152 (setq org-macro-templates templates
)))
154 (defun org-macro-expand (macro templates
)
155 "Return expanded MACRO, as a string.
156 MACRO is an object, obtained, for example, with
157 `org-element-context'. TEMPLATES is an alist of templates used
158 for expansion. See `org-macro-templates' for a buffer-local
159 default value. Return nil if no template was found."
161 ;; Macro names are case-insensitive.
162 (cdr (assoc-string (org-element-property :key macro
) templates t
))))
164 (let ((value (replace-regexp-in-string
167 (or (nth (1- (string-to-number (substring arg
1)))
168 (org-element-property :args macro
))
169 ;; No argument: remove place-holder.
171 template nil
'literal
)))
172 ;; VALUE starts with "(eval": it is a s-exp, `eval' it.
173 (when (string-match "\\`(eval\\>" value
)
174 (setq value
(eval (read value
))))
176 (format "%s" (or value
""))))))
178 (defun org-macro-replace-all (templates &optional finalize keywords
)
179 "Replace all macros in current buffer by their expansion.
181 TEMPLATES is an alist of templates used for expansion. See
182 `org-macro-templates' for a buffer-local default value.
184 If optional arg FINALIZE is non-nil, raise an error if a macro is
185 found in the buffer with no definition in TEMPLATES.
187 Optional argument KEYWORDS, when non-nil is a list of keywords,
188 as strings, where macro expansion is allowed."
190 (goto-char (point-min))
191 (let ((properties-regexp
192 (format "\\`EXPORT_%s\\+?\\'" (regexp-opt keywords
)))
194 (while (re-search-forward "{{{[-A-Za-z0-9_]" nil t
)
195 (let* ((datum (save-match-data (org-element-context)))
196 (type (org-element-type datum
))
199 ((eq type
'macro
) datum
)
200 ;; In parsed keywords and associated node properties,
201 ;; force macro recognition.
202 ((or (and (eq type
'keyword
)
203 (member (org-element-property :key datum
) keywords
))
204 (and (eq type
'node-property
)
207 (org-element-property :key datum
))))
209 (narrow-to-region (match-beginning 0) (line-end-position))
210 (org-element-map (org-element-parse-buffer) 'macro
211 #'identity nil t
))))))
213 (let* ((value (org-macro-expand macro templates
))
214 (begin (org-element-property :begin macro
))
215 (signature (list begin
217 (org-element-property :args macro
))))
218 ;; Avoid circular dependencies by checking if the same
219 ;; macro with the same arguments is expanded at the same
221 (cond ((member signature record
)
222 (error "Circular macro expansion: %s"
223 (org-element-property :key macro
)))
225 (push signature record
)
228 ;; Preserve white spaces after the macro.
229 (progn (goto-char (org-element-property :end macro
))
230 (skip-chars-backward " \t")
232 ;; Leave point before replacement in case of
233 ;; recursive expansions.
234 (save-excursion (insert value
)))
236 (error "Undefined Org macro: %s; aborting"
237 (org-element-property :key macro
)))))))))))
239 (defun org-macro-escape-arguments (&rest args
)
240 "Build macro's arguments string from ARGS.
241 ARGS are strings. Return value is a string with arguments
242 properly escaped and separated with commas. This is the opposite
243 of `org-macro-extract-arguments'."
245 (dolist (arg (reverse args
) (substring s
1))
249 (replace-regexp-in-string
252 (concat (make-string (1+ (* 2 (length (match-string 1 m
)))) ?
\\)
254 ;; If a non-terminal argument ends on backslashes, make
255 ;; sure to also escape them as they will be followed by
257 (concat arg
(and (not (equal s
""))
258 (string-match "\\\\+\\'" arg
)
259 (match-string 0 arg
)))
263 (defun org-macro-extract-arguments (s)
264 "Extract macro arguments from string S.
265 S is a string containing comma separated values properly escaped.
266 Return a list of arguments, as strings. This is the opposite of
267 `org-macro-escape-arguments'."
268 ;; Do not use `org-split-string' since empty strings are
271 (replace-regexp-in-string
274 (let ((len (length (match-string 1 str
))))
275 (concat (make-string (/ len
2) ?
\\)
276 (if (zerop (mod len
2)) "\000" ","))))
282 ;;; org-macro.el ends here