Merge branch 'maint'
[org-mode.git] / lisp / org-macro.el
blob5e9be98d75c8064ebbcb89bc9ba77969cd5e16f8
1 ;;; org-macro.el --- Macro Replacement Code for Org -*- lexical-binding: t; -*-
3 ;; Copyright (C) 2013-2016 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/>.
23 ;;; Commentary:
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.
45 ;;; Code:
46 (require 'org-macs)
47 (require 'org-compat)
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
53 with-affiliated))
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))
63 ;;; Variables
65 (defvar-local 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")
74 ;;; Functions
76 (defun org-macro--collect-macros ()
77 "Collect macro definitions in current buffer and setup files.
78 Return an alist containing all macro templates found."
79 (letrec ((collect-macros
80 (lambda (files templates)
81 ;; Return an alist of macro templates. FILES is a list
82 ;; of setup files names read so far, used to avoid
83 ;; circular dependencies. TEMPLATES is the alist
84 ;; collected so far.
85 (let ((case-fold-search t))
86 (org-with-wide-buffer
87 (goto-char (point-min))
88 (while (re-search-forward
89 "^[ \t]*#\\+\\(MACRO\\|SETUPFILE\\):" nil t)
90 (let ((element (org-element-at-point)))
91 (when (eq (org-element-type element) 'keyword)
92 (let ((val (org-element-property :value element)))
93 (if (equal (org-element-property :key element) "MACRO")
94 ;; Install macro in TEMPLATES.
95 (when (string-match
96 "^\\(.*?\\)\\(?:\\s-+\\(.*\\)\\)?\\s-*$" val)
97 (let* ((name (match-string 1 val))
98 (template (or (match-string 2 val) ""))
99 (old-cell (assoc name templates)))
100 (if old-cell (setcdr old-cell template)
101 (push (cons name template) templates))))
102 ;; Enter setup file.
103 (let ((file (expand-file-name
104 (org-remove-double-quotes val))))
105 (unless (member file files)
106 (with-temp-buffer
107 (setq default-directory
108 (file-name-directory file))
109 (org-mode)
110 (insert (org-file-contents file 'noerror))
111 (setq templates
112 (funcall collect-macros (cons file files)
113 templates)))))))))))
114 templates))))
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))
125 (update-templates
126 (lambda (cell)
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
134 (let ((l \"$2\"))
135 (when (org-string-nw-p l)
136 (condition-case _
137 (let ((org-link-search-must-match-exact-headline t))
138 (org-link-search l nil t))
139 (error
140 (error \"Macro property failed: cannot find location %s\"
141 l)))))
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))"
150 (prin1-to-string
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."
160 (let ((template
161 ;; Macro names are case-insensitive.
162 (cdr (assoc-string (org-element-property :key macro) templates t))))
163 (when template
164 (let ((value (replace-regexp-in-string
165 "\\$[0-9]+"
166 (lambda (arg)
167 (or (nth (1- (string-to-number (substring arg 1)))
168 (org-element-property :args macro))
169 ;; No argument: remove place-holder.
170 ""))
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))))
175 ;; Return string.
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."
189 (org-with-wide-buffer
190 (goto-char (point-min))
191 (let ((properties-regexp
192 (format "\\`EXPORT_%s\\+?\\'" (regexp-opt keywords)))
193 record)
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))
197 (macro
198 (cond
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)
205 (org-string-match-p
206 properties-regexp
207 (org-element-property :key datum))))
208 (save-restriction
209 (narrow-to-region (match-beginning 0) (line-end-position))
210 (org-element-map (org-element-parse-buffer) 'macro
211 #'identity nil t))))))
212 (when macro
213 (let* ((value (org-macro-expand macro templates))
214 (begin (org-element-property :begin macro))
215 (signature (list begin
216 macro
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
220 ;; position twice.
221 (cond ((member signature record)
222 (error "Circular macro expansion: %s"
223 (org-element-property :key macro)))
224 (value
225 (push signature record)
226 (delete-region
227 begin
228 ;; Preserve white spaces after the macro.
229 (progn (goto-char (org-element-property :end macro))
230 (skip-chars-backward " \t")
231 (point)))
232 ;; Leave point before replacement in case of
233 ;; recursive expansions.
234 (save-excursion (insert value)))
235 (finalize
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'."
244 (let ((s ""))
245 (dolist (arg (reverse args) (substring s 1))
246 (setq s
247 (concat
249 (replace-regexp-in-string
250 "\\(\\\\*\\),"
251 (lambda (m)
252 (concat (make-string (1+ (* 2 (length (match-string 1 m)))) ?\\)
253 ","))
254 ;; If a non-terminal argument ends on backslashes, make
255 ;; sure to also escape them as they will be followed by
256 ;; a comma.
257 (concat arg (and (not (equal s ""))
258 (string-match "\\\\+\\'" arg)
259 (match-string 0 arg)))
260 nil t)
261 s)))))
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
269 ;; meaningful here.
270 (split-string
271 (replace-regexp-in-string
272 "\\(\\\\*\\),"
273 (lambda (str)
274 (let ((len (length (match-string 1 str))))
275 (concat (make-string (/ len 2) ?\\)
276 (if (zerop (mod len 2)) "\000" ","))))
277 s nil t)
278 "\000"))
281 (provide 'org-macro)
282 ;;; org-macro.el ends here