doc/org.texi: document `org-clock-timestamps-up'.
[org-mode.git] / contrib / babel / library-of-babel.org
blobe76b31319f342ba43766b031b1deba3205616ba2
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 #+srcname: 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 #+srcname: 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 #+srcname: 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 #+srcname: 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 #+source: 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 #+source: 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 #+srcname: 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 #+lob: 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 #+source: 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 block can be used to wrap a table in the latex =booktabs=
202 environment, it takes the following arguments -- all but the first two
203 are optional.
205 | arg   | description                                |
206 |-------+--------------------------------------------|
207 | table | a reference to the table                   |
208 | align | optional alignment string                  |
209 | env   | optional environment, default to "tabular" |
210 | width | optional width specification string        |
212 #+srcname: booktabs
213 #+begin_src emacs-lisp :var table='((:head) hline (:body)) :var align='() :var env="tabular" :var width='() :noweb yes :results latex
214   (flet ((to-tab (tab)
215                  (orgtbl-to-generic
216                   (mapcar (lambda (lis)
217                             (if (listp lis)
218                                 (mapcar (lambda (el)
219                                           (if (stringp el)
220                                               el
221                                             (format "%S" el))) lis)
222                               lis)) tab)
223                   (list :lend " \\\\" :sep " & " :hline "\\hline"))))
224     (org-fill-template
225      "
226   \\begin{%env}%width%align
227   \\toprule
228   %table
229   \\bottomrule
230   \\end{%env}\n"
231      (list
232       (cons "env"       (or env "table"))
233       (cons "width"     (if width (format "{%s}" width) ""))
234       (cons "align"     (if align (format "{%s}" align) ""))
235       (cons "table"
236             ;; only use \midrule if it looks like there are column headers
237             (if (equal 'hline (second table))
238                 (concat (to-tab (list (first table)))
239                         "\n\\midrule\n"
240                         (to-tab (cddr table)))
241               (to-tab table))))))
242 #+end_src
244 *** Longtable
246 This block can be used to wrap a table in the latex =longtable=
247 environment, it takes the following arguments -- all but the first two
248 are optional.
250 | arg       | description                                                 |
251 |-----------+-------------------------------------------------------------|
252 | table     | a reference to the table                                    |
253 | align     | optional alignment string                                   |
254 | width     | optional width specification string                         |
255 | hline     | the string to use as hline separator, defaults to "\\hline" |
256 | head      | optional "head" string                                      |
257 | firsthead | optional "firsthead" string                                 |
258 | foot      | optional "foot" string                                      |
259 | lastfoot  | optional "lastfoot" string                                  |
261 #+srcname: longtable
262 #+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
263   (org-fill-template
264    "
265   \\begin{longtable}%width%align
266   %firsthead
267   %head
268   %foot
269   %lastfoot
270   
271   %table
272   \\end{longtable}\n"
273    (list
274     (cons "width"     (if width (format "{%s}" width) ""))
275     (cons "align"     (if align (format "{%s}" align) ""))
276     (cons "firsthead" (if firsthead (concat firsthead "\n\\endfirsthead\n") ""))
277     (cons "head"      (if head (concat head "\n\\endhead\n") ""))
278     (cons "foot"      (if foot (concat foot "\n\\endfoot\n") ""))
279     (cons "lastfoot"  (if lastfoot (concat lastfoot "\n\\endlastfoot\n") ""))
280     (cons "table" (orgtbl-to-generic
281                    (mapcar (lambda (lis)
282                              (if (listp lis)
283                                  (mapcar (lambda (el)
284                                            (if (stringp el)
285                                                el
286                                              (format "%S" el))) lis)
287                                lis)) table)
288                    (list :lend " \\\\" :sep " & " :hline hline)))))
289 #+end_src
291 ** Elegant lisp for transposing a matrix.
293 #+tblname: transpose-example
294 | 1 | 2 | 3 |
295 | 4 | 5 | 6 |
297 #+srcname: transpose
298 #+begin_src emacs-lisp :var table=transpose-example
299   (apply #'mapcar* #'list table)
300 #+end_src
302 #+resname:
303 | 1 | 4 |
304 | 2 | 5 |
305 | 3 | 6 |
307 * Misc
309 ** File-specific Version Control logging
310    :PROPERTIES:
311    :AUTHOR: Luke Crook
312    :END:
313    
314 This function will attempt to retrieve the entire commit log for the
315 file associated with the current buffer and insert this log into the
316 export. The function uses the Emacs VC commands to interface to the
317 local version control system, but has only been tested to work with
318 Git. 'limit' is currently unsupported.
320 #+source: vc-log
321 #+headers: :var limit=-1
322 #+headers: :var buf=(buffer-name (current-buffer))
323 #+begin_src emacs-lisp
324   ;; Most of this code is copied from vc.el vc-print-log
325   (require 'vc)
326   (when (vc-find-backend-function
327          (vc-backend (buffer-file-name (get-buffer buf))) 'print-log)
328     (let ((limit -1)
329           (vc-fileset nil)
330           (backend nil)
331           (files nil))
332       (with-current-buffer (get-buffer buf)
333         (setq vc-fileset (vc-deduce-fileset t)) ; FIXME: Why t? --Stef
334         (setq backend (car vc-fileset))
335         (setq files (cadr vc-fileset)))
336       (with-temp-buffer 
337         (let ((status (vc-call-backend
338                        backend 'print-log files (current-buffer))))
339           (when (and (processp status)   ; Make sure status is a process
340                      (= 0 (process-exit-status status))) ; which has not terminated
341             (while (not (eq 'exit (process-status status)))
342               (sit-for 1 t)))
343           (buffer-string)))))
344 #+end_src
346 ** Trivial python code blocks
348 #+srcname: python-identity(a=1)
349 #+begin_src python
351 #+end_src
353 #+srcname: python-add(a=1, b=2)
354 #+begin_src python
355 a + b
356 #+end_src
358 ** Arithmetic
360 #+source: lob-add
361 #+begin_src emacs-lisp :var a=0 :var b=0
362   (+ a b)
363 #+end_src
365 #+source: lob-minus
366 #+begin_src emacs-lisp :var a=0 :var b=0
367   (- a b)
368 #+end_src
370 #+source: lob-times
371 #+begin_src emacs-lisp :var a=0 :var b=0
372   (* a b)
373 #+end_src
375 #+source: lob-div
376 #+begin_src emacs-lisp :var a=0 :var b=0
377   (/ a b)
378 #+end_src
380 * GANTT Charts
382 The =elispgantt= source block was sent to the mailing list by Eric
383 Fraga.  It was modified slightly by Tom Dye.
385 #+source: elispgantt
386 #+begin_src emacs-lisp :var table=gantttest
387   (let ((dates "")
388         (entries (nthcdr 2 table))
389         (milestones "")
390         (nmilestones 0)
391         (ntasks 0)
392         (projecttime 0)
393         (tasks "")
394         (xlength 1))
395     (message "Initial: %s\n" table)
396     (message "Entries: %s\n" entries)
397     (while entries
398       (let ((entry (first entries)))
399         (if (listp entry)
400             (let ((id (first entry))
401                   (type (nth 1 entry))
402                   (label (nth 2 entry))
403                   (task (nth 3 entry))
404                   (dependencies (nth 4 entry))
405                   (start (nth 5 entry))
406                   (duration (nth 6 entry))
407                   (end (nth 7 entry))
408                   (alignment (nth 8 entry)))
409               (if (> start projecttime) (setq projecttime start))
410               (if (string= type "task")
411                   (let ((end (+ start duration))
412                         (textposition (+ start (/ duration 2)))
413                         (flush ""))
414                     (if (string= alignment "left")
415                         (progn
416                           (setq textposition start)
417                           (setq flush "[left]"))
418                       (if (string= alignment "right")
419                           (progn
420                             (setq textposition end)
421                             (setq flush "[right]"))))
422                     (setq tasks
423                           (format "%s  \\gantttask{%s}{%s}{%d}{%d}{%d}{%s}\n"
424                                   tasks label task start end textposition flush))
425                     (setq ntasks (+ 1 ntasks))
426                     (if (> end projecttime)
427                         (setq projecttime end)))
428                 (if (string= type "milestone")
429                     (progn
430                       (setq milestones
431                             (format
432                              "%s  \\ganttmilestone{$\\begin{array}{c}\\mbox{%s}\\\\ \\mbox{%s}\\end{array}$}{%d}\n"
433                              milestones label task start))
434                       (setq nmilestones (+ 1 nmilestones)))
435                   (if (string= type "date")
436                       (setq dates (format "%s  \\ganttdateline{%s}{%d}\n"
437                                           dates label start))
438                     (message "Ignoring entry with type %s\n" type)))))
439           (message "Ignoring non-list entry %s\n" entry)) ; end if list entry
440         (setq entries (cdr entries))))  ; end while entries left
441     (format "\\pgfdeclarelayer{background}
442   \\pgfdeclarelayer{foreground}
443   \\pgfsetlayers{background,foreground}
444   \\renewcommand{\\ganttprojecttime}{%d}
445   \\renewcommand{\\ganttntasks}{%d}
446   \\noindent
447   \\begin{tikzpicture}[y=-0.75cm,x=0.75\\textwidth]
448     \\begin{pgfonlayer}{background}
449       \\draw[very thin, red!10!white] (0,1+\\ganttntasks) grid [ystep=0.75cm,xstep=1/\\ganttprojecttime] (1,0);
450       \\draw[\\ganttdatelinecolour] (0,0) -- (1,0);
451       \\draw[\\ganttdatelinecolour] (0,1+\\ganttntasks) -- (1,1+\\ganttntasks);
452     \\end{pgfonlayer}
453   %s
454   %s
455   %s
456   \\end{tikzpicture}" projecttime ntasks tasks milestones dates))
457 #+end_src
459 * Available languages
460   :PROPERTIES:
461   :AUTHOR:   Bastien
462   :END:
464 ** From Org's core
466 | Language   | Identifier | Language       | Identifier |
467 |------------+------------+----------------+------------|
468 | Asymptote  | asymptote  | Awk            | awk        |
469 | Emacs Calc | calc       | C              | C          |
470 | C++        | C++        | Clojure        | clojure    |
471 | CSS        | css        | ditaa          | ditaa      |
472 | Graphviz   | dot        | Emacs Lisp     | emacs-lisp |
473 | gnuplot    | gnuplot    | Haskell        | haskell    |
474 | Javascript | js         | LaTeX          | latex      |
475 | Ledger     | ledger     | Lisp           | lisp       |
476 | Lilypond   | lilypond   | MATLAB         | matlab     |
477 | Mscgen     | mscgen     | Objective Caml | ocaml      |
478 | Octave     | octave     | Org-mode       | org        |
479 |            |            | Perl           | perl       |
480 | Plantuml   | plantuml   | Python         | python     |
481 | R          | R          | Ruby           | ruby       |
482 | Sass       | sass       | Scheme         | scheme     |
483 | GNU Screen | screen     | shell          | sh         |
484 | SQL        | sql        | SQLite         | sqlite     |
486 ** From Org's contrib/babel/langs
488 - ob-oz.el, by Torsten Anders and Eric Schulte 
489 - ob-fomus.el, by Torsten Anders