Merge branch 'maint'
[org-mode/org-tableheadings.git] / lisp / org-macro.el
blob856089186f1803de0eab72f227b2913476f9b29e
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 'cl-lib)
47 (require 'org-macs)
48 (require 'org-compat)
50 (declare-function org-element-at-point "org-element" ())
51 (declare-function org-element-context "org-element" (&optional element))
52 (declare-function org-element-map "org-element"
53 (data types fun &optional info first-match no-recursion
54 with-affiliated))
55 (declare-function org-element-parse-buffer "org-element"
56 (&optional granularity visible-only))
57 (declare-function org-element-property "org-element" (property element))
58 (declare-function org-element-type "org-element" (element))
59 (declare-function org-file-contents "org" (file &optional noerror))
60 (declare-function org-mode "org" ())
61 (declare-function vc-backend "vc-hooks" (f))
62 (declare-function vc-call "vc-hooks" (fun file &rest args) t)
63 (declare-function vc-exec-after "vc-dispatcher" (code))
65 ;;; Variables
67 (defvar-local org-macro-templates nil
68 "Alist containing all macro templates in current buffer.
69 Associations are in the shape of (NAME . TEMPLATE) where NAME
70 stands for macro's name and template for its replacement value,
71 both as strings. This is an internal variable. Do not set it
72 directly, use instead:
74 #+MACRO: name template")
76 ;;; Functions
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 (letrec ((collect-macros
82 (lambda (files templates)
83 ;; Return an alist of macro templates. FILES is a list
84 ;; of setup files names read so far, used to avoid
85 ;; circular dependencies. TEMPLATES is the alist
86 ;; collected so far.
87 (let ((case-fold-search t))
88 (org-with-wide-buffer
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.
97 (when (string-match
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))))
104 ;; Enter setup file.
105 (let ((file (expand-file-name
106 (org-unbracket-string "\"" "\"" val))))
107 (unless (member file files)
108 (with-temp-buffer
109 (setq default-directory
110 (file-name-directory file))
111 (org-mode)
112 (insert (org-file-contents file 'noerror))
113 (setq templates
114 (funcall collect-macros (cons file files)
115 templates)))))))))))
116 templates))))
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))
127 (update-templates
128 (lambda (cell)
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
136 (let ((l \"$2\"))
137 (when (org-string-nw-p l)
138 (condition-case _
139 (let ((org-link-search-must-match-exact-headline t))
140 (org-link-search l nil t))
141 (error
142 (error \"Macro property failed: cannot find location %s\"
143 l)))))
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\" (or (and (org-string-nw-p \"$2\") (org-macro--vc-modified-time %s)) '%s)))"
152 (prin1-to-string visited-file)
153 (prin1-to-string
154 (nth 5 (file-attributes visited-file)))))))))
155 (setq org-macro-templates templates)))
157 (defun org-macro-expand (macro templates)
158 "Return expanded MACRO, as a string.
159 MACRO is an object, obtained, for example, with
160 `org-element-context'. TEMPLATES is an alist of templates used
161 for expansion. See `org-macro-templates' for a buffer-local
162 default value. Return nil if no template was found."
163 (let ((template
164 ;; Macro names are case-insensitive.
165 (cdr (assoc-string (org-element-property :key macro) templates t))))
166 (when template
167 (let ((value (replace-regexp-in-string
168 "\\$[0-9]+"
169 (lambda (arg)
170 (or (nth (1- (string-to-number (substring arg 1)))
171 (org-element-property :args macro))
172 ;; No argument: remove place-holder.
173 ""))
174 template nil 'literal)))
175 ;; VALUE starts with "(eval": it is a s-exp, `eval' it.
176 (when (string-match "\\`(eval\\>" value)
177 (setq value (eval (read value))))
178 ;; Return string.
179 (format "%s" (or value ""))))))
181 (defun org-macro-replace-all (templates &optional finalize keywords)
182 "Replace all macros in current buffer by their expansion.
184 TEMPLATES is an alist of templates used for expansion. See
185 `org-macro-templates' for a buffer-local default value.
187 If optional arg FINALIZE is non-nil, raise an error if a macro is
188 found in the buffer with no definition in TEMPLATES.
190 Optional argument KEYWORDS, when non-nil is a list of keywords,
191 as strings, where macro expansion is allowed."
192 (org-with-wide-buffer
193 (goto-char (point-min))
194 (let ((properties-regexp
195 (format "\\`EXPORT_%s\\+?\\'" (regexp-opt keywords)))
196 record)
197 (while (re-search-forward "{{{[-A-Za-z0-9_]" nil t)
198 (let* ((datum (save-match-data (org-element-context)))
199 (type (org-element-type datum))
200 (macro
201 (cond
202 ((eq type 'macro) datum)
203 ;; In parsed keywords and associated node properties,
204 ;; force macro recognition.
205 ((or (and (eq type 'keyword)
206 (member (org-element-property :key datum) keywords))
207 (and (eq type 'node-property)
208 (string-match-p
209 properties-regexp
210 (org-element-property :key datum))))
211 (save-restriction
212 (narrow-to-region (match-beginning 0) (line-end-position))
213 (org-element-map (org-element-parse-buffer) 'macro
214 #'identity nil t))))))
215 (when macro
216 (let* ((value (org-macro-expand macro templates))
217 (begin (org-element-property :begin macro))
218 (signature (list begin
219 macro
220 (org-element-property :args macro))))
221 ;; Avoid circular dependencies by checking if the same
222 ;; macro with the same arguments is expanded at the same
223 ;; position twice.
224 (cond ((member signature record)
225 (error "Circular macro expansion: %s"
226 (org-element-property :key macro)))
227 (value
228 (push signature record)
229 (delete-region
230 begin
231 ;; Preserve white spaces after the macro.
232 (progn (goto-char (org-element-property :end macro))
233 (skip-chars-backward " \t")
234 (point)))
235 ;; Leave point before replacement in case of
236 ;; recursive expansions.
237 (save-excursion (insert value)))
238 (finalize
239 (error "Undefined Org macro: %s; aborting"
240 (org-element-property :key macro)))))))))))
242 (defun org-macro-escape-arguments (&rest args)
243 "Build macro's arguments string from ARGS.
244 ARGS are strings. Return value is a string with arguments
245 properly escaped and separated with commas. This is the opposite
246 of `org-macro-extract-arguments'."
247 (let ((s ""))
248 (dolist (arg (reverse args) (substring s 1))
249 (setq s
250 (concat
252 (replace-regexp-in-string
253 "\\(\\\\*\\),"
254 (lambda (m)
255 (concat (make-string (1+ (* 2 (length (match-string 1 m)))) ?\\)
256 ","))
257 ;; If a non-terminal argument ends on backslashes, make
258 ;; sure to also escape them as they will be followed by
259 ;; a comma.
260 (concat arg (and (not (equal s ""))
261 (string-match "\\\\+\\'" arg)
262 (match-string 0 arg)))
263 nil t)
264 s)))))
266 (defun org-macro-extract-arguments (s)
267 "Extract macro arguments from string S.
268 S is a string containing comma separated values properly escaped.
269 Return a list of arguments, as strings. This is the opposite of
270 `org-macro-escape-arguments'."
271 ;; Do not use `org-split-string' since empty strings are
272 ;; meaningful here.
273 (split-string
274 (replace-regexp-in-string
275 "\\(\\\\*\\),"
276 (lambda (str)
277 (let ((len (length (match-string 1 str))))
278 (concat (make-string (/ len 2) ?\\)
279 (if (zerop (mod len 2)) "\000" ","))))
280 s nil t)
281 "\000"))
283 (defun org-macro--vc-modified-time (file)
284 (save-window-excursion
285 (when (vc-backend file)
286 (let ((buf (get-buffer-create " *org-vc*"))
287 (case-fold-search t)
288 date)
289 (unwind-protect
290 (progn
291 (vc-call print-log file buf nil nil 1)
292 (with-current-buffer buf
293 (vc-exec-after
294 (lambda ()
295 (goto-char (point-min))
296 (when (re-search-forward "Date:?[ \t]*" nil t)
297 (let ((time (parse-time-string
298 (buffer-substring
299 (point) (line-end-position)))))
300 (when (cl-some #'identity time)
301 (setq date (apply #'encode-time time))))))))
302 (let ((proc (get-buffer-process buf)))
303 (while (and proc (accept-process-output proc .5 nil t)))))
304 (kill-buffer buf))
305 date))))
308 (provide 'org-macro)
309 ;;; org-macro.el ends here