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
)
109 (setq default-directory
110 (file-name-directory file
))
112 (insert (org-file-contents file
'noerror
))
114 (funcall collect-macros
(cons file files
)
117 (funcall collect-macros nil nil
)))
119 (defun org-macro-initialize-templates ()
120 "Collect macro templates defined in current buffer.
121 Templates are stored in buffer-local variable
122 `org-macro-templates'. In addition to buffer-defined macros, the
123 function installs the following ones: \"property\",
124 \"time\". and, if the buffer is associated to a file,
125 \"input-file\" and \"modification-time\"."
126 (let* ((templates (org-macro--collect-macros))
129 (let ((old-template (assoc (car cell
) templates
)))
130 (if old-template
(setcdr old-template
(cdr cell
))
131 (push cell templates
))))))
132 ;; Install hard-coded macros.
133 (mapc update-templates
134 (list (cons "property"
135 "(eval (save-excursion
137 (when (org-string-nw-p l)
139 (let ((org-link-search-must-match-exact-headline t))
140 (org-link-search l nil t))
142 (error \"Macro property failed: cannot find location %s\"
144 (org-entry-get nil \"$1\" 'selective)))")
145 (cons "time" "(eval (format-time-string \"$1\"))")))
146 (let ((visited-file (buffer-file-name (buffer-base-buffer))))
147 (when (and visited-file
(file-exists-p visited-file
))
148 (mapc update-templates
149 (list (cons "input-file" (file-name-nondirectory visited-file
))
150 (cons "modification-time"
151 (format "(eval (format-time-string \"$1\" '%s))"
153 (nth 5 (file-attributes visited-file
)))))))))
154 (setq org-macro-templates templates
)))
156 (defun org-macro-expand (macro templates
)
157 "Return expanded MACRO, as a string.
158 MACRO is an object, obtained, for example, with
159 `org-element-context'. TEMPLATES is an alist of templates used
160 for expansion. See `org-macro-templates' for a buffer-local
161 default value. Return nil if no template was found."
163 ;; Macro names are case-insensitive.
164 (cdr (assoc-string (org-element-property :key macro
) templates t
))))
166 (let ((value (replace-regexp-in-string
169 (or (nth (1- (string-to-number (substring arg
1)))
170 (org-element-property :args macro
))
171 ;; No argument: remove place-holder.
173 template nil
'literal
)))
174 ;; VALUE starts with "(eval": it is a s-exp, `eval' it.
175 (when (string-match "\\`(eval\\>" value
)
176 (setq value
(eval (read value
))))
178 (format "%s" (or value
""))))))
180 (defun org-macro-replace-all (templates &optional finalize keywords
)
181 "Replace all macros in current buffer by their expansion.
183 TEMPLATES is an alist of templates used for expansion. See
184 `org-macro-templates' for a buffer-local default value.
186 If optional arg FINALIZE is non-nil, raise an error if a macro is
187 found in the buffer with no definition in TEMPLATES.
189 Optional argument KEYWORDS, when non-nil is a list of keywords,
190 as strings, where macro expansion is allowed."
192 (goto-char (point-min))
193 (let ((properties-regexp
194 (format "\\`EXPORT_%s\\+?\\'" (regexp-opt keywords
)))
196 (while (re-search-forward "{{{[-A-Za-z0-9_]" nil t
)
197 (let* ((datum (save-match-data (org-element-context)))
198 (type (org-element-type datum
))
201 ((eq type
'macro
) datum
)
202 ;; In parsed keywords and associated node properties,
203 ;; force macro recognition.
204 ((or (and (eq type
'keyword
)
205 (member (org-element-property :key datum
) keywords
))
206 (and (eq type
'node-property
)
209 (org-element-property :key datum
))))
211 (narrow-to-region (match-beginning 0) (line-end-position))
212 (org-element-map (org-element-parse-buffer) 'macro
213 #'identity nil t
))))))
215 (let* ((value (org-macro-expand macro templates
))
216 (begin (org-element-property :begin macro
))
217 (signature (list begin
219 (org-element-property :args macro
))))
220 ;; Avoid circular dependencies by checking if the same
221 ;; macro with the same arguments is expanded at the same
223 (cond ((member signature record
)
224 (error "Circular macro expansion: %s"
225 (org-element-property :key macro
)))
227 (push signature record
)
230 ;; Preserve white spaces after the macro.
231 (progn (goto-char (org-element-property :end macro
))
232 (skip-chars-backward " \t")
234 ;; Leave point before replacement in case of
235 ;; recursive expansions.
236 (save-excursion (insert value
)))
238 (error "Undefined Org macro: %s; aborting"
239 (org-element-property :key macro
)))))))))))
241 (defun org-macro-escape-arguments (&rest args
)
242 "Build macro's arguments string from ARGS.
243 ARGS are strings. Return value is a string with arguments
244 properly escaped and separated with commas. This is the opposite
245 of `org-macro-extract-arguments'."
247 (dolist (arg (reverse args
) (substring s
1))
251 (replace-regexp-in-string
254 (concat (make-string (1+ (* 2 (length (match-string 1 m
)))) ?
\\)
256 ;; If a non-terminal argument ends on backslashes, make
257 ;; sure to also escape them as they will be followed by
259 (concat arg
(and (not (equal s
""))
260 (string-match "\\\\+\\'" arg
)
261 (match-string 0 arg
)))
265 (defun org-macro-extract-arguments (s)
266 "Extract macro arguments from string S.
267 S is a string containing comma separated values properly escaped.
268 Return a list of arguments, as strings. This is the opposite of
269 `org-macro-escape-arguments'."
270 ;; Do not use `org-split-string' since empty strings are
273 (replace-regexp-in-string
276 (let ((len (length (match-string 1 str
))))
277 (concat (make-string (/ len
2) ?
\\)
278 (if (zerop (mod len
2)) "\000" ","))))
284 ;;; org-macro.el ends here