Merge branch 'maint'
[org-mode.git] / contrib / babel / library-of-babel.org
blob571eb706cfc8c5f804f399eb5cba25a0bbb101c7
1 #+title:    The Library of Babel
2 #+author:     Org-mode People
3 #+STARTUP:  oddeven hideblocks
5 * Introduction
7   The Library of Babel is an extensible collection of ready-made and
8   easily-shortcut-callable source-code blocks for handling common tasks.
9   Org-babel comes pre-populated with the source-code blocks located in this
10   file. It is possible to add source-code blocks from any org-mode file to
11   the library by calling =(org-babel-lob-ingest "path/to/file.org")=.
12   
13   This file is included in worg mainly less for viewing through the web
14   interface, and more for contribution through the worg git repository.  If
15   you have code snippets that you think others may find useful please add
16   them to this file and [[file:~/src/worg/worg-git.org::contribute-to-worg][contribute them]] to worg.
17   
18   The raw Org-mode text of this file can be downloaded at
19   [[repofile:contrib/babel/library-of-babel.org][library-of-babel.org]]
21 * Simple
23 A collection of simple utility functions:
25 #+name: echo
26 #+begin_src emacs-lisp :var input="echo'd"
27   input
28 #+end_src
30 * File I/O
32 ** Reading and writing files
34 Read the contents of the file at =file=.  The =:results vector= and
35 =:results scalar= header arguments can be used to read the contents of
36 file as either a table or a string.
38 #+name: read
39 #+begin_src emacs-lisp :var file="" :var format=""
40   (if (string= format "csv")
41       (with-temp-buffer
42         (org-table-import (expand-file-name file) nil)
43         (org-table-to-lisp))
44     (with-temp-buffer
45       (insert-file-contents (expand-file-name file))
46       (buffer-string)))
47 #+end_src
49 Write =data= to a file at =file=.  If =data= is a list, then write it
50 as a table in traditional Org-mode table syntax.
52 #+name: write
53 #+begin_src emacs-lisp :var data="" :var file="" :var ext='()
54   (flet ((echo (r) (if (stringp r) r (format "%S" r))))
55     (with-temp-file file
56       (case (and (listp data)
57                  (or ext (intern (file-name-extension file))))
58         ('tsv (insert (orgtbl-to-tsv data '(:fmt echo))))
59         ('csv (insert (orgtbl-to-csv data '(:fmt echo))))
60         (t    (org-babel-insert-result data)))))
61   nil
62 #+end_src
64 ** Remote files
66 **** json
68 Read local or remote file in [[http://www.json.org/][json]] format into emacs-lisp objects.
70 #+name: json
71 #+begin_src emacs-lisp :var file='() :var url='()
72   (require 'json)
73   (cond
74    (file
75     (with-temp-filebuffer file
76       (goto-char (point-min))
77       (json-read)))
78    (url
79     (require 'w3m)
80     (with-temp-buffer
81       (w3m-retrieve url)
82       (goto-char (point-min))
83       (json-read))))
84 #+end_src
86 **** Google docs
88 The following code blocks make use of the [[http://code.google.com/p/googlecl/][googlecl]] Google command line
89 tool.  This tool provides functionality for accessing Google services
90 from the command line, and the following code blocks use /googlecl/
91 for reading from and writing to Google docs with Org-mode code blocks.
93 ****** Read a document from Google docs
95 The =google= command seems to be throwing "Moved Temporarily" errors
96 when trying to download textual documents, but this is working fine
97 for spreadsheets.
99 #+name: gdoc-read
100 #+begin_src emacs-lisp :var title="example" :var format="csv"
101   (let* ((file (concat title "." format))
102          (cmd (format "google docs get --format %S --title %S" format title)))
103     (message cmd) (message (shell-command-to-string cmd))
104     (prog1 (if (string= format "csv")
105                (with-temp-buffer
106                  (org-table-import (shell-quote-argument file) '(4))
107                  (org-table-to-lisp))
108              (with-temp-buffer
109                (insert-file-contents (shell-quote-argument file))
110                (buffer-string)))
111       (delete-file file)))
112 #+end_src
114 For example, a line like the following can be used to read the
115 contents of a spreadsheet named =num-cells= into a table.
116 : #+call: gdoc-read(title="num-cells"")
118 A line like the following can be used to read the contents of a
119 document as a string.
121 : #+call: gdoc-read(title="loremi", :format "txt")
123 ****** Write a document to a Google docs
125 Write =data= to a google document named =title=.  If =data= is tabular
126 it will be saved to a spreadsheet, otherwise it will be saved as a
127 normal document.
129 #+name: gdoc-write
130 #+begin_src emacs-lisp :var title="babel-upload" :var data=fibs(n=10) :results silent
131   (let* ((format (if (listp data) "csv" "txt"))
132          (tmp-file (make-temp-file "org-babel-google-doc" nil (concat "." format)))
133          (cmd (format "google docs upload --title %S %S" title tmp-file)))
134     (with-temp-file tmp-file
135       (insert
136        (if (listp data)
137            (orgtbl-to-csv
138             data '(:fmt (lambda (el) (if (stringp el) el (format "%S" el)))))
139          (if (stringp data) data (format "%S" data)))))
140     (message cmd)
141     (prog1 (shell-command-to-string cmd) (delete-file tmp-file)))
142 #+end_src
144 example usage
145 : #+source: fibs
146 : #+begin_src emacs-lisp :var n=8
147 :   (flet ((fib (m) (if (< m 2) 1 (+ (fib (- m 1)) (fib (- m 2))))))
148 :     (mapcar (lambda (el) (list el (fib el))) (number-sequence 0 (- n 1))))
149 : #+end_src
151 : #+call: gdoc-write(title="fibs", data=fibs(n=10))
153 * Plotting code
155 ** R
157   Plot column 2 (y axis) against column 1 (x axis). Columns 3 and
158   beyond, if present, are ignored.
160 #+name: R-plot(data=R-plot-example-data)
161 #+begin_src R
162 plot(data)
163 #+end_src
165 #+tblname: R-plot-example-data
166 | 1 |  2 |
167 | 2 |  4 |
168 | 3 |  9 |
169 | 4 | 16 |
170 | 5 | 25 |
172 #+call: R-plot(data=R-plot-example-data)
174 #+resname: R-plot(data=R-plot-example-data)
175 : nil
177 ** Gnuplot
179 * Org reference
181 ** Headline references
183 #+name: headline
184 #+begin_src emacs-lisp :var headline=top :var file='()
185   (save-excursion
186     (when file (get-file-buffer file))
187     (org-open-link-from-string (org-make-link-string headline))
188     (save-restriction
189       (org-narrow-to-subtree)
190       (buffer-string)))
191 #+end_src
193 #+call: headline(headline="headline references")
195 * Tables
197 ** LaTeX Table Export
199 *** booktabs
201 This source block can be used to wrap a table in the latex =booktabs=
202 environment. The source block adds a =toprule= and =bottomrule= (so
203 don't use =hline= at the top or bottom of the table).  The =hline=
204 after the header is replaced with a =midrule=.
206 Note that this function bypasses the Org-mode LaTeX exporter and calls
207 =orgtbl-to-generic= to create the output table.  This means that the
208 entries in the table are not translated from Org-mode to LaTeX.
210 It takes the following arguments -- all but the first two are
211 optional.
213 | arg   | description                                |
214 |-------+--------------------------------------------|
215 | table | a reference to the table                   |
216 | align | alignment string                           |
217 | env   | optional environment, default to "tabular" |
218 | width | optional width specification string        |
220 #+name: booktabs
221 #+begin_src emacs-lisp :var table='((:head) hline (:body)) :var align='() :var env="tabular" :var width='() :noweb yes :results latex
222   (flet ((to-tab (tab)
223                  (orgtbl-to-generic
224                   (mapcar (lambda (lis)
225                             (if (listp lis)
226                                 (mapcar (lambda (el)
227                                           (if (stringp el)
228                                               el
229                                             (format "%S" el))) lis)
230                               lis)) tab)
231                   (list :lend " \\\\" :sep " & " :hline "\\hline"))))
232     (org-fill-template
233      "
234   \\begin{%env}%width%align
235   \\toprule
236   %table
237   \\bottomrule
238   \\end{%env}\n"
239      (list
240       (cons "env"       (or env "table"))
241       (cons "width"     (if width (format "{%s}" width) ""))
242       (cons "align"     (if align (format "{%s}" align) ""))
243       (cons "table"
244             ;; only use \midrule if it looks like there are column headers
245             (if (equal 'hline (second table))
246                 (concat (to-tab (list (first table)))
247                         "\n\\midrule\n"
248                         (to-tab (cddr table)))
249               (to-tab table))))))
250 #+end_src
252 *** longtable
254 This block can be used to wrap a table in the latex =longtable=
255 environment, it takes the following arguments -- all but the first two
256 are optional.
258 | arg       | description                                                 |
259 |-----------+-------------------------------------------------------------|
260 | table     | a reference to the table                                    |
261 | align     | optional alignment string                                   |
262 | width     | optional width specification string                         |
263 | hline     | the string to use as hline separator, defaults to "\\hline" |
264 | head      | optional "head" string                                      |
265 | firsthead | optional "firsthead" string                                 |
266 | foot      | optional "foot" string                                      |
267 | lastfoot  | optional "lastfoot" string                                  |
269 #+name: longtable
270 #+begin_src emacs-lisp :var table='((:table)) :var align='() :var width='() :var hline="\\hline" :var firsthead='() :var head='() :var foot='() :var lastfoot='() :noweb yes :results latex
271   (org-fill-template
272    "
273   \\begin{longtable}%width%align
274   %firsthead
275   %head
276   %foot
277   %lastfoot
278   
279   %table
280   \\end{longtable}\n"
281    (list
282     (cons "width"     (if width (format "{%s}" width) ""))
283     (cons "align"     (if align (format "{%s}" align) ""))
284     (cons "firsthead" (if firsthead (concat firsthead "\n\\endfirsthead\n") ""))
285     (cons "head"      (if head (concat head "\n\\endhead\n") ""))
286     (cons "foot"      (if foot (concat foot "\n\\endfoot\n") ""))
287     (cons "lastfoot"  (if lastfoot (concat lastfoot "\n\\endlastfoot\n") ""))
288     (cons "table" (orgtbl-to-generic
289                    (mapcar (lambda (lis)
290                              (if (listp lis)
291                                  (mapcar (lambda (el)
292                                            (if (stringp el)
293                                                el
294                                              (format "%S" el))) lis)
295                                lis)) table)
296                    (list :lend " \\\\" :sep " & " :hline hline)))))
297 #+end_src
300 *** booktabs-notes
302 This source block builds on [[booktabs]].  It accepts two additional
303 arguments, both of which are optional.
305 #+tblname: arguments
306 | arg    | description                                          |
307 |--------+------------------------------------------------------|
308 | notes  | an org-mode table with footnotes                     |
309 | lspace | if non-nil, insert =addlinespace= after =bottomrule= |
311 An example footnote to the =arguments= table specifies the column
312 span. Note the use of LaTeX, rather than Org-mode, markup.
314 #+tblname: arguments-notes
315 | \multicolumn{2}{l}{This is a footnote to the \emph{arguments} table.} |
317 #+name: booktabs-notes
318 #+begin_src emacs-lisp :var table='((:head) hline (:body)) :var notes='() :var align='() :var env="tabular" :var width='() :var lspace='() :noweb yes :results latex
319   (flet ((to-tab (tab)
320                  (orgtbl-to-generic
321                   (mapcar (lambda (lis)
322                             (if (listp lis)
323                                 (mapcar (lambda (el)
324                                           (if (stringp el)
325                                               el
326                                             (format "%S" el))) lis)
327                               lis)) tab)
328                   (list :lend " \\\\" :sep " & " :hline "\\hline"))))
329     (org-fill-template
330      "
331     \\begin{%env}%width%align
332     \\toprule
333     %table
334     \\bottomrule%spacer
335     %notes
336     \\end{%env}\n"
337      (list
338       (cons "env"       (or env "table"))
339       (cons "width"     (if width (format "{%s}" width) ""))
340       (cons "align"     (if align (format "{%s}" align) ""))
341       (cons "spacer"    (if lspace "\\addlinespace" ""))
342       (cons "table"
343             ;; only use \midrule if it looks like there are column headers
344             (if (equal 'hline (second table))
345                 (concat (to-tab (list (first table)))
346                         "\n\\midrule\n"
347                         (to-tab (cddr table)))
348               (to-tab table)))
349       (cons "notes" (if notes (to-tab notes) ""))
350       )))
351 #+end_src
353 ** Elegant lisp for transposing a matrix.
355 #+tblname: transpose-example
356 | 1 | 2 | 3 |
357 | 4 | 5 | 6 |
359 #+name: transpose
360 #+begin_src emacs-lisp :var table=transpose-example
361   (apply #'mapcar* #'list table)
362 #+end_src
364 #+resname:
365 | 1 | 4 |
366 | 2 | 5 |
367 | 3 | 6 |
369 ** Convert every element of a table to a string
371 #+tblname: hetero-table
372 | 1 | 2 | 3 |
373 | a | b | c |
375 #+name: all-to-string
376 #+begin_src emacs-lisp :var tbl='()
377   (defun all-to-string (tbl)
378     (if (listp tbl)
379         (mapcar #'all-to-string tbl)
380       (if (stringp tbl)
381           tbl
382         (format "%s" tbl))))
383   (all-to-string tbl)
384 #+end_src
386 #+begin_src emacs-lisp :var tbl=hetero-table
387   (mapcar (lambda (row) (mapcar (lambda (cell) (stringp cell)) row)) tbl)
388 #+end_src
390 #+name:
391 | nil | nil | nil |
392 | t   | t   | t   |
394 #+begin_src emacs-lisp :var tbl=all-to-string(hetero-table)
395   (mapcar (lambda (row) (mapcar (lambda (cell) (stringp cell)) row)) tbl)
396 #+end_src
398 #+name:
399 | t | t | t |
400 | t | t | t |
402 * Misc
404 ** File-specific Version Control logging
405    :PROPERTIES:
406    :AUTHOR: Luke Crook
407    :END:
408    
409 This function will attempt to retrieve the entire commit log for the
410 file associated with the current buffer and insert this log into the
411 export. The function uses the Emacs VC commands to interface to the
412 local version control system, but has only been tested to work with
413 Git. 'limit' is currently unsupported.
415 #+name: vc-log
416 #+headers: :var limit=-1
417 #+headers: :var buf=(buffer-name (current-buffer))
418 #+begin_src emacs-lisp
419   ;; Most of this code is copied from vc.el vc-print-log
420   (require 'vc)
421   (when (vc-find-backend-function
422          (vc-backend (buffer-file-name (get-buffer buf))) 'print-log)
423     (let ((limit -1)
424           (vc-fileset nil)
425           (backend nil)
426           (files nil))
427       (with-current-buffer (get-buffer buf)
428         (setq vc-fileset (vc-deduce-fileset t)) ; FIXME: Why t? --Stef
429         (setq backend (car vc-fileset))
430         (setq files (cadr vc-fileset)))
431       (with-temp-buffer 
432         (let ((status (vc-call-backend
433                        backend 'print-log files (current-buffer))))
434           (when (and (processp status)   ; Make sure status is a process
435                      (= 0 (process-exit-status status))) ; which has not terminated
436             (while (not (eq 'exit (process-status status)))
437               (sit-for 1 t)))
438           (buffer-string)))))
439 #+end_src
441 ** Trivial python code blocks
443 #+name: python-identity(a=1)
444 #+begin_src python
446 #+end_src
448 #+name: python-add(a=1, b=2)
449 #+begin_src python
450 a + b
451 #+end_src
453 ** Arithmetic
455 #+name: lob-add
456 #+begin_src emacs-lisp :var a=0 :var b=0
457   (+ a b)
458 #+end_src
460 #+name: lob-minus
461 #+begin_src emacs-lisp :var a=0 :var b=0
462   (- a b)
463 #+end_src
465 #+name: lob-times
466 #+begin_src emacs-lisp :var a=0 :var b=0
467   (* a b)
468 #+end_src
470 #+name: lob-div
471 #+begin_src emacs-lisp :var a=0 :var b=0
472   (/ a b)
473 #+end_src
475 * GANTT Charts
477 The =elispgantt= source block was sent to the mailing list by Eric
478 Fraga.  It was modified slightly by Tom Dye.
480 #+name: elispgantt
481 #+begin_src emacs-lisp :var table=gantttest
482   (let ((dates "")
483         (entries (nthcdr 2 table))
484         (milestones "")
485         (nmilestones 0)
486         (ntasks 0)
487         (projecttime 0)
488         (tasks "")
489         (xlength 1))
490     (message "Initial: %s\n" table)
491     (message "Entries: %s\n" entries)
492     (while entries
493       (let ((entry (first entries)))
494         (if (listp entry)
495             (let ((id (first entry))
496                   (type (nth 1 entry))
497                   (label (nth 2 entry))
498                   (task (nth 3 entry))
499                   (dependencies (nth 4 entry))
500                   (start (nth 5 entry))
501                   (duration (nth 6 entry))
502                   (end (nth 7 entry))
503                   (alignment (nth 8 entry)))
504               (if (> start projecttime) (setq projecttime start))
505               (if (string= type "task")
506                   (let ((end (+ start duration))
507                         (textposition (+ start (/ duration 2)))
508                         (flush ""))
509                     (if (string= alignment "left")
510                         (progn
511                           (setq textposition start)
512                           (setq flush "[left]"))
513                       (if (string= alignment "right")
514                           (progn
515                             (setq textposition end)
516                             (setq flush "[right]"))))
517                     (setq tasks
518                           (format "%s  \\gantttask{%s}{%s}{%d}{%d}{%d}{%s}\n"
519                                   tasks label task start end textposition flush))
520                     (setq ntasks (+ 1 ntasks))
521                     (if (> end projecttime)
522                         (setq projecttime end)))
523                 (if (string= type "milestone")
524                     (progn
525                       (setq milestones
526                             (format
527                              "%s  \\ganttmilestone{$\\begin{array}{c}\\mbox{%s}\\\\ \\mbox{%s}\\end{array}$}{%d}\n"
528                              milestones label task start))
529                       (setq nmilestones (+ 1 nmilestones)))
530                   (if (string= type "date")
531                       (setq dates (format "%s  \\ganttdateline{%s}{%d}\n"
532                                           dates label start))
533                     (message "Ignoring entry with type %s\n" type)))))
534           (message "Ignoring non-list entry %s\n" entry)) ; end if list entry
535         (setq entries (cdr entries))))  ; end while entries left
536     (format "\\pgfdeclarelayer{background}
537   \\pgfdeclarelayer{foreground}
538   \\pgfsetlayers{background,foreground}
539   \\renewcommand{\\ganttprojecttime}{%d}
540   \\renewcommand{\\ganttntasks}{%d}
541   \\noindent
542   \\begin{tikzpicture}[y=-0.75cm,x=0.75\\textwidth]
543     \\begin{pgfonlayer}{background}
544       \\draw[very thin, red!10!white] (0,1+\\ganttntasks) grid [ystep=0.75cm,xstep=1/\\ganttprojecttime] (1,0);
545       \\draw[\\ganttdatelinecolour] (0,0) -- (1,0);
546       \\draw[\\ganttdatelinecolour] (0,1+\\ganttntasks) -- (1,1+\\ganttntasks);
547     \\end{pgfonlayer}
548   %s
549   %s
550   %s
551   \\end{tikzpicture}" projecttime ntasks tasks milestones dates))
552 #+end_src
554 * Available languages
555   :PROPERTIES:
556   :AUTHOR:   Bastien
557   :END:
559 ** From Org's core
561 | Language   | Identifier | Language       | Identifier |
562 |------------+------------+----------------+------------|
563 | Asymptote  | asymptote  | Awk            | awk        |
564 | Emacs Calc | calc       | C              | C          |
565 | C++        | C++        | Clojure        | clojure    |
566 | CSS        | css        | ditaa          | ditaa      |
567 | Graphviz   | dot        | Emacs Lisp     | emacs-lisp |
568 | gnuplot    | gnuplot    | Haskell        | haskell    |
569 | Javascript | js         | LaTeX          | latex      |
570 | Ledger     | ledger     | Lisp           | lisp       |
571 | Lilypond   | lilypond   | MATLAB         | matlab     |
572 | Mscgen     | mscgen     | Objective Caml | ocaml      |
573 | Octave     | octave     | Org-mode       | org        |
574 |            |            | Perl           | perl       |
575 | Plantuml   | plantuml   | Python         | python     |
576 | R          | R          | Ruby           | ruby       |
577 | Sass       | sass       | Scheme         | scheme     |
578 | GNU Screen | screen     | shell          | sh         |
579 | SQL        | sql        | SQLite         | sqlite     |
581 ** From Org's contrib/babel/langs
583 - ob-oz.el, by Torsten Anders and Eric Schulte 
584 - ob-fomus.el, by Torsten Anders