org-macro.el 11 KB

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