1 #+title: The Library of Babel
2 #+author: Org-mode People
5 # This file is released by its authors and contributors under the GNU
6 # Free Documentation license v1.3 or later, code examples are released
7 # under the GNU General Public License v3 or later.
11 The Library of Babel is an extensible collection of ready-made and
12 easily-shortcut-callable source-code blocks for handling common tasks.
13 Org-babel comes pre-populated with the source-code blocks located in
14 this file. It is possible to add source-code blocks from any org-mode
15 file to the library by calling =(org-babel-lob-ingest
18 This file is included in worg mainly less for viewing through the web
19 interface, and more for contribution through the worg git repository.
20 If you have code snippets that you think others may find useful please
21 add them to this file and [[file:worg-about.org::*How to use git for Worg][How to use git for Worg]] to worg.
23 The raw Org-mode text of this file can be downloaded at
24 [[https://orgmode.org/worg/library-of-babel.org][library-of-babel.org]]
28 A collection of simple utility functions:
31 #+begin_src emacs-lisp :var input="echo'd"
37 ** Reading and writing files
39 Read the contents of the file at =file=. The =:results vector= and
40 =:results scalar= header arguments can be used to read the contents of
41 file as either a table or a string.
44 #+begin_src emacs-lisp :var file="" :var format=""
45 (if (string= format "csv")
47 (org-table-import (expand-file-name file) nil)
50 (insert-file-contents (expand-file-name file))
54 Write =data= to a file at =file=. If =data= is a list, then write it
55 as a table in traditional Org-mode table syntax.
58 #+begin_src emacs-lisp :var data="" :var file="" :var ext='()
59 (flet ((echo (r) (if (stringp r) r (format "%S" r))))
61 (case (and (listp data)
62 (or ext (intern (file-name-extension file))))
63 ('tsv (insert (orgtbl-to-tsv data '(:fmt echo))))
64 ('csv (insert (orgtbl-to-csv data '(:fmt echo))))
65 (t (org-babel-insert-result data)))))
73 Read local or remote file in [[http://www.json.org/][json]] format into emacs-lisp objects.
76 #+begin_src emacs-lisp :var file='() :var url='()
80 (org-babel-with-temp-filebuffer file
81 (goto-char (point-min))
87 (goto-char (point-min))
93 The following code blocks make use of the [[http://code.google.com/p/googlecl/][googlecl]] Google command line
94 tool. This tool provides functionality for accessing Google services
95 from the command line, and the following code blocks use /googlecl/
96 for reading from and writing to Google docs with Org-mode code blocks.
98 **** Read a document from Google docs
100 The =google= command seems to be throwing "Moved Temporarily" errors
101 when trying to download textual documents, but this is working fine
105 #+begin_src emacs-lisp :var title="example" :var format="csv"
106 (let* ((file (concat title "." format))
107 (cmd (format "google docs get --format %S --title %S" format title)))
108 (message cmd) (message (shell-command-to-string cmd))
109 (prog1 (if (string= format "csv")
111 (org-table-import (shell-quote-argument file) '(4))
114 (insert-file-contents (shell-quote-argument file))
119 For example, a line like the following can be used to read the
120 contents of a spreadsheet named =num-cells= into a table.
121 : #+call: gdoc-read(title="num-cells"")
123 A line like the following can be used to read the contents of a
124 document as a string.
126 : #+call: gdoc-read(title="loremi", :format "txt")
128 **** Write a document to a Google docs
130 Write =data= to a google document named =title=. If =data= is tabular
131 it will be saved to a spreadsheet, otherwise it will be saved as a
135 #+begin_src emacs-lisp :var title="babel-upload" :var data=fibs(n=10) :results silent
136 (let* ((format (if (listp data) "csv" "txt"))
137 (tmp-file (make-temp-file "org-babel-google-doc" nil (concat "." format)))
138 (cmd (format "google docs upload --title %S %S" title tmp-file)))
139 (with-temp-file tmp-file
143 data '(:fmt (lambda (el) (if (stringp el) el (format "%S" el)))))
144 (if (stringp data) data (format "%S" data)))))
146 (prog1 (shell-command-to-string cmd) (delete-file tmp-file)))
151 : #+begin_src emacs-lisp :var n=8
152 : (flet ((fib (m) (if (< m 2) 1 (+ (fib (- m 1)) (fib (- m 2))))))
153 : (mapcar (lambda (el) (list el (fib el))) (number-sequence 0 (- n 1))))
156 : #+call: gdoc-write(title="fibs", data=fibs(n=10))
162 Plot column 2 (y axis) against column 1 (x axis). Columns 3 and
163 beyond, if present, are ignored.
165 Running this code will create a file =Rplots.pdf= in the current working directory.
168 #+begin_src R :var data=R-plot-example-data
172 #+name: R-plot-example-data
179 #+call: R-plot(data=R-plot-example-data)
185 ** Headline references
188 #+begin_src emacs-lisp :var headline=top :var file='()
190 (when file (get-file-buffer file))
191 (org-open-link-from-string (org-make-link-string headline))
193 (org-narrow-to-subtree)
197 #+call: headline(headline="headline references")
201 ** LaTeX Table Export
205 This source block can be used to wrap a table in the latex =booktabs=
206 environment. The source block adds a =toprule= and =bottomrule= (so
207 don't use =hline= at the top or bottom of the table). The =hline=
208 after the header is replaced with a =midrule=.
210 Note that this function bypasses the Org-mode LaTeX exporter and calls
211 =orgtbl-to-generic= to create the output table. This means that the
212 entries in the table are not translated from Org-mode to LaTeX.
214 It takes the following arguments -- all but the first two are
217 | arg | description |
218 |-------+--------------------------------------------|
219 | table | a reference to the table |
220 | align | alignment string |
221 | env | optional environment, default to "tabular" |
222 | width | optional width specification string |
225 #+begin_src emacs-lisp :var table='((:head) hline (:body)) :var align='() :var env="tabular" :var width='() :noweb yes :results latex
228 (mapcar (lambda (lis)
233 (format "%S" el))) lis)
235 (list :lend " \\\\" :sep " & " :hline "\\hline"))))
238 \\begin{%env}%width%align
244 (cons "env" (or env "table"))
245 (cons "width" (if width (format "{%s}" width) ""))
246 (cons "align" (if align (format "{%s}" align) ""))
248 ;; only use \midrule if it looks like there are column headers
249 (if (equal 'hline (second table))
250 (concat (to-tab (list (first table)))
252 (to-tab (cddr table)))
258 This block can be used to wrap a table in the latex =longtable=
259 environment, it takes the following arguments -- all but the first two
262 | arg | description |
263 |-----------+-------------------------------------------------------------|
264 | table | a reference to the table |
265 | align | optional alignment string |
266 | width | optional width specification string |
267 | hline | the string to use as hline separator, defaults to "\\hline" |
268 | head | optional "head" string |
269 | firsthead | optional "firsthead" string |
270 | foot | optional "foot" string |
271 | lastfoot | optional "lastfoot" string |
274 #+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
277 \\begin{longtable}%width%align
286 (cons "width" (if width (format "{%s}" width) ""))
287 (cons "align" (if align (format "{%s}" align) ""))
288 (cons "firsthead" (if firsthead (concat firsthead "\n\\endfirsthead\n") ""))
289 (cons "head" (if head (concat head "\n\\endhead\n") ""))
290 (cons "foot" (if foot (concat foot "\n\\endfoot\n") ""))
291 (cons "lastfoot" (if lastfoot (concat lastfoot "\n\\endlastfoot\n") ""))
292 (cons "table" (orgtbl-to-generic
293 (mapcar (lambda (lis)
298 (format "%S" el))) lis)
300 (list :lend " \\\\" :sep " & " :hline hline)))))
305 This source block builds on [[booktabs]]. It accepts two additional
306 arguments, both of which are optional.
309 | arg | description |
310 |--------+------------------------------------------------------|
311 | notes | an org-mode table with footnotes |
312 | lspace | if non-nil, insert =addlinespace= after =bottomrule= |
314 An example footnote to the =arguments= table specifies the column
315 span. Note the use of LaTeX, rather than Org-mode, markup.
317 #+tblname: arguments-notes
318 | \multicolumn{2}{l}{This is a footnote to the \emph{arguments} table.} |
320 #+name: booktabs-notes
321 #+begin_src emacs-lisp :var table='((:head) hline (:body)) :var notes='() :var align='() :var env="tabular" :var width='() :var lspace='() :noweb yes :results latex
324 (mapcar (lambda (lis)
329 (format "%S" el))) lis)
331 (list :lend " \\\\" :sep " & " :hline "\\hline"))))
334 \\begin{%env}%width%align
341 (cons "env" (or env "table"))
342 (cons "width" (if width (format "{%s}" width) ""))
343 (cons "align" (if align (format "{%s}" align) ""))
344 (cons "spacer" (if lspace "\\addlinespace" ""))
346 ;; only use \midrule if it looks like there are column headers
347 (if (equal 'hline (second table))
348 (concat (to-tab (list (first table)))
350 (to-tab (cddr table)))
352 (cons "notes" (if notes (to-tab notes) ""))
356 ** Elegant lisp for transposing a matrix
358 #+tblname: transpose-example
363 #+begin_src emacs-lisp :var table=transpose-example
364 (apply #'mapcar* #'list table)
372 ** Convert every element of a table to a string
374 #+tblname: hetero-table
378 #+name: all-to-string
379 #+begin_src emacs-lisp :var tbl='()
380 (defun all-to-string (tbl)
382 (mapcar #'all-to-string tbl)
389 #+begin_src emacs-lisp :var tbl=hetero-table
390 (mapcar (lambda (row) (mapcar (lambda (cell) (stringp cell)) row)) tbl)
397 #+begin_src emacs-lisp :var tbl=all-to-string(hetero-table)
398 (mapcar (lambda (row) (mapcar (lambda (cell) (stringp cell)) row)) tbl)
407 ** File-specific Version Control logging
412 This function will attempt to retrieve the entire commit log for the
413 file associated with the current buffer and insert this log into the
414 export. The function uses the Emacs VC commands to interface to the
415 local version control system, but has only been tested to work with
416 Git. 'limit' is currently unsupported.
419 #+headers: :var limit=-1
420 #+headers: :var buf=(buffer-name (current-buffer))
421 #+begin_src emacs-lisp
422 ;; Most of this code is copied from vc.el vc-print-log
424 (when (vc-find-backend-function
425 (vc-backend (buffer-file-name (get-buffer buf))) 'print-log)
430 (with-current-buffer (get-buffer buf)
431 (setq vc-fileset (vc-deduce-fileset t)) ; FIXME: Why t? --Stef
432 (setq backend (car vc-fileset))
433 (setq files (cadr vc-fileset)))
435 (let ((status (vc-call-backend
436 backend 'print-log files (current-buffer))))
437 (when (and (processp status) ; Make sure status is a process
438 (= 0 (process-exit-status status))) ; which has not terminated
439 (while (not (eq 'exit (process-status status)))
444 ** Trivial python code blocks
446 #+name: python-identity
447 #+begin_src python :var a=1
452 #+begin_src python :var a=1 :var b=2
459 #+begin_src emacs-lisp :var a=0 :var b=0
464 #+begin_src emacs-lisp :var a=0 :var b=0
469 #+begin_src emacs-lisp :var a=0 :var b=0
474 #+begin_src emacs-lisp :var a=0 :var b=0
480 The =elispgantt= source block was sent to the mailing list by Eric
481 Fraga. It was modified slightly by Tom Dye.
484 #+begin_src emacs-lisp :var table=gantttest
486 (entries (nthcdr 2 table))
493 (message "Initial: %s\n" table)
494 (message "Entries: %s\n" entries)
496 (let ((entry (first entries)))
498 (let ((id (first entry))
500 (label (nth 2 entry))
502 (dependencies (nth 4 entry))
503 (start (nth 5 entry))
504 (duration (nth 6 entry))
506 (alignment (nth 8 entry)))
507 (if (> start projecttime) (setq projecttime start))
508 (if (string= type "task")
509 (let ((end (+ start duration))
510 (textposition (+ start (/ duration 2)))
512 (if (string= alignment "left")
514 (setq textposition start)
515 (setq flush "[left]"))
516 (if (string= alignment "right")
518 (setq textposition end)
519 (setq flush "[right]"))))
521 (format "%s \\gantttask{%s}{%s}{%d}{%d}{%d}{%s}\n"
522 tasks label task start end textposition flush))
523 (setq ntasks (+ 1 ntasks))
524 (if (> end projecttime)
525 (setq projecttime end)))
526 (if (string= type "milestone")
530 "%s \\ganttmilestone{$\\begin{array}{c}\\mbox{%s}\\\\ \\mbox{%s}\\end{array}$}{%d}\n"
531 milestones label task start))
532 (setq nmilestones (+ 1 nmilestones)))
533 (if (string= type "date")
534 (setq dates (format "%s \\ganttdateline{%s}{%d}\n"
536 (message "Ignoring entry with type %s\n" type)))))
537 (message "Ignoring non-list entry %s\n" entry)) ; end if list entry
538 (setq entries (cdr entries)))) ; end while entries left
539 (format "\\pgfdeclarelayer{background}
540 \\pgfdeclarelayer{foreground}
541 \\pgfsetlayers{background,foreground}
542 \\renewcommand{\\ganttprojecttime}{%d}
543 \\renewcommand{\\ganttntasks}{%d}
545 \\begin{tikzpicture}[y=-0.75cm,x=0.75\\textwidth]
546 \\begin{pgfonlayer}{background}
547 \\draw[very thin, red!10!white] (0,1+\\ganttntasks) grid [ystep=0.75cm,xstep=1/\\ganttprojecttime] (1,0);
548 \\draw[\\ganttdatelinecolour] (0,0) -- (1,0);
549 \\draw[\\ganttdatelinecolour] (0,1+\\ganttntasks) -- (1,1+\\ganttntasks);
554 \\end{tikzpicture}" projecttime ntasks tasks milestones dates))
557 * Available languages
564 | Language | Identifier | Language | Identifier |
565 |------------+------------+----------------+------------|
566 | Asymptote | asymptote | Awk | awk |
567 | Emacs Calc | calc | C | C |
568 | C++ | C++ | Clojure | clojure |
569 | CSS | css | ditaa | ditaa |
570 | Graphviz | dot | Emacs Lisp | emacs-lisp |
571 | gnuplot | gnuplot | Haskell | haskell |
572 | Javascript | js | LaTeX | latex |
573 | Ledger | ledger | Lisp | lisp |
574 | Lilypond | lilypond | MATLAB | matlab |
575 | Mscgen | mscgen | Objective Caml | ocaml |
576 | Octave | octave | Org-mode | org |
578 | Plantuml | plantuml | Python | python |
579 | R | R | Ruby | ruby |
580 | Sass | sass | Scheme | scheme |
581 | GNU Screen | screen | shell | sh |
582 | SQL | sql | SQLite | sqlite |
584 ** From Org's contrib/babel/langs
586 - ob-oz.el, by Torsten Anders and Eric Schulte
587 - ob-fomus.el, by Torsten Anders
589 * Default result for block execution
591 When a source code block has no =:result= parameter, the default
592 behavior is to use the /functional value/ of the execution as the
593 result. However, some languages use an option to deviate from
594 this default behavior. Below is a list of such options:
596 | Org Babel file | Default result | Option |
597 |----------------+----------------+--------------------------------------------|
598 | ob-shell.el | output | org-babel-shell-results-defaults-to-output |