org-exp-blocks.el 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  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. 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. "^#\\+begin_\\(\\S-+\\)[ \t]*\\(.*\\)?[\r\n]\\([^\000]*?\\)#\\+end_\\S-+.*" nil t)
  173. (save-match-data (setf type (intern (match-string 1))))
  174. (unless (memq type types) (setf types (cons type types)))
  175. (setf end (save-match-data (match-beginning 0)))
  176. (interblock start end type)
  177. (if (setf func (cadr (assoc type org-export-blocks)))
  178. (replace-match (save-match-data
  179. (if (memq type blocks)
  180. ""
  181. (apply func (match-string 3) (split-string (match-string 2) " ")))) t t))
  182. (setf start (save-match-data (match-end 0))))
  183. (mapcar (lambda (type)
  184. (interblock start (point-max) type))
  185. types)))))
  186. (add-hook 'org-export-preprocess-hook 'org-export-blocks-preprocess)
  187. ;;================================================================================
  188. ;; type specific functions
  189. ;;--------------------------------------------------------------------------------
  190. ;; ditaa: create images from ASCII art using the ditaa utility
  191. (defvar org-ditaa-jar-path (expand-file-name
  192. "ditaa.jar"
  193. (file-name-as-directory
  194. (expand-file-name
  195. "scripts"
  196. (file-name-as-directory
  197. (expand-file-name
  198. ".."
  199. (file-name-directory (or load-file-name buffer-file-name)))))))
  200. "Path to the ditaa jar executable")
  201. (defun org-export-blocks-format-ditaa (body &rest headers)
  202. "Pass block BODY to the ditaa utility creating an image.
  203. Specify the path at which the image should be saved as the first
  204. element of headers, any additional elements of headers will be
  205. passed to the ditaa utility as command line arguments."
  206. (message "ditaa-formatting...")
  207. (let ((out-file (if headers (car headers)))
  208. (args (if (cdr headers) (mapconcat 'identity (cdr headers) " ")))
  209. (data-file (make-temp-file "org-ditaa")))
  210. (unless (file-exists-p org-ditaa-jar-path)
  211. (error (format "Could not find ditaa.jar at %s" org-ditaa-jar-path)))
  212. (setq body (if (string-match "^\\([^:\\|:[^ ]\\)" body)
  213. body
  214. (mapconcat (lambda (x) (substring x (if (> (length x) 1) 2 1)))
  215. (org-split-string body "\n")
  216. "\n")))
  217. (cond
  218. ((or htmlp latexp docbookp)
  219. (with-temp-file data-file (insert body))
  220. (message (concat "java -jar " org-ditaa-jar-path " " args " " data-file " " out-file))
  221. (shell-command (concat "java -jar " org-ditaa-jar-path " " args " " data-file " " out-file))
  222. (format "\n[[file:%s]]\n" out-file))
  223. (t (concat
  224. "\n#+BEGIN_EXAMPLE\n"
  225. body (if (string-match "\n$" body) "" "\n")
  226. "#+END_EXAMPLE\n")))))
  227. ;;--------------------------------------------------------------------------------
  228. ;; dot: create graphs using the dot graphing language
  229. ;; (require the dot executable to be in your path)
  230. (defun org-export-blocks-format-dot (body &rest headers)
  231. "Pass block BODY to the dot graphing utility creating an image.
  232. Specify the path at which the image should be saved as the first
  233. element of headers, any additional elements of headers will be
  234. passed to the dot utility as command line arguments. Don't
  235. forget to specify the output type for the dot command, so if you
  236. are exporting to a file with a name like 'image.png' you should
  237. include a '-Tpng' argument, and your block should look like the
  238. following.
  239. #+begin_dot models.png -Tpng
  240. digraph data_relationships {
  241. \"data_requirement\" [shape=Mrecord, label=\"{DataRequirement|description\lformat\l}\"]
  242. \"data_product\" [shape=Mrecord, label=\"{DataProduct|name\lversion\lpoc\lformat\l}\"]
  243. \"data_requirement\" -> \"data_product\"
  244. }
  245. #+end_dot"
  246. (message "dot-formatting...")
  247. (let ((out-file (if headers (car headers)))
  248. (args (if (cdr headers) (mapconcat 'identity (cdr headers) " ")))
  249. (data-file (make-temp-file "org-ditaa")))
  250. (cond
  251. ((or htmlp latexp docbookp)
  252. (with-temp-file data-file (insert body))
  253. (message (concat "dot " data-file " " args " -o " out-file))
  254. (shell-command (concat "dot " data-file " " args " -o " out-file))
  255. (format "\n[[file:%s]]\n" out-file))
  256. (t (concat
  257. "\n#+BEGIN_EXAMPLE\n"
  258. body (if (string-match "\n$" body) "" "\n")
  259. "#+END_EXAMPLE\n")))))
  260. ;;--------------------------------------------------------------------------------
  261. ;; comment: export comments in author-specific css-stylable divs
  262. (defun org-export-blocks-format-comment (body &rest headers)
  263. "Format comment BODY by OWNER and return it formatted for export.
  264. Currently, this only does something for HTML export, for all
  265. other backends, it converts the comment into an EXAMPLE segment."
  266. (let ((owner (if headers (car headers)))
  267. (title (if (cdr headers) (mapconcat 'identity (cdr headers) " "))))
  268. (cond
  269. (htmlp ;; We are exporting to HTML
  270. (concat "#+BEGIN_HTML\n"
  271. "<div class=\"org-comment\""
  272. (if owner (format " id=\"org-comment-%s\" " owner))
  273. ">\n"
  274. (if owner (concat "<b>" owner "</b> ") "")
  275. (if (and title (> (length title) 0)) (concat " -- " title "</br>\n") "</br>\n")
  276. "<p>\n"
  277. "#+END_HTML\n"
  278. body
  279. "#+BEGIN_HTML\n"
  280. "</p>\n"
  281. "</div>\n"
  282. "#+END_HTML\n"))
  283. (t ;; This is not HTML, so just make it an example.
  284. (concat "#+BEGIN_EXAMPLE\n"
  285. (if title (concat "Title:" title "\n") "")
  286. (if owner (concat "By:" owner "\n") "")
  287. body
  288. (if (string-match "\n\\'" body) "" "\n")
  289. "#+END_EXAMPLE\n")))))
  290. ;;--------------------------------------------------------------------------------
  291. ;; R: Sweave-type functionality
  292. (defvar interblock-R-buffer nil
  293. "Holds the buffer for the current R process")
  294. (defvar count) ; dynamicaly scoped from `org-export-blocks-preprocess'?
  295. (defun org-export-blocks-format-R (body &rest headers)
  296. "Process R blocks and replace \R{} forms outside the blocks
  297. with their values as determined by R."
  298. (interactive)
  299. (message "R processing...")
  300. (let ((image-path (or (and (car headers)
  301. (string-match "\\(.?\\)\.\\(EPS\\|eps\\)" (car headers))
  302. (match-string 1 (car headers)))
  303. (and (> (length (car headers)) 0)
  304. (car headers))
  305. ;; create the default filename
  306. (format "Rplot-%03d" count)))
  307. (plot (string-match "plot" body))
  308. R-proc)
  309. (setf count (+ count 1))
  310. (interblock-initiate-R-buffer)
  311. (setf R-proc (get-buffer-process interblock-R-buffer))
  312. ;; send strings to the ESS process using `comint-send-string'
  313. (setf body (mapconcat (lambda (line)
  314. (interblock-R-input-command line) (concat "> " line))
  315. (butlast (split-string body "[\r\n]"))
  316. "\n"))
  317. ;; if there is a plot command, then create the images
  318. (when plot
  319. (interblock-R-input-command (format "dev.copy2eps(file=\"%s.eps\")" image-path)))
  320. (concat (cond
  321. (htmlp (org-export-blocks-html-quote body
  322. (format "<div id=\"R-%d\">\n<pre>\n" count)
  323. "</pre>\n</div>\n"))
  324. (latexp (org-export-blocks-latex-quote body
  325. "\\begin{Schunk}\n\\begin{Sinput}\n"
  326. "\\end{Sinput}\n\\end{Schunk}\n"))
  327. (t (insert ;; default export
  328. "#+begin_R " (mapconcat 'identity headers " ") "\n"
  329. body (if (string-match "\n$" body) "" "\n")
  330. "#+end_R\n")))
  331. (if plot
  332. (format "[[file:%s.eps]]\n" image-path)
  333. ""))))
  334. (defun org-export-interblocks-format-R (start end)
  335. "This is run over parts of the org-file which are between R
  336. blocks. It's main use is to expand the \R{stuff} chunks for
  337. export."
  338. (save-excursion
  339. (goto-char start)
  340. (interblock-initiate-R-buffer)
  341. (let (code replacement)
  342. (while (and (< (point) end) (re-search-forward "\\\\R{\\(.*\\)}" end t))
  343. (save-match-data (setf code (match-string 1)))
  344. (setf replacement (interblock-R-command-to-string code))
  345. (setf replacement (cond
  346. (htmlp replacement)
  347. (latexp replacement)
  348. (t replacement)))
  349. (setf end (+ end (- (length replacement) (length code))))
  350. (replace-match replacement t t)))))
  351. (defun interblock-initiate-R-buffer ()
  352. "If there is not a current R process then create one."
  353. (unless (and (buffer-live-p interblock-R-buffer) (get-buffer interblock-R-buffer))
  354. (save-excursion
  355. (R)
  356. (setf interblock-R-buffer (current-buffer))
  357. (interblock-R-wait-for-output)
  358. (interblock-R-input-command ""))))
  359. (defun interblock-R-command-to-string (command)
  360. "Send a command to R, and return the results as a string."
  361. (interblock-R-input-command command)
  362. (interblock-R-last-output))
  363. (defun interblock-R-input-command (command)
  364. "Pass COMMAND to the R process running in `interblock-R-buffer'."
  365. (save-excursion
  366. (save-match-data
  367. (set-buffer interblock-R-buffer)
  368. (goto-char (process-mark (get-buffer-process (current-buffer))))
  369. (insert command)
  370. (comint-send-input)
  371. (interblock-R-wait-for-output))))
  372. (defun interblock-R-wait-for-output ()
  373. "Wait until output arrives"
  374. (save-excursion
  375. (save-match-data
  376. (set-buffer interblock-R-buffer)
  377. (while (progn
  378. (goto-char comint-last-input-end)
  379. (not (re-search-forward comint-prompt-regexp nil t)))
  380. (accept-process-output (get-buffer-process (current-buffer)))))))
  381. (defun interblock-R-last-output ()
  382. "Return the last R output as a string"
  383. (save-excursion
  384. (save-match-data
  385. (set-buffer interblock-R-buffer)
  386. (goto-char (process-mark (get-buffer-process (current-buffer))))
  387. (forward-line 0)
  388. (let ((raw (buffer-substring comint-last-input-end (- (point) 1))))
  389. (if (string-match "\n" raw)
  390. raw
  391. (and (string-match "\\[[[:digit:]+]\\] *\\(.*\\)$" raw)
  392. (message raw)
  393. (message (match-string 1 raw))
  394. (match-string 1 raw)))))))
  395. (provide 'org-exp-blocks)
  396. ;;; org-exp-blocks.el ends here