dir-locals.el: Set org-list-two-spaces-after-bullet-regexp to nil
[worg.git] / library-of-babel.org
blob1e54ba6205cc45f91d562840c6f6cea5866433ee
1 #+title:    The Library of Babel
2 #+author:     Org-mode People
3 #+STARTUP:  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
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
12 "path/to/file.org")=.
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:./worg-git.org::#contribute-to-worg][contribute them]] to worg.
19 The raw Org-mode text of this file can be downloaded at
20 [[https://orgmode.org/worg/library-of-babel.org][library-of-babel.org]]
22 * Simple
24 A collection of simple utility functions:
26 #+name: echo
27 #+begin_src emacs-lisp :var input="echo'd"
28   input
29 #+end_src
31 * File I/O
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.
39 #+name: read
40 #+begin_src emacs-lisp :var file="" :var format=""
41   (if (string= format "csv")
42       (with-temp-buffer
43         (org-table-import (expand-file-name file) nil)
44         (org-table-to-lisp))
45     (with-temp-buffer
46       (insert-file-contents (expand-file-name file))
47       (buffer-string)))
48 #+end_src
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.
53 #+name: write
54 #+begin_src emacs-lisp :var data="" :var file="" :var ext='()
55   (flet ((echo (r) (if (stringp r) r (format "%S" r))))
56     (with-temp-file file
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)))))
62   nil
63 #+end_src
65 ** Remote files
67 *** json
69 Read local or remote file in [[http://www.json.org/][json]] format into emacs-lisp objects.
71 #+name: json
72 #+begin_src emacs-lisp :var file='() :var url='()
73   (require 'json)
74   (cond
75    (file
76     (org-babel-with-temp-filebuffer file
77       (goto-char (point-min))
78       (json-read)))
79    (url
80     (require 'w3m)
81     (with-temp-buffer
82       (w3m-retrieve url)
83       (goto-char (point-min))
84       (json-read))))
85 #+end_src
87 *** Google docs
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
98 for spreadsheets.
100 #+name: gdoc-read
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")
106                (with-temp-buffer
107                  (org-table-import (shell-quote-argument file) '(4))
108                  (org-table-to-lisp))
109              (with-temp-buffer
110                (insert-file-contents (shell-quote-argument file))
111                (buffer-string)))
112       (delete-file file)))
113 #+end_src
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
128 normal document.
130 #+name: gdoc-write
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
136       (insert
137        (if (listp data)
138            (orgtbl-to-csv
139             data '(:fmt (lambda (el) (if (stringp el) el (format "%S" el)))))
140          (if (stringp data) data (format "%S" data)))))
141     (message cmd)
142     (prog1 (shell-command-to-string cmd) (delete-file tmp-file)))
143 #+end_src
145 example usage
146 : #+name: fibs
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))))
150 : #+end_src
152 : #+call: gdoc-write(title="fibs", data=fibs(n=10))
154 * Plotting code
156 ** R
158 Plot column 2 (y axis) against column 1 (x axis). Columns 3 and
159 beyond, if present, are ignored.
161 Running this code will create a file =Rplots.pdf= in the current working directory.
163 #+name: R-plot
164 #+begin_src R :var data=R-plot-example-data
165 plot(data)
166 #+end_src
168 #+name: R-plot-example-data
169 | 1 |  2 |
170 | 2 |  4 |
171 | 3 |  9 |
172 | 4 | 16 |
173 | 5 | 25 |
175 #+call: R-plot(data=R-plot-example-data)
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
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
299 *** booktabs-notes
301 This source block builds on [[booktabs]].  It accepts two additional
302 arguments, both of which are optional.
304 #+tblname: arguments
305 | arg    | description                                          |
306 |--------+------------------------------------------------------|
307 | notes  | an org-mode table with footnotes                     |
308 | lspace | if non-nil, insert =addlinespace= after =bottomrule= |
310 An example footnote to the =arguments= table specifies the column
311 span. Note the use of LaTeX, rather than Org-mode, markup.
313 #+tblname: arguments-notes
314 | \multicolumn{2}{l}{This is a footnote to the \emph{arguments} table.} |
316 #+name: booktabs-notes
317 #+begin_src emacs-lisp :var table='((:head) hline (:body)) :var notes='() :var align='() :var env="tabular" :var width='() :var lspace='() :noweb yes :results latex
318   (flet ((to-tab (tab)
319                  (orgtbl-to-generic
320                   (mapcar (lambda (lis)
321                             (if (listp lis)
322                                 (mapcar (lambda (el)
323                                           (if (stringp el)
324                                               el
325                                             (format "%S" el))) lis)
326                               lis)) tab)
327                   (list :lend " \\\\" :sep " & " :hline "\\hline"))))
328     (org-fill-template
329      "
330     \\begin{%env}%width%align
331     \\toprule
332     %table
333     \\bottomrule%spacer
334     %notes
335     \\end{%env}\n"
336      (list
337       (cons "env"       (or env "table"))
338       (cons "width"     (if width (format "{%s}" width) ""))
339       (cons "align"     (if align (format "{%s}" align) ""))
340       (cons "spacer"    (if lspace "\\addlinespace" ""))
341       (cons "table"
342             ;; only use \midrule if it looks like there are column headers
343             (if (equal 'hline (second table))
344                 (concat (to-tab (list (first table)))
345                         "\n\\midrule\n"
346                         (to-tab (cddr table)))
347               (to-tab table)))
348       (cons "notes" (if notes (to-tab notes) ""))
349       )))
350 #+end_src
352 ** Elegant lisp for transposing a matrix
354 #+tblname: transpose-example
355 | 1 | 2 | 3 |
356 | 4 | 5 | 6 |
358 #+name: transpose
359 #+begin_src emacs-lisp :var table=transpose-example
360   (apply #'mapcar* #'list table)
361 #+end_src
363 #+resname:
364 | 1 | 4 |
365 | 2 | 5 |
366 | 3 | 6 |
368 ** Convert every element of a table to a string
370 #+tblname: hetero-table
371 | 1 | 2 | 3 |
372 | a | b | c |
374 #+name: all-to-string
375 #+begin_src emacs-lisp :var tbl='()
376   (defun all-to-string (tbl)
377     (if (listp tbl)
378         (mapcar #'all-to-string tbl)
379       (if (stringp tbl)
380           tbl
381         (format "%s" tbl))))
382   (all-to-string tbl)
383 #+end_src
385 #+begin_src emacs-lisp :var tbl=hetero-table
386   (mapcar (lambda (row) (mapcar (lambda (cell) (stringp cell)) row)) tbl)
387 #+end_src
389 #+name:
390 | nil | nil | nil |
391 | t   | t   | t   |
393 #+begin_src emacs-lisp :var tbl=all-to-string(hetero-table)
394   (mapcar (lambda (row) (mapcar (lambda (cell) (stringp cell)) row)) tbl)
395 #+end_src
397 #+name:
398 | t | t | t |
399 | t | t | t |
401 * Misc
403 ** File-specific Version Control logging
404    :PROPERTIES:
405    :AUTHOR: Luke Crook
406    :END:
408 This function will attempt to retrieve the entire commit log for the
409 file associated with the current buffer and insert this log into the
410 export. The function uses the Emacs VC commands to interface to the
411 local version control system, but has only been tested to work with
412 Git. 'limit' is currently unsupported.
414 #+name: vc-log
415 #+headers: :var limit=-1
416 #+headers: :var buf=(buffer-name (current-buffer))
417 #+begin_src emacs-lisp
418   ;; Most of this code is copied from vc.el vc-print-log
419   (require 'vc)
420   (when (vc-find-backend-function
421          (vc-backend (buffer-file-name (get-buffer buf))) 'print-log)
422     (let ((limit -1)
423           (vc-fileset nil)
424           (backend nil)
425           (files nil))
426       (with-current-buffer (get-buffer buf)
427         (setq vc-fileset (vc-deduce-fileset t)) ; FIXME: Why t? --Stef
428         (setq backend (car vc-fileset))
429         (setq files (cadr vc-fileset)))
430       (with-temp-buffer
431         (let ((status (vc-call-backend
432                        backend 'print-log files (current-buffer))))
433           (when (and (processp status)   ; Make sure status is a process
434                      (= 0 (process-exit-status status))) ; which has not terminated
435             (while (not (eq 'exit (process-status status)))
436               (sit-for 1 t)))
437           (buffer-string)))))
438 #+end_src
440 ** Trivial python code blocks
442 #+name: python-identity
443 #+begin_src python :var a=1
445 #+end_src
447 #+name: python-add
448 #+begin_src python :var a=1 :var b=2
449 a + b
450 #+end_src
452 ** Arithmetic
454 #+name: lob-add
455 #+begin_src emacs-lisp :var a=0 :var b=0
456   (+ a b)
457 #+end_src
459 #+name: lob-minus
460 #+begin_src emacs-lisp :var a=0 :var b=0
461   (- a b)
462 #+end_src
464 #+name: lob-times
465 #+begin_src emacs-lisp :var a=0 :var b=0
466   (* a b)
467 #+end_src
469 #+name: lob-div
470 #+begin_src emacs-lisp :var a=0 :var b=0
471   (/ a b)
472 #+end_src
474 * GANTT Charts
476 The =elispgantt= source block was sent to the mailing list by Eric
477 Fraga.  It was modified slightly by Tom Dye.
479 #+name: elispgantt
480 #+begin_src emacs-lisp :var table=gantttest
481   (let ((dates "")
482         (entries (nthcdr 2 table))
483         (milestones "")
484         (nmilestones 0)
485         (ntasks 0)
486         (projecttime 0)
487         (tasks "")
488         (xlength 1))
489     (message "Initial: %s\n" table)
490     (message "Entries: %s\n" entries)
491     (while entries
492       (let ((entry (first entries)))
493         (if (listp entry)
494             (let ((id (first entry))
495                   (type (nth 1 entry))
496                   (label (nth 2 entry))
497                   (task (nth 3 entry))
498                   (dependencies (nth 4 entry))
499                   (start (nth 5 entry))
500                   (duration (nth 6 entry))
501                   (end (nth 7 entry))
502                   (alignment (nth 8 entry)))
503               (if (> start projecttime) (setq projecttime start))
504               (if (string= type "task")
505                   (let ((end (+ start duration))
506                         (textposition (+ start (/ duration 2)))
507                         (flush ""))
508                     (if (string= alignment "left")
509                         (progn
510                           (setq textposition start)
511                           (setq flush "[left]"))
512                       (if (string= alignment "right")
513                           (progn
514                             (setq textposition end)
515                             (setq flush "[right]"))))
516                     (setq tasks
517                           (format "%s  \\gantttask{%s}{%s}{%d}{%d}{%d}{%s}\n"
518                                   tasks label task start end textposition flush))
519                     (setq ntasks (+ 1 ntasks))
520                     (if (> end projecttime)
521                         (setq projecttime end)))
522                 (if (string= type "milestone")
523                     (progn
524                       (setq milestones
525                             (format
526                              "%s  \\ganttmilestone{$\\begin{array}{c}\\mbox{%s}\\\\ \\mbox{%s}\\end{array}$}{%d}\n"
527                              milestones label task start))
528                       (setq nmilestones (+ 1 nmilestones)))
529                   (if (string= type "date")
530                       (setq dates (format "%s  \\ganttdateline{%s}{%d}\n"
531                                           dates label start))
532                     (message "Ignoring entry with type %s\n" type)))))
533           (message "Ignoring non-list entry %s\n" entry)) ; end if list entry
534         (setq entries (cdr entries))))  ; end while entries left
535     (format "\\pgfdeclarelayer{background}
536   \\pgfdeclarelayer{foreground}
537   \\pgfsetlayers{background,foreground}
538   \\renewcommand{\\ganttprojecttime}{%d}
539   \\renewcommand{\\ganttntasks}{%d}
540   \\noindent
541   \\begin{tikzpicture}[y=-0.75cm,x=0.75\\textwidth]
542     \\begin{pgfonlayer}{background}
543       \\draw[very thin, red!10!white] (0,1+\\ganttntasks) grid [ystep=0.75cm,xstep=1/\\ganttprojecttime] (1,0);
544       \\draw[\\ganttdatelinecolour] (0,0) -- (1,0);
545       \\draw[\\ganttdatelinecolour] (0,1+\\ganttntasks) -- (1,1+\\ganttntasks);
546     \\end{pgfonlayer}
547   %s
548   %s
549   %s
550   \\end{tikzpicture}" projecttime ntasks tasks milestones dates))
551 #+end_src
553 * Available languages
554   :PROPERTIES:
555   :AUTHOR:   Bastien
556   :END:
558 ** From Org's core
560 | Language   | Identifier | Language       | Identifier |
561 |------------+------------+----------------+------------|
562 | Asymptote  | asymptote  | Awk            | awk        |
563 | Emacs Calc | calc       | C              | C          |
564 | C++        | C++        | Clojure        | clojure    |
565 | CSS        | css        | ditaa          | ditaa      |
566 | Graphviz   | dot        | Emacs Lisp     | emacs-lisp |
567 | gnuplot    | gnuplot    | Haskell        | haskell    |
568 | Javascript | js         | LaTeX          | latex      |
569 | Ledger     | ledger     | Lisp           | lisp       |
570 | Lilypond   | lilypond   | MATLAB         | matlab     |
571 | Mscgen     | mscgen     | Objective Caml | ocaml      |
572 | Octave     | octave     | Org-mode       | org        |
573 |            |            | Perl           | perl       |
574 | Plantuml   | plantuml   | Python         | python     |
575 | R          | R          | Ruby           | ruby       |
576 | Sass       | sass       | Scheme         | scheme     |
577 | GNU Screen | screen     | shell          | sh         |
578 | SQL        | sql        | SQLite         | sqlite     |
580 ** From Org's contrib/babel/langs
582 - ob-oz.el, by Torsten Anders and Eric Schulte
583 - ob-fomus.el, by Torsten Anders