1 #+title: The Library of Babel
2 #+author: Org-mode People
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
10 this file. It is possible to add source-code blocks from any org-mode
11 file to the library by calling =(org-babel-lob-ingest
14 This file is included in worg mainly less for viewing through the web
15 interface, and more for contribution through the worg git repository.
16 If you have code snippets that you think others may find useful please
17 add them to this file and [[file:~/src/worg/worg-git.org::contribute-to-worg][contribute them]] to worg.
19 The raw Org-mode text of this file can be downloaded at
20 [[repofile:contrib/babel/library-of-babel.org][library-of-babel.org]]
24 A collection of simple utility functions:
27 #+begin_src emacs-lisp :var input="echo'd"
33 ** Reading and writing files
35 Read the contents of the file at =file=. The =:results vector= and
36 =:results scalar= header arguments can be used to read the contents of
37 file as either a table or a string.
40 #+begin_src emacs-lisp :var file="" :var format=""
41 (if (string= format "csv")
43 (org-table-import (expand-file-name file) nil)
46 (insert-file-contents (expand-file-name file))
50 Write =data= to a file at =file=. If =data= is a list, then write it
51 as a table in traditional Org-mode table syntax.
54 #+begin_src emacs-lisp :var data="" :var file="" :var ext='()
55 (flet ((echo (r) (if (stringp r) r (format "%S" r))))
57 (case (and (listp data)
58 (or ext (intern (file-name-extension file))))
59 ('tsv (insert (orgtbl-to-tsv data '(:fmt echo))))
60 ('csv (insert (orgtbl-to-csv data '(:fmt echo))))
61 (t (org-babel-insert-result data)))))
69 Read local or remote file in [[http://www.json.org/][json]] format into emacs-lisp objects.
72 #+begin_src emacs-lisp :var file='() :var url='()
76 (with-temp-filebuffer file
77 (goto-char (point-min))
83 (goto-char (point-min))
89 The following code blocks make use of the [[http://code.google.com/p/googlecl/][googlecl]] Google command line
90 tool. This tool provides functionality for accessing Google services
91 from the command line, and the following code blocks use /googlecl/
92 for reading from and writing to Google docs with Org-mode code blocks.
94 **** Read a document from Google docs
96 The =google= command seems to be throwing "Moved Temporarily" errors
97 when trying to download textual documents, but this is working fine
101 #+begin_src emacs-lisp :var title="example" :var format="csv"
102 (let* ((file (concat title "." format))
103 (cmd (format "google docs get --format %S --title %S" format title)))
104 (message cmd) (message (shell-command-to-string cmd))
105 (prog1 (if (string= format "csv")
107 (org-table-import (shell-quote-argument file) '(4))
110 (insert-file-contents (shell-quote-argument file))
115 For example, a line like the following can be used to read the
116 contents of a spreadsheet named =num-cells= into a table.
117 : #+call: gdoc-read(title="num-cells"")
119 A line like the following can be used to read the contents of a
120 document as a string.
122 : #+call: gdoc-read(title="loremi", :format "txt")
124 **** Write a document to a Google docs
126 Write =data= to a google document named =title=. If =data= is tabular
127 it will be saved to a spreadsheet, otherwise it will be saved as a
131 #+begin_src emacs-lisp :var title="babel-upload" :var data=fibs(n=10) :results silent
132 (let* ((format (if (listp data) "csv" "txt"))
133 (tmp-file (make-temp-file "org-babel-google-doc" nil (concat "." format)))
134 (cmd (format "google docs upload --title %S %S" title tmp-file)))
135 (with-temp-file tmp-file
139 data '(:fmt (lambda (el) (if (stringp el) el (format "%S" el)))))
140 (if (stringp data) data (format "%S" data)))))
142 (prog1 (shell-command-to-string cmd) (delete-file tmp-file)))
147 : #+begin_src emacs-lisp :var n=8
148 : (flet ((fib (m) (if (< m 2) 1 (+ (fib (- m 1)) (fib (- m 2))))))
149 : (mapcar (lambda (el) (list el (fib el))) (number-sequence 0 (- n 1))))
152 : #+call: gdoc-write(title="fibs", data=fibs(n=10))
158 Plot column 2 (y axis) against column 1 (x axis). Columns 3 and
159 beyond, if present, are ignored.
162 #+begin_src R :var data=R-plot-example-data
166 #+tblname: R-plot-example-data
173 #+call: R-plot(data=R-plot-example-data)
175 #+resname: R-plot(data=R-plot-example-data)
182 ** Headline references
185 #+begin_src emacs-lisp :var headline=top :var file='()
187 (when file (get-file-buffer file))
188 (org-open-link-from-string (org-make-link-string headline))
190 (org-narrow-to-subtree)
194 #+call: headline(headline="headline references")
198 ** LaTeX Table Export
202 This source block can be used to wrap a table in the latex =booktabs=
203 environment. The source block adds a =toprule= and =bottomrule= (so
204 don't use =hline= at the top or bottom of the table). The =hline=
205 after the header is replaced with a =midrule=.
207 Note that this function bypasses the Org-mode LaTeX exporter and calls
208 =orgtbl-to-generic= to create the output table. This means that the
209 entries in the table are not translated from Org-mode to LaTeX.
211 It takes the following arguments -- all but the first two are
214 | arg | description |
215 |-------+--------------------------------------------|
216 | table | a reference to the table |
217 | align | alignment string |
218 | env | optional environment, default to "tabular" |
219 | width | optional width specification string |
222 #+begin_src emacs-lisp :var table='((:head) hline (:body)) :var align='() :var env="tabular" :var width='() :noweb yes :results latex
225 (mapcar (lambda (lis)
230 (format "%S" el))) lis)
232 (list :lend " \\\\" :sep " & " :hline "\\hline"))))
235 \\begin{%env}%width%align
241 (cons "env" (or env "table"))
242 (cons "width" (if width (format "{%s}" width) ""))
243 (cons "align" (if align (format "{%s}" align) ""))
245 ;; only use \midrule if it looks like there are column headers
246 (if (equal 'hline (second table))
247 (concat (to-tab (list (first table)))
249 (to-tab (cddr table)))
255 This block can be used to wrap a table in the latex =longtable=
256 environment, it takes the following arguments -- all but the first two
259 | arg | description |
260 |-----------+-------------------------------------------------------------|
261 | table | a reference to the table |
262 | align | optional alignment string |
263 | width | optional width specification string |
264 | hline | the string to use as hline separator, defaults to "\\hline" |
265 | head | optional "head" string |
266 | firsthead | optional "firsthead" string |
267 | foot | optional "foot" string |
268 | lastfoot | optional "lastfoot" string |
271 #+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
274 \\begin{longtable}%width%align
283 (cons "width" (if width (format "{%s}" width) ""))
284 (cons "align" (if align (format "{%s}" align) ""))
285 (cons "firsthead" (if firsthead (concat firsthead "\n\\endfirsthead\n") ""))
286 (cons "head" (if head (concat head "\n\\endhead\n") ""))
287 (cons "foot" (if foot (concat foot "\n\\endfoot\n") ""))
288 (cons "lastfoot" (if lastfoot (concat lastfoot "\n\\endlastfoot\n") ""))
289 (cons "table" (orgtbl-to-generic
290 (mapcar (lambda (lis)
295 (format "%S" el))) lis)
297 (list :lend " \\\\" :sep " & " :hline hline)))))
302 This source block builds on [[booktabs]]. It accepts two additional
303 arguments, both of which are optional.
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
321 (mapcar (lambda (lis)
326 (format "%S" el))) lis)
328 (list :lend " \\\\" :sep " & " :hline "\\hline"))))
331 \\begin{%env}%width%align
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" ""))
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)))
347 (to-tab (cddr table)))
349 (cons "notes" (if notes (to-tab notes) ""))
353 ** Elegant lisp for transposing a matrix
355 #+tblname: transpose-example
360 #+begin_src emacs-lisp :var table=transpose-example
361 (apply #'mapcar* #'list table)
369 ** Convert every element of a table to a string
371 #+tblname: hetero-table
375 #+name: all-to-string
376 #+begin_src emacs-lisp :var tbl='()
377 (defun all-to-string (tbl)
379 (mapcar #'all-to-string tbl)
386 #+begin_src emacs-lisp :var tbl=hetero-table
387 (mapcar (lambda (row) (mapcar (lambda (cell) (stringp cell)) row)) tbl)
394 #+begin_src emacs-lisp :var tbl=all-to-string(hetero-table)
395 (mapcar (lambda (row) (mapcar (lambda (cell) (stringp cell)) row)) tbl)
404 ** File-specific Version Control logging
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.
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
421 (when (vc-find-backend-function
422 (vc-backend (buffer-file-name (get-buffer buf))) 'print-log)
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)))
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)))
441 ** Trivial python code blocks
443 #+name: python-identity
444 #+begin_src python :var a=1
449 #+begin_src python :var a=1 :var b=2
456 #+begin_src emacs-lisp :var a=0 :var b=0
461 #+begin_src emacs-lisp :var a=0 :var b=0
466 #+begin_src emacs-lisp :var a=0 :var b=0
471 #+begin_src emacs-lisp :var a=0 :var b=0
477 The =elispgantt= source block was sent to the mailing list by Eric
478 Fraga. It was modified slightly by Tom Dye.
481 #+begin_src emacs-lisp :var table=gantttest
483 (entries (nthcdr 2 table))
490 (message "Initial: %s\n" table)
491 (message "Entries: %s\n" entries)
493 (let ((entry (first entries)))
495 (let ((id (first entry))
497 (label (nth 2 entry))
499 (dependencies (nth 4 entry))
500 (start (nth 5 entry))
501 (duration (nth 6 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)))
509 (if (string= alignment "left")
511 (setq textposition start)
512 (setq flush "[left]"))
513 (if (string= alignment "right")
515 (setq textposition end)
516 (setq flush "[right]"))))
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")
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"
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}
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);
551 \\end{tikzpicture}" projecttime ntasks tasks milestones dates))
554 * Available languages
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 |
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