org.texi: Merge "markup" related nodes
[org-mode/org-tableheadings.git] / lisp / org-macro.el
blob0e650f56b9e6246f6c4f879b72b6139f1fec4fad
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 org-remove-double-quotes "org" (s))
62 (declare-function vc-backend "vc-hooks" (f))
63 (declare-function vc-call "vc-hooks" (fun file &rest args) t)
64 (declare-function vc-exec-after "vc-dispatcher" (code))
66 ;;; Variables
68 (defvar-local org-macro-templates nil
69 "Alist containing all macro templates in current buffer.
70 Associations are in the shape of (NAME . TEMPLATE) where NAME
71 stands for macro's name and template for its replacement value,
72 both as strings. This is an internal variable. Do not set it
73 directly, use instead:
75 #+MACRO: name template")
77 ;;; Functions
79 (defun org-macro--collect-macros ()
80 "Collect macro definitions in current buffer and setup files.
81 Return an alist containing all macro templates found."
82 (letrec ((collect-macros
83 (lambda (files templates)
84 ;; Return an alist of macro templates. FILES is a list
85 ;; of setup files names read so far, used to avoid
86 ;; circular dependencies. TEMPLATES is the alist
87 ;; collected so far.
88 (let ((case-fold-search t))
89 (org-with-wide-buffer
90 (goto-char (point-min))
91 (while (re-search-forward
92 "^[ \t]*#\\+\\(MACRO\\|SETUPFILE\\):" nil t)
93 (let ((element (org-element-at-point)))
94 (when (eq (org-element-type element) 'keyword)
95 (let ((val (org-element-property :value element)))
96 (if (equal (org-element-property :key element) "MACRO")
97 ;; Install macro in TEMPLATES.
98 (when (string-match
99 "^\\(.*?\\)\\(?:\\s-+\\(.*\\)\\)?\\s-*$" val)
100 (let* ((name (match-string 1 val))
101 (template (or (match-string 2 val) ""))
102 (old-cell (assoc name templates)))
103 (if old-cell (setcdr old-cell template)
104 (push (cons name template) templates))))
105 ;; Enter setup file.
106 (let ((file (expand-file-name
107 (org-remove-double-quotes val))))
108 (unless (member file files)
109 (with-temp-buffer
110 (setq default-directory
111 (file-name-directory file))
112 (org-mode)
113 (insert (org-file-contents file 'noerror))
114 (setq templates
115 (funcall collect-macros (cons file files)
116 templates)))))))))))
117 templates))))
118 (funcall collect-macros nil nil)))
120 (defun org-macro-initialize-templates ()
121 "Collect macro templates defined in current buffer.
122 Templates are stored in buffer-local variable
123 `org-macro-templates'. In addition to buffer-defined macros, the
124 function installs the following ones: \"property\",
125 \"time\". and, if the buffer is associated to a file,
126 \"input-file\" and \"modification-time\"."
127 (let* ((templates (org-macro--collect-macros))
128 (update-templates
129 (lambda (cell)
130 (let ((old-template (assoc (car cell) templates)))
131 (if old-template (setcdr old-template (cdr cell))
132 (push cell templates))))))
133 ;; Install hard-coded macros.
134 (mapc update-templates
135 (list (cons "property"
136 "(eval (save-excursion
137 (let ((l \"$2\"))
138 (when (org-string-nw-p l)
139 (condition-case _
140 (let ((org-link-search-must-match-exact-headline t))
141 (org-link-search l nil t))
142 (error
143 (error \"Macro property failed: cannot find location %s\"
144 l)))))
145 (org-entry-get nil \"$1\" 'selective)))")
146 (cons "time" "(eval (format-time-string \"$1\"))")))
147 (let ((visited-file (buffer-file-name (buffer-base-buffer))))
148 (when (and visited-file (file-exists-p visited-file))
149 (mapc update-templates
150 (list (cons "input-file" (file-name-nondirectory visited-file))
151 (cons "modification-time"
152 (format "(eval (format-time-string \"$1\" (or (and (org-string-nw-p \"$2\") (org-macro--vc-modified-time %s)) '%s)))"
153 (prin1-to-string visited-file)
154 (prin1-to-string
155 (nth 5 (file-attributes visited-file)))))))))
156 (setq org-macro-templates templates)))
158 (defun org-macro-expand (macro templates)
159 "Return expanded MACRO, as a string.
160 MACRO is an object, obtained, for example, with
161 `org-element-context'. TEMPLATES is an alist of templates used
162 for expansion. See `org-macro-templates' for a buffer-local
163 default value. Return nil if no template was found."
164 (let ((template
165 ;; Macro names are case-insensitive.
166 (cdr (assoc-string (org-element-property :key macro) templates t))))
167 (when template
168 (let ((value (replace-regexp-in-string
169 "\\$[0-9]+"
170 (lambda (arg)
171 (or (nth (1- (string-to-number (substring arg 1)))
172 (org-element-property :args macro))
173 ;; No argument: remove place-holder.
174 ""))
175 template nil 'literal)))
176 ;; VALUE starts with "(eval": it is a s-exp, `eval' it.
177 (when (string-match "\\`(eval\\>" value)
178 (setq value (eval (read value))))
179 ;; Return string.
180 (format "%s" (or value ""))))))
182 (defun org-macro-replace-all (templates &optional finalize keywords)
183 "Replace all macros in current buffer by their expansion.
185 TEMPLATES is an alist of templates used for expansion. See
186 `org-macro-templates' for a buffer-local default value.
188 If optional arg FINALIZE is non-nil, raise an error if a macro is
189 found in the buffer with no definition in TEMPLATES.
191 Optional argument KEYWORDS, when non-nil is a list of keywords,
192 as strings, where macro expansion is allowed."
193 (org-with-wide-buffer
194 (goto-char (point-min))
195 (let ((properties-regexp
196 (format "\\`EXPORT_%s\\+?\\'" (regexp-opt keywords)))
197 record)
198 (while (re-search-forward "{{{[-A-Za-z0-9_]" nil t)
199 (let* ((datum (save-match-data (org-element-context)))
200 (type (org-element-type datum))
201 (macro
202 (cond
203 ((eq type 'macro) datum)
204 ;; In parsed keywords and associated node properties,
205 ;; force macro recognition.
206 ((or (and (eq type 'keyword)
207 (member (org-element-property :key datum) keywords))
208 (and (eq type 'node-property)
209 (org-string-match-p
210 properties-regexp
211 (org-element-property :key datum))))
212 (save-restriction
213 (narrow-to-region (match-beginning 0) (line-end-position))
214 (org-element-map (org-element-parse-buffer) 'macro
215 #'identity nil t))))))
216 (when macro
217 (let* ((value (org-macro-expand macro templates))
218 (begin (org-element-property :begin macro))
219 (signature (list begin
220 macro
221 (org-element-property :args macro))))
222 ;; Avoid circular dependencies by checking if the same
223 ;; macro with the same arguments is expanded at the same
224 ;; position twice.
225 (cond ((member signature record)
226 (error "Circular macro expansion: %s"
227 (org-element-property :key macro)))
228 (value
229 (push signature record)
230 (delete-region
231 begin
232 ;; Preserve white spaces after the macro.
233 (progn (goto-char (org-element-property :end macro))
234 (skip-chars-backward " \t")
235 (point)))
236 ;; Leave point before replacement in case of
237 ;; recursive expansions.
238 (save-excursion (insert value)))
239 (finalize
240 (error "Undefined Org macro: %s; aborting"
241 (org-element-property :key macro)))))))))))
243 (defun org-macro-escape-arguments (&rest args)
244 "Build macro's arguments string from ARGS.
245 ARGS are strings. Return value is a string with arguments
246 properly escaped and separated with commas. This is the opposite
247 of `org-macro-extract-arguments'."
248 (let ((s ""))
249 (dolist (arg (reverse args) (substring s 1))
250 (setq s
251 (concat
253 (replace-regexp-in-string
254 "\\(\\\\*\\),"
255 (lambda (m)
256 (concat (make-string (1+ (* 2 (length (match-string 1 m)))) ?\\)
257 ","))
258 ;; If a non-terminal argument ends on backslashes, make
259 ;; sure to also escape them as they will be followed by
260 ;; a comma.
261 (concat arg (and (not (equal s ""))
262 (string-match "\\\\+\\'" arg)
263 (match-string 0 arg)))
264 nil t)
265 s)))))
267 (defun org-macro-extract-arguments (s)
268 "Extract macro arguments from string S.
269 S is a string containing comma separated values properly escaped.
270 Return a list of arguments, as strings. This is the opposite of
271 `org-macro-escape-arguments'."
272 ;; Do not use `org-split-string' since empty strings are
273 ;; meaningful here.
274 (split-string
275 (replace-regexp-in-string
276 "\\(\\\\*\\),"
277 (lambda (str)
278 (let ((len (length (match-string 1 str))))
279 (concat (make-string (/ len 2) ?\\)
280 (if (zerop (mod len 2)) "\000" ","))))
281 s nil t)
282 "\000"))
284 (defun org-macro--vc-modified-time (file)
285 (save-window-excursion
286 (when (vc-backend file)
287 (let ((buf (get-buffer-create " *org-vc*"))
288 (case-fold-search t)
289 date)
290 (unwind-protect
291 (progn
292 (vc-call print-log file buf nil nil 1)
293 (with-current-buffer buf
294 (vc-exec-after
295 (lambda ()
296 (goto-char (point-min))
297 (when (re-search-forward "Date:?[ \t]*" nil t)
298 (let ((time (parse-time-string
299 (buffer-substring
300 (point) (line-end-position)))))
301 (when (cl-some #'identity time)
302 (setq date (apply #'encode-time time))))))))
303 (let ((proc (get-buffer-process buf)))
304 (while (and proc (accept-process-output proc .5 nil t)))))
305 (kill-buffer buf))
306 date))))
309 (provide 'org-macro)
310 ;;; org-macro.el ends here