test-org-element: Add tests for latex fragments parsing
[org-mode.git] / lisp / org-macro.el
blob6cafc6bdb108f5ecc0bca0bb3c58587443954478
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/>.
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)
48 (declare-function org-element-at-point "org-element" ())
49 (declare-function org-element-context "org-element" (&optional element))
50 (declare-function org-element-property "org-element" (property element))
51 (declare-function org-element-type "org-element" (element))
52 (declare-function org-remove-double-quotes "org" (s))
53 (declare-function org-mode "org" ())
54 (declare-function org-file-contents "org" (file &optional noerror))
55 (declare-function org-with-wide-buffer "org-macs" (&rest body))
57 ;;; Variables
59 (defvar org-macro-templates nil
60 "Alist containing all macro templates in current buffer.
61 Associations are in the shape of (NAME . TEMPLATE) where NAME
62 stands for macro's name and template for its replacement value,
63 both as strings. This is an internal variable. Do not set it
64 directly, use instead:
66 #+MACRO: name template")
67 (make-variable-buffer-local 'org-macro-templates)
70 ;;; Functions
72 (defun org-macro--collect-macros ()
73 "Collect macro definitions in current buffer and setup files.
74 Return an alist containing all macro templates found."
75 (let* (collect-macros ; For byte-compiler.
76 (collect-macros
77 (lambda (files templates)
78 ;; Return an alist of macro templates. FILES is a list of
79 ;; setup files names read so far, used to avoid circular
80 ;; dependencies. TEMPLATES is the alist collected so far.
81 (let ((case-fold-search t))
82 (org-with-wide-buffer
83 (goto-char (point-min))
84 (while (re-search-forward
85 "^[ \t]*#\\+\\(MACRO\\|SETUPFILE\\):" nil t)
86 (let ((element (org-element-at-point)))
87 (when (eq (org-element-type element) 'keyword)
88 (let ((val (org-element-property :value element)))
89 (if (equal (org-element-property :key element) "MACRO")
90 ;; Install macro in TEMPLATES.
91 (when (string-match
92 "^\\(.*?\\)\\(?:\\s-+\\(.*\\)\\)?\\s-*$" val)
93 (let* ((name (match-string 1 val))
94 (template (or (match-string 2 val) ""))
95 (old-cell (assoc name templates)))
96 (if old-cell (setcdr old-cell template)
97 (push (cons name template) templates))))
98 ;; Enter setup file.
99 (let ((file (expand-file-name
100 (org-remove-double-quotes val))))
101 (unless (member file files)
102 (with-temp-buffer
103 (org-mode)
104 (insert (org-file-contents file 'noerror))
105 (setq templates
106 (funcall collect-macros (cons file files)
107 templates)))))))))))
108 templates))))
109 (funcall collect-macros nil nil)))
111 (defun org-macro-initialize-templates ()
112 "Collect macro templates defined in current buffer.
113 Templates are stored in buffer-local variable
114 `org-macro-templates'. In addition to buffer-defined macros, the
115 function installs the following ones: \"property\",
116 \"time\". and, if the buffer is associated to a file,
117 \"input-file\" and \"modification-time\"."
118 (let* ((templates (org-macro--collect-macros))
119 (update-templates
120 (lambda (cell)
121 (let ((old-template (assoc (car cell) templates)))
122 (if old-template (setcdr old-template (cdr cell))
123 (push cell templates))))))
124 ;; Install hard-coded macros.
125 (mapc update-templates
126 (list (cons "property" "(eval (org-entry-get nil \"$1\" 'selective))")
127 (cons "time" "(eval (format-time-string \"$1\"))")))
128 (let ((visited-file (buffer-file-name (buffer-base-buffer))))
129 (when (and visited-file (file-exists-p visited-file))
130 (mapc update-templates
131 (list (cons "input-file" (file-name-nondirectory visited-file))
132 (cons "modification-time"
133 (format "(eval (format-time-string \"$1\" '%s))"
134 (prin1-to-string
135 (nth 5 (file-attributes visited-file)))))))))
136 (setq org-macro-templates templates)))
138 (defun org-macro-expand (macro templates)
139 "Return expanded MACRO, as a string.
140 MACRO is an object, obtained, for example, with
141 `org-element-context'. TEMPLATES is an alist of templates used
142 for expansion. See `org-macro-templates' for a buffer-local
143 default value. Return nil if no template was found."
144 (let ((template
145 ;; Macro names are case-insensitive.
146 (cdr (assoc-string (org-element-property :key macro) templates t))))
147 (when template
148 (let ((value (replace-regexp-in-string
149 "\\$[0-9]+"
150 (lambda (arg)
151 (or (nth (1- (string-to-number (substring arg 1)))
152 (org-element-property :args macro))
153 ;; No argument: remove place-holder.
154 ""))
155 template nil 'literal)))
156 ;; VALUE starts with "(eval": it is a s-exp, `eval' it.
157 (when (string-match "\\`(eval\\>" value)
158 (setq value (eval (read value))))
159 ;; Return string.
160 (format "%s" (or value ""))))))
162 (defun org-macro-replace-all (templates &optional finalize keywords)
163 "Replace all macros in current buffer by their expansion.
165 TEMPLATES is an alist of templates used for expansion. See
166 `org-macro-templates' for a buffer-local default value.
168 If optional arg FINALIZE is non-nil, raise an error if a macro is
169 found in the buffer with no definition in TEMPLATES."
170 (save-excursion
171 (goto-char (point-min))
172 (let ((properties-regexp
173 (format "\\`EXPORT_%s\\+?\\'" (regexp-opt keywords)))
174 record)
175 (while (re-search-forward "{{{[-A-Za-z0-9_]" nil t)
176 (let* ((datum (save-match-data (org-element-context)))
177 (type (org-element-type datum))
178 (macro
179 (cond
180 ((eq type 'macro) datum)
181 ;; In parsed keywords and associated node properties,
182 ;; force macro recognition.
183 ((or (and (eq type 'keyword)
184 (member (org-element-property :key datum) keywords))
185 (and (eq type 'node-property)
186 (org-string-match-p
187 properties-regexp
188 (org-element-property :key datum))))
189 (save-restriction
190 (narrow-to-region (match-beginning 0) (line-end-position))
191 (org-element-map (org-element-parse-buffer) 'macro
192 #'identity nil t))))))
193 (when macro
194 (let* ((value (org-macro-expand macro templates))
195 (begin (org-element-property :begin macro))
196 (signature (list begin
197 macro
198 (org-element-property :args macro))))
199 ;; Avoid circular dependencies by checking if the same
200 ;; macro with the same arguments is expanded at the same
201 ;; position twice.
202 (cond ((member signature record)
203 (error "Circular macro expansion: %s"
204 (org-element-property :key macro)))
205 (value
206 (push signature record)
207 (delete-region
208 begin
209 ;; Preserve white spaces after the macro.
210 (progn (goto-char (org-element-property :end macro))
211 (skip-chars-backward " \t")
212 (point)))
213 ;; Leave point before replacement in case of
214 ;; recursive expansions.
215 (save-excursion (insert value)))
216 (finalize
217 (error "Undefined Org macro: %s; aborting"
218 (org-element-property :key macro)))))))))))
220 (defun org-macro-escape-arguments (&rest args)
221 "Build macro's arguments string from ARGS.
222 ARGS are strings. Return value is a string with arguments
223 properly escaped and separated with commas. This is the opposite
224 of `org-macro-extract-arguments'."
225 (let ((s ""))
226 (dolist (arg (reverse args) (substring s 1))
227 (setq s
228 (concat
230 (replace-regexp-in-string
231 "\\(\\\\*\\),"
232 (lambda (m)
233 (concat (make-string (1+ (* 2 (length (match-string 1 m)))) ?\\)
234 ","))
235 ;; If a non-terminal argument ends on backslashes, make
236 ;; sure to also escape them as they will be followed by
237 ;; a comma.
238 (concat arg (and (not (equal s ""))
239 (string-match "\\\\+\\'" arg)
240 (match-string 0 arg)))
241 nil t)
242 s)))))
244 (defun org-macro-extract-arguments (s)
245 "Extract macro arguments from string S.
246 S is a string containing comma separated values properly escaped.
247 Return a list of arguments, as strings. This is the opposite of
248 `org-macro-escape-arguments'."
249 ;; Do not use `org-split-string' since empty strings are
250 ;; meaningful here.
251 (split-string
252 (replace-regexp-in-string
253 "\\(\\\\*\\),"
254 (lambda (str)
255 (let ((len (length (match-string 1 str))))
256 (concat (make-string (/ len 2) ?\\)
257 (if (zerop (mod len 2)) "\000" ","))))
258 s nil t)
259 "\000"))
262 (provide 'org-macro)
263 ;;; org-macro.el ends here