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