org-macro.el 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. ;;; org-macro.el --- Macro Replacement Code for Org -*- lexical-binding: t; -*-
  2. ;; Copyright (C) 2013-2016 Free Software Foundation, Inc.
  3. ;; Author: Nicolas Goaziou <n.goaziou@gmail.com>
  4. ;; Keywords: outlines, hypermedia, calendar, wp
  5. ;; This file is part of GNU Emacs.
  6. ;; GNU Emacs is free software: you can redistribute it and/or modify
  7. ;; it under the terms of the GNU General Public License as published by
  8. ;; the Free Software Foundation, either version 3 of the License, or
  9. ;; (at your option) any later version.
  10. ;; GNU Emacs is distributed in the hope that it will be useful,
  11. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. ;; GNU General Public License for more details.
  14. ;; You should have received a copy of the GNU General Public License
  15. ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
  16. ;;; Commentary:
  17. ;; Macros are expanded with `org-macro-replace-all', which relies
  18. ;; internally on `org-macro-expand'.
  19. ;; Default templates for expansion are stored in the buffer-local
  20. ;; variable `org-macro-templates'. This variable is updated by
  21. ;; `org-macro-initialize-templates', which recursively calls
  22. ;; `org-macro--collect-macros' in order to read setup files.
  23. ;; Argument in macros are separated with commas. Proper escaping rules
  24. ;; are implemented in `org-macro-escape-arguments' and arguments can
  25. ;; be extracted from a string with `org-macro-extract-arguments'.
  26. ;; Along with macros defined through #+MACRO: keyword, default
  27. ;; templates include the following hard-coded macros:
  28. ;; {{{time(format-string)}}}, {{{property(node-property)}}},
  29. ;; {{{input-file}}} and {{{modification-time(format-string)}}}.
  30. ;; Upon exporting, "ox.el" will also provide {{{author}}}, {{{date}}},
  31. ;; {{{email}}} and {{{title}}} macros.
  32. ;;; Code:
  33. (require 'cl-lib)
  34. (require 'org-macs)
  35. (require 'org-compat)
  36. (declare-function org-element-at-point "org-element" ())
  37. (declare-function org-element-context "org-element" (&optional element))
  38. (declare-function org-element-map "org-element"
  39. (data types fun &optional info first-match no-recursion
  40. with-affiliated))
  41. (declare-function org-element-parse-buffer "org-element"
  42. (&optional granularity visible-only))
  43. (declare-function org-element-property "org-element" (property element))
  44. (declare-function org-element-type "org-element" (element))
  45. (declare-function org-file-contents "org" (file &optional noerror))
  46. (declare-function org-mode "org" ())
  47. (declare-function org-remove-double-quotes "org" (s))
  48. (declare-function vc-backend "vc-hooks" (f))
  49. (declare-function vc-call "vc-hooks" (fun file &rest args) t)
  50. (declare-function vc-exec-after "vc-dispatcher" (code))
  51. ;;; Variables
  52. (defvar-local org-macro-templates nil
  53. "Alist containing all macro templates in current buffer.
  54. Associations are in the shape of (NAME . TEMPLATE) where NAME
  55. stands for macro's name and template for its replacement value,
  56. both as strings. This is an internal variable. Do not set it
  57. directly, use instead:
  58. #+MACRO: name template")
  59. ;;; Functions
  60. (defun org-macro--collect-macros ()
  61. "Collect macro definitions in current buffer and setup files.
  62. Return an alist containing all macro templates found."
  63. (letrec ((collect-macros
  64. (lambda (files templates)
  65. ;; Return an alist of macro templates. FILES is a list
  66. ;; of setup files names read so far, used to avoid
  67. ;; circular dependencies. TEMPLATES is the alist
  68. ;; collected so far.
  69. (let ((case-fold-search t))
  70. (org-with-wide-buffer
  71. (goto-char (point-min))
  72. (while (re-search-forward
  73. "^[ \t]*#\\+\\(MACRO\\|SETUPFILE\\):" nil t)
  74. (let ((element (org-element-at-point)))
  75. (when (eq (org-element-type element) 'keyword)
  76. (let ((val (org-element-property :value element)))
  77. (if (equal (org-element-property :key element) "MACRO")
  78. ;; Install macro in TEMPLATES.
  79. (when (string-match
  80. "^\\(.*?\\)\\(?:\\s-+\\(.*\\)\\)?\\s-*$" val)
  81. (let* ((name (match-string 1 val))
  82. (template (or (match-string 2 val) ""))
  83. (old-cell (assoc name templates)))
  84. (if old-cell (setcdr old-cell template)
  85. (push (cons name template) templates))))
  86. ;; Enter setup file.
  87. (let ((file (expand-file-name
  88. (org-remove-double-quotes val))))
  89. (unless (member file files)
  90. (with-temp-buffer
  91. (setq default-directory
  92. (file-name-directory file))
  93. (org-mode)
  94. (insert (org-file-contents file 'noerror))
  95. (setq templates
  96. (funcall collect-macros (cons file files)
  97. templates)))))))))))
  98. templates))))
  99. (funcall collect-macros nil nil)))
  100. (defun org-macro-initialize-templates ()
  101. "Collect macro templates defined in current buffer.
  102. Templates are stored in buffer-local variable
  103. `org-macro-templates'. In addition to buffer-defined macros, the
  104. function installs the following ones: \"property\",
  105. \"time\". and, if the buffer is associated to a file,
  106. \"input-file\" and \"modification-time\"."
  107. (let* ((templates (org-macro--collect-macros))
  108. (update-templates
  109. (lambda (cell)
  110. (let ((old-template (assoc (car cell) templates)))
  111. (if old-template (setcdr old-template (cdr cell))
  112. (push cell templates))))))
  113. ;; Install hard-coded macros.
  114. (mapc update-templates
  115. (list (cons "property"
  116. "(eval (save-excursion
  117. (let ((l \"$2\"))
  118. (when (org-string-nw-p l)
  119. (condition-case _
  120. (let ((org-link-search-must-match-exact-headline t))
  121. (org-link-search l nil t))
  122. (error
  123. (error \"Macro property failed: cannot find location %s\"
  124. l)))))
  125. (org-entry-get nil \"$1\" 'selective)))")
  126. (cons "time" "(eval (format-time-string \"$1\"))")))
  127. (let ((visited-file (buffer-file-name (buffer-base-buffer))))
  128. (when (and visited-file (file-exists-p visited-file))
  129. (mapc update-templates
  130. (list (cons "input-file" (file-name-nondirectory visited-file))
  131. (cons "modification-time"
  132. (format "(eval (format-time-string \"$1\" (or (and (org-string-nw-p \"$2\") (org-macro--vc-modified-time %s)) '%s)))"
  133. (prin1-to-string visited-file)
  134. (prin1-to-string
  135. (nth 5 (file-attributes visited-file)))))))))
  136. (setq org-macro-templates templates)))
  137. (defun org-macro-expand (macro templates)
  138. "Return expanded MACRO, as a string.
  139. MACRO is an object, obtained, for example, with
  140. `org-element-context'. TEMPLATES is an alist of templates used
  141. for expansion. See `org-macro-templates' for a buffer-local
  142. default value. Return nil if no template was found."
  143. (let ((template
  144. ;; Macro names are case-insensitive.
  145. (cdr (assoc-string (org-element-property :key macro) templates t))))
  146. (when template
  147. (let ((value (replace-regexp-in-string
  148. "\\$[0-9]+"
  149. (lambda (arg)
  150. (or (nth (1- (string-to-number (substring arg 1)))
  151. (org-element-property :args macro))
  152. ;; No argument: remove place-holder.
  153. ""))
  154. template nil 'literal)))
  155. ;; VALUE starts with "(eval": it is a s-exp, `eval' it.
  156. (when (string-match "\\`(eval\\>" value)
  157. (setq value (eval (read value))))
  158. ;; Return string.
  159. (format "%s" (or value ""))))))
  160. (defun org-macro-replace-all (templates &optional finalize keywords)
  161. "Replace all macros in current buffer by their expansion.
  162. TEMPLATES is an alist of templates used for expansion. See
  163. `org-macro-templates' for a buffer-local default value.
  164. If optional arg FINALIZE is non-nil, raise an error if a macro is
  165. found in the buffer with no definition in TEMPLATES.
  166. Optional argument KEYWORDS, when non-nil is a list of keywords,
  167. as strings, where macro expansion is allowed."
  168. (org-with-wide-buffer
  169. (goto-char (point-min))
  170. (let ((properties-regexp
  171. (format "\\`EXPORT_%s\\+?\\'" (regexp-opt keywords)))
  172. record)
  173. (while (re-search-forward "{{{[-A-Za-z0-9_]" nil t)
  174. (let* ((datum (save-match-data (org-element-context)))
  175. (type (org-element-type datum))
  176. (macro
  177. (cond
  178. ((eq type 'macro) datum)
  179. ;; In parsed keywords and associated node properties,
  180. ;; force macro recognition.
  181. ((or (and (eq type 'keyword)
  182. (member (org-element-property :key datum) keywords))
  183. (and (eq type 'node-property)
  184. (org-string-match-p
  185. properties-regexp
  186. (org-element-property :key datum))))
  187. (save-restriction
  188. (narrow-to-region (match-beginning 0) (line-end-position))
  189. (org-element-map (org-element-parse-buffer) 'macro
  190. #'identity nil t))))))
  191. (when macro
  192. (let* ((value (org-macro-expand macro templates))
  193. (begin (org-element-property :begin macro))
  194. (signature (list begin
  195. macro
  196. (org-element-property :args macro))))
  197. ;; Avoid circular dependencies by checking if the same
  198. ;; macro with the same arguments is expanded at the same
  199. ;; position twice.
  200. (cond ((member signature record)
  201. (error "Circular macro expansion: %s"
  202. (org-element-property :key macro)))
  203. (value
  204. (push signature record)
  205. (delete-region
  206. begin
  207. ;; Preserve white spaces after the macro.
  208. (progn (goto-char (org-element-property :end macro))
  209. (skip-chars-backward " \t")
  210. (point)))
  211. ;; Leave point before replacement in case of
  212. ;; recursive expansions.
  213. (save-excursion (insert value)))
  214. (finalize
  215. (error "Undefined Org macro: %s; aborting"
  216. (org-element-property :key macro)))))))))))
  217. (defun org-macro-escape-arguments (&rest args)
  218. "Build macro's arguments string from ARGS.
  219. ARGS are strings. Return value is a string with arguments
  220. properly escaped and separated with commas. This is the opposite
  221. of `org-macro-extract-arguments'."
  222. (let ((s ""))
  223. (dolist (arg (reverse args) (substring s 1))
  224. (setq s
  225. (concat
  226. ","
  227. (replace-regexp-in-string
  228. "\\(\\\\*\\),"
  229. (lambda (m)
  230. (concat (make-string (1+ (* 2 (length (match-string 1 m)))) ?\\)
  231. ","))
  232. ;; If a non-terminal argument ends on backslashes, make
  233. ;; sure to also escape them as they will be followed by
  234. ;; a comma.
  235. (concat arg (and (not (equal s ""))
  236. (string-match "\\\\+\\'" arg)
  237. (match-string 0 arg)))
  238. nil t)
  239. s)))))
  240. (defun org-macro-extract-arguments (s)
  241. "Extract macro arguments from string S.
  242. S is a string containing comma separated values properly escaped.
  243. Return a list of arguments, as strings. This is the opposite of
  244. `org-macro-escape-arguments'."
  245. ;; Do not use `org-split-string' since empty strings are
  246. ;; meaningful here.
  247. (split-string
  248. (replace-regexp-in-string
  249. "\\(\\\\*\\),"
  250. (lambda (str)
  251. (let ((len (length (match-string 1 str))))
  252. (concat (make-string (/ len 2) ?\\)
  253. (if (zerop (mod len 2)) "\000" ","))))
  254. s nil t)
  255. "\000"))
  256. (defun org-macro--vc-modified-time (file)
  257. (save-window-excursion
  258. (when (vc-backend file)
  259. (let ((buf (get-buffer-create " *org-vc*"))
  260. (case-fold-search t)
  261. date)
  262. (unwind-protect
  263. (progn
  264. (vc-call print-log file buf nil nil 1)
  265. (with-current-buffer buf
  266. (vc-exec-after
  267. (lambda ()
  268. (goto-char (point-min))
  269. (when (re-search-forward "Date:?[ \t]*" nil t)
  270. (let ((time (parse-time-string
  271. (buffer-substring
  272. (point) (line-end-position)))))
  273. (when (cl-some #'identity time)
  274. (setq date (apply #'encode-time time))))))))
  275. (let ((proc (get-buffer-process buf)))
  276. (while (and proc (accept-process-output proc .5 nil t)))))
  277. (kill-buffer buf))
  278. date))))
  279. (provide 'org-macro)
  280. ;;; org-macro.el ends here