org-exp-blocks.el 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  1. ;;; org-exp-blocks.el --- pre-process blocks when exporting org files
  2. ;; Copyright (C) 2009
  3. ;; Free Software Foundation, Inc.
  4. ;; Author: Eric Schulte
  5. ;; This file is part of GNU Emacs.
  6. ;;
  7. ;; GNU Emacs is free software: you can redistribute it and/or modify
  8. ;; it under the terms of the GNU General Public License as published by
  9. ;; the Free Software Foundation, either version 3 of the License, or
  10. ;; (at your option) any later version.
  11. ;; GNU Emacs is distributed in the hope that it will be useful,
  12. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. ;; GNU General Public License for more details.
  15. ;; You should have received a copy of the GNU General Public License
  16. ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
  17. ;;; Commentary:
  18. ;;
  19. ;; This is a utility for pre-processing blocks in org files before
  20. ;; export using the `org-export-preprocess-hook'. It can be used for
  21. ;; exporting new types of blocks from org-mode files and also for
  22. ;; changing the default export behavior of existing org-mode blocks.
  23. ;; The `org-export-blocks' and `org-export-interblocks' variables can
  24. ;; be used to control how blocks and the spaces between blocks
  25. ;; respectively are processed upon export.
  26. ;;
  27. ;; The type of a block is defined as the string following =#+begin_=,
  28. ;; so for example the following block would be of type ditaa. Note
  29. ;; that both upper or lower case are allowed in =#+BEGIN_= and
  30. ;; =#+END_=.
  31. ;;
  32. ;; #+begin_ditaa blue.png -r -S
  33. ;; +---------+
  34. ;; | cBLU |
  35. ;; | |
  36. ;; | +----+
  37. ;; | |cPNK|
  38. ;; | | |
  39. ;; +----+----+
  40. ;; #+end_ditaa
  41. ;;
  42. ;;; Currently Implemented Block Types
  43. ;;
  44. ;; ditaa :: Convert ascii pictures to actual images using ditaa
  45. ;; http://ditaa.sourceforge.net/. To use this set
  46. ;; `org-ditaa-jar-path' to the path to ditaa.jar on your
  47. ;; system (should be set automatically in most cases) .
  48. ;;
  49. ;; dot :: Convert graphs defined using the dot graphing language to
  50. ;; images using the dot utility. For information on dot see
  51. ;; http://www.graphviz.org/
  52. ;;
  53. ;; comment :: Wrap comments with titles and author information, in
  54. ;; their own divs with author-specific ids allowing for css
  55. ;; coloring of comments based on the author.
  56. ;;
  57. ;; R :: Implements Sweave type exporting, evaluates blocks of R code,
  58. ;; and also replaces \R{} chunks in the file with their result
  59. ;; when passed to R. This require the `R' command which is
  60. ;; provided by ESS (Emacs Speaks Statistics).
  61. ;;
  62. ;;; Adding new blocks
  63. ;;
  64. ;; When adding a new block type first define a formatting function
  65. ;; along the same lines as `org-export-blocks-format-dot' and then use
  66. ;; `org-export-blocks-add-block' to add your block type to
  67. ;; `org-export-blocks'.
  68. (require 'org)
  69. (defvar comint-last-input-end)
  70. (defvar comint-prompt-regexp)
  71. (defvar comint-last-input-end)
  72. (defvar htmlp)
  73. (defvar latexp)
  74. (defvar docbookp)
  75. (defvar asciip)
  76. (declare-function comint-send-input "comint" (&optional no-newline artificial))
  77. (declare-function R "ess" nil)
  78. (defun org-export-blocks-set (var value)
  79. "Set the value of `org-export-blocks' and install fontification."
  80. (set var value)
  81. (mapc (lambda (spec)
  82. (if (nth 2 spec)
  83. (setq org-protecting-blocks
  84. (delete (symbol-name (car spec))
  85. org-protecting-blocks))
  86. (add-to-list 'org-protecting-blocks
  87. (symbol-name (car spec)))))
  88. value))
  89. (defcustom org-export-blocks
  90. '((comment org-export-blocks-format-comment t)
  91. (ditaa org-export-blocks-format-ditaa nil)
  92. (dot org-export-blocks-format-dot nil)
  93. (r org-export-blocks-format-R nil)
  94. (R org-export-blocks-format-R nil))
  95. "Use this a-list to associate block types with block exporting
  96. functions. The type of a block is determined by the text
  97. immediately following the '#+BEGIN_' portion of the block header.
  98. Each block export function should accept three argumets..."
  99. :group 'org-export-general
  100. :type '(repeat
  101. (list
  102. (symbol :tag "Block name")
  103. (function :tag "Block formatter")
  104. (boolean :tag "Fontify content as Org syntax")))
  105. :set 'org-export-blocks-set)
  106. (defun org-export-blocks-add-block (block-spec)
  107. "Add a new block type to `org-export-blocks'. BLOCK-SPEC
  108. should be a three element list the first element of which should
  109. indicate the name of the block, the second element should be the
  110. formatting function called by `org-export-blocks-preprocess' and
  111. the third element a flag indicating whether these types of blocks
  112. should be fontified in org-mode buffers (see
  113. `org-protecting-blocks'). For example the BLOCK-SPEC for ditaa
  114. blocks is as follows...
  115. (ditaa org-export-blocks-format-ditaa nil)"
  116. (unless (member block-spec org-export-blocks)
  117. (setq org-export-blocks (cons block-spec org-export-blocks))
  118. (org-export-blocks-set 'org-export-blocks org-export-blocks)))
  119. (defcustom org-export-interblocks
  120. '((r org-export-interblocks-format-R)
  121. (R org-export-interblocks-format-R))
  122. "Use this a-list to associate block types with block exporting
  123. functions. The type of a block is determined by the text
  124. immediately following the '#+BEGIN_' portion of the block header.
  125. Each block export function should accept three argumets..."
  126. :group 'org-export-general
  127. :type 'alist)
  128. (defcustom org-export-blocks-witheld
  129. '(hidden)
  130. "List of block types (see `org-export-blocks') which should not
  131. be exported."
  132. :group 'org-export-general
  133. :type 'list)
  134. (defvar org-export-blocks-postblock-hooks nil "")
  135. (defun org-export-blocks-html-quote (body &optional open close)
  136. "Protext BODY from org html export. The optional OPEN and
  137. CLOSE tags will be inserted around BODY."
  138. (concat
  139. "\n#+BEGIN_HTML\n"
  140. (or open "")
  141. body (if (string-match "\n$" body) "" "\n")
  142. (or close "")
  143. "#+END_HTML\n"))
  144. (defun org-export-blocks-latex-quote (body &optional open close)
  145. "Protext BODY from org latex export. The optional OPEN and
  146. CLOSE tags will be inserted around BODY."
  147. (concat
  148. "\n#+BEGIN_LaTeX\n"
  149. (or open "")
  150. body (if (string-match "\n$" body) "" "\n")
  151. (or close "")
  152. "#+END_LaTeX\n"))
  153. (defun org-export-blocks-preprocess ()
  154. "Export all blocks acording to the `org-export-blocks' block
  155. exportation alist. Does not export block types specified in
  156. specified in BLOCKS which default to the value of
  157. `org-export-blocks-witheld'."
  158. (interactive)
  159. (save-window-excursion
  160. (let ((count 0)
  161. (blocks org-export-blocks-witheld)
  162. (case-fold-search t)
  163. (types '())
  164. indentation type func start end)
  165. (flet ((interblock (start end type)
  166. (save-match-data
  167. (when (setf func (cadr (assoc type org-export-interblocks)))
  168. (funcall func start end)))))
  169. (goto-char (point-min))
  170. (setf start (point))
  171. (while (re-search-forward
  172. "^\\([ \t]*\\)#\\+begin_\\(\\S-+\\)[ \t]*\\(.*\\)?[\r\n]\\([^\000]*?\\)[\r\n][ \t]*#\\+end_\\S-+.*" nil t)
  173. (save-match-data (setq indentation (length (match-string 1))))
  174. (save-match-data (setf type (intern (match-string 2))))
  175. (unless (memq type types) (setf types (cons type types)))
  176. (setf end (save-match-data (match-beginning 0)))
  177. (interblock start end type)
  178. (if (setf func (cadr (assoc type org-export-blocks)))
  179. (progn
  180. (replace-match (save-match-data
  181. (if (memq type blocks)
  182. ""
  183. (apply func (save-match-data (org-remove-indentation (match-string 4)))
  184. (split-string (match-string 3) " ")))) t t)
  185. ;; indent the replaced match
  186. (indent-region (match-beginning 0) (match-end 0) indentation)
  187. ))
  188. (setf start (save-match-data (match-end 0))))
  189. (mapcar (lambda (type)
  190. (interblock start (point-max) type))
  191. types)))))
  192. (add-hook 'org-export-preprocess-hook 'org-export-blocks-preprocess)
  193. ;;================================================================================
  194. ;; type specific functions
  195. ;;--------------------------------------------------------------------------------
  196. ;; ditaa: create images from ASCII art using the ditaa utility
  197. (defvar org-ditaa-jar-path (expand-file-name
  198. "ditaa.jar"
  199. (file-name-as-directory
  200. (expand-file-name
  201. "scripts"
  202. (file-name-as-directory
  203. (expand-file-name
  204. ".."
  205. (file-name-directory (or load-file-name buffer-file-name)))))))
  206. "Path to the ditaa jar executable")
  207. (defun org-export-blocks-format-ditaa (body &rest headers)
  208. "Pass block BODY to the ditaa utility creating an image.
  209. Specify the path at which the image should be saved as the first
  210. element of headers, any additional elements of headers will be
  211. passed to the ditaa utility as command line arguments."
  212. (message "ditaa-formatting...")
  213. (let ((out-file (if headers (car headers)))
  214. (args (if (cdr headers) (mapconcat 'identity (cdr headers) " ")))
  215. (data-file (make-temp-file "org-ditaa")))
  216. (unless (file-exists-p org-ditaa-jar-path)
  217. (error (format "Could not find ditaa.jar at %s" org-ditaa-jar-path)))
  218. (setq body (if (string-match "^\\([^:\\|:[^ ]\\)" body)
  219. body
  220. (mapconcat (lambda (x) (substring x (if (> (length x) 1) 2 1)))
  221. (org-split-string body "\n")
  222. "\n")))
  223. (cond
  224. ((or htmlp latexp docbookp)
  225. (with-temp-file data-file (insert body))
  226. (message (concat "java -jar " org-ditaa-jar-path " " args " " data-file " " out-file))
  227. (shell-command (concat "java -jar " org-ditaa-jar-path " " args " " data-file " " out-file))
  228. (format "\n[[file:%s]]\n" out-file))
  229. (t (concat
  230. "\n#+BEGIN_EXAMPLE\n"
  231. body (if (string-match "\n$" body) "" "\n")
  232. "#+END_EXAMPLE\n")))))
  233. ;;--------------------------------------------------------------------------------
  234. ;; dot: create graphs using the dot graphing language
  235. ;; (require the dot executable to be in your path)
  236. (defun org-export-blocks-format-dot (body &rest headers)
  237. "Pass block BODY to the dot graphing utility creating an image.
  238. Specify the path at which the image should be saved as the first
  239. element of headers, any additional elements of headers will be
  240. passed to the dot utility as command line arguments. Don't
  241. forget to specify the output type for the dot command, so if you
  242. are exporting to a file with a name like 'image.png' you should
  243. include a '-Tpng' argument, and your block should look like the
  244. following.
  245. #+begin_dot models.png -Tpng
  246. digraph data_relationships {
  247. \"data_requirement\" [shape=Mrecord, label=\"{DataRequirement|description\lformat\l}\"]
  248. \"data_product\" [shape=Mrecord, label=\"{DataProduct|name\lversion\lpoc\lformat\l}\"]
  249. \"data_requirement\" -> \"data_product\"
  250. }
  251. #+end_dot"
  252. (message "dot-formatting...")
  253. (let ((out-file (if headers (car headers)))
  254. (args (if (cdr headers) (mapconcat 'identity (cdr headers) " ")))
  255. (data-file (make-temp-file "org-ditaa")))
  256. (cond
  257. ((or htmlp latexp docbookp)
  258. (with-temp-file data-file (insert body))
  259. (message (concat "dot " data-file " " args " -o " out-file))
  260. (shell-command (concat "dot " data-file " " args " -o " out-file))
  261. (format "\n[[file:%s]]\n" out-file))
  262. (t (concat
  263. "\n#+BEGIN_EXAMPLE\n"
  264. body (if (string-match "\n$" body) "" "\n")
  265. "#+END_EXAMPLE\n")))))
  266. ;;--------------------------------------------------------------------------------
  267. ;; comment: export comments in author-specific css-stylable divs
  268. (defun org-export-blocks-format-comment (body &rest headers)
  269. "Format comment BODY by OWNER and return it formatted for export.
  270. Currently, this only does something for HTML export, for all
  271. other backends, it converts the comment into an EXAMPLE segment."
  272. (let ((owner (if headers (car headers)))
  273. (title (if (cdr headers) (mapconcat 'identity (cdr headers) " "))))
  274. (cond
  275. (htmlp ;; We are exporting to HTML
  276. (concat "#+BEGIN_HTML\n"
  277. "<div class=\"org-comment\""
  278. (if owner (format " id=\"org-comment-%s\" " owner))
  279. ">\n"
  280. (if owner (concat "<b>" owner "</b> ") "")
  281. (if (and title (> (length title) 0)) (concat " -- " title "</br>\n") "</br>\n")
  282. "<p>\n"
  283. "#+END_HTML\n"
  284. body
  285. "#+BEGIN_HTML\n"
  286. "</p>\n"
  287. "</div>\n"
  288. "#+END_HTML\n"))
  289. (t ;; This is not HTML, so just make it an example.
  290. (concat "#+BEGIN_EXAMPLE\n"
  291. (if title (concat "Title:" title "\n") "")
  292. (if owner (concat "By:" owner "\n") "")
  293. body
  294. (if (string-match "\n\\'" body) "" "\n")
  295. "#+END_EXAMPLE\n")))))
  296. ;;--------------------------------------------------------------------------------
  297. ;; R: Sweave-type functionality
  298. (defvar interblock-R-buffer nil
  299. "Holds the buffer for the current R process")
  300. (defvar count) ; dynamicaly scoped from `org-export-blocks-preprocess'?
  301. (defun org-export-blocks-format-R (body &rest headers)
  302. "Process R blocks and replace \R{} forms outside the blocks
  303. with their values as determined by R."
  304. (interactive)
  305. (message "R processing...")
  306. (let ((image-path (or (and (car headers)
  307. (string-match "\\(.?\\)\.\\(EPS\\|eps\\)" (car headers))
  308. (match-string 1 (car headers)))
  309. (and (> (length (car headers)) 0)
  310. (car headers))
  311. ;; create the default filename
  312. (format "Rplot-%03d" count)))
  313. (plot (string-match "plot" body))
  314. R-proc)
  315. (setf count (+ count 1))
  316. (interblock-initiate-R-buffer)
  317. (setf R-proc (get-buffer-process interblock-R-buffer))
  318. ;; send strings to the ESS process using `comint-send-string'
  319. (setf body (mapconcat (lambda (line)
  320. (interblock-R-input-command line) (concat "> " line))
  321. (butlast (split-string body "[\r\n]"))
  322. "\n"))
  323. ;; if there is a plot command, then create the images
  324. (when plot
  325. (interblock-R-input-command (format "dev.copy2eps(file=\"%s.eps\")" image-path)))
  326. (concat (cond
  327. (htmlp (org-export-blocks-html-quote body
  328. (format "<div id=\"R-%d\">\n<pre>\n" count)
  329. "</pre>\n</div>\n"))
  330. (latexp (org-export-blocks-latex-quote body
  331. "\\begin{Schunk}\n\\begin{Sinput}\n"
  332. "\\end{Sinput}\n\\end{Schunk}\n"))
  333. (t (insert ;; default export
  334. "#+begin_R " (mapconcat 'identity headers " ") "\n"
  335. body (if (string-match "\n$" body) "" "\n")
  336. "#+end_R\n")))
  337. (if plot
  338. (format "[[file:%s.eps]]\n" image-path)
  339. ""))))
  340. (defun org-export-interblocks-format-R (start end)
  341. "This is run over parts of the org-file which are between R
  342. blocks. It's main use is to expand the \R{stuff} chunks for
  343. export."
  344. (save-excursion
  345. (goto-char start)
  346. (interblock-initiate-R-buffer)
  347. (let (code replacement)
  348. (while (and (< (point) end) (re-search-forward "\\\\R{\\(.*\\)}" end t))
  349. (save-match-data (setf code (match-string 1)))
  350. (setf replacement (interblock-R-command-to-string code))
  351. (setf replacement (cond
  352. (htmlp replacement)
  353. (latexp replacement)
  354. (t replacement)))
  355. (setf end (+ end (- (length replacement) (length code))))
  356. (replace-match replacement t t)))))
  357. (defun interblock-initiate-R-buffer ()
  358. "If there is not a current R process then create one."
  359. (unless (and (buffer-live-p interblock-R-buffer) (get-buffer interblock-R-buffer))
  360. (save-excursion
  361. (R)
  362. (setf interblock-R-buffer (current-buffer))
  363. (interblock-R-wait-for-output)
  364. (interblock-R-input-command ""))))
  365. (defun interblock-R-command-to-string (command)
  366. "Send a command to R, and return the results as a string."
  367. (interblock-R-input-command command)
  368. (interblock-R-last-output))
  369. (defun interblock-R-input-command (command)
  370. "Pass COMMAND to the R process running in `interblock-R-buffer'."
  371. (save-excursion
  372. (save-match-data
  373. (set-buffer interblock-R-buffer)
  374. (goto-char (process-mark (get-buffer-process (current-buffer))))
  375. (insert command)
  376. (comint-send-input)
  377. (interblock-R-wait-for-output))))
  378. (defun interblock-R-wait-for-output ()
  379. "Wait until output arrives"
  380. (save-excursion
  381. (save-match-data
  382. (set-buffer interblock-R-buffer)
  383. (while (progn
  384. (goto-char comint-last-input-end)
  385. (not (re-search-forward comint-prompt-regexp nil t)))
  386. (accept-process-output (get-buffer-process (current-buffer)))))))
  387. (defun interblock-R-last-output ()
  388. "Return the last R output as a string"
  389. (save-excursion
  390. (save-match-data
  391. (set-buffer interblock-R-buffer)
  392. (goto-char (process-mark (get-buffer-process (current-buffer))))
  393. (forward-line 0)
  394. (let ((raw (buffer-substring comint-last-input-end (- (point) 1))))
  395. (if (string-match "\n" raw)
  396. raw
  397. (and (string-match "\\[[[:digit:]+]\\] *\\(.*\\)$" raw)
  398. (message raw)
  399. (message (match-string 1 raw))
  400. (match-string 1 raw)))))))
  401. (provide 'org-exp-blocks)
  402. ;;; org-exp-blocks.el ends here