Skip to content

Latest commit

 

History

History
7263 lines (5924 loc) · 138 KB

scraps.org

File metadata and controls

7263 lines (5924 loc) · 138 KB

Org-mode Scraps

scraps

pretty printed source code block result

set the value

(defvar foo '(defun square (x)  (* x x)))
foo

prologue and epilogue in R code blocks

cat("Test")

export header argument dependent on backend

(message "do stuff")

parenthesis in prologue and epilogue

qwerty <- "test";

call line caching

(sit-for 1)
(message "bar=%S" bar)

This does not return immediately, because the block must execute.

This returns immediately thanks to the cached result.

#+RESULTS[1df20b5a51c3c710b11d7d9cac7272a66a85990f]: call-line-caching-called

bar="qux"

valid inline function names

echo no space
  • call_space ()
  • call_w/o-spaces() no space

quoted lines between block and result

date

#+RESULTS[767d8ce04ce746568cd0f3f1f8f621a3583b93c5]:

Fri Dec 13 15:05:38 MST 2013

literal example

A literal example
on two lines
(concatenate 'string x " for me.")

shell history, alias and environment variables

echo $SHELL
echo $HOME
source ~/.bashrc
alias | wc
env | wc
history | wc
echo $SHELL
echo $HOME
source ~/.alia
source ~/.bashrc
alias | wc
env | wc
history | wc

C undefined behavior

int i=0;
printf("%d %d %d %d\n", ++i, ++i, ++i, ++i);
int i=0;
printf("%d %d %d %d\n", i++, i++, i++, i++);
void p(int a, int b, int c, int d){
  printf("%d %d %d %d\n", a, b, c, d);
}

int i=0;
p(i++, i++, ++i, ++i);
int i=0;
std::cout << i++ << " " << i++ << " " << ++i << " " << ++i;

header arguments on call lines

"the result"
the result

the result

removing result with a silent header argument

evaluating the following code block will remove the related result.
date +%Y-%m-%d
2011-09-07

leading commas in code blocks

a <- c(1
       , 2
       , 3)
,this one will have commas removed
#+begin_src R
,  a <- c(1
,         , 2
,         , 3)
#+end_src

silent results in org but not in export

The results of the following code block will not be inserted during interactive evaluation but will during export.
echo  "I want to see this in HTML/PDF, but not in Org"

demarcation of indented blocks

Demarcating a block with the point part-way in a line should indent the remainder of the line in the second block.
echo 1
echo 2
echo 3
echo 4
  

becomes

echo 1
echo 2
echo
     3
echo 4

returning file type to inline call line

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec hendrerit tempor tellus. Donec pretium posuere tellus. Proin quam nisl, tincidunt et, mattis eget, convallis nec, purus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla posuere. Donec vitae dolor. Nullam tristique diam non turpis. call_nothing_to_something()[:results file] something.txt Cras placerat accumsan nulla. Nullam rutrum. Nam vestibulum accumsan nisl.
echo nothing

simple gnuplot plotting of Org-mode tables

xy
12
24
36
48
510
612
714
816
set term postscript
set title "test"
set auto x
set style data histogram
set style fill solid border -1
set boxwidth 0.9
plot data using 2:xtic(1)

simple indexing

123
456
789
echo $column
1 4 7

convert results to all string

'((1 2 3 4)
  ("a" "b" "c" "d"))
(defun all-to-string (tbl)
  (if (listp tbl)
      (mapcar #'all-to-string tbl)
    (if (stringp tbl)
        tbl
      (format "%s" tbl))))
(all-to-string tbl)
(mapcar (lambda (row) (mapcar (lambda (cell) (stringp cell)) row)) tbl)
nilnilnilnil
tttt
(mapcar (lambda (row) (mapcar (lambda (cell) (stringp cell)) row)) tbl)
tttt
tttt

simple short R block

c(1,23,54,5)
1
23
54
5

two blocks and a table

echo 1
echo 2
echo 3
echo "$input" |tail -1
one
two
3

inheriting the file property

+-----------------------------+
|                             |
|    +-----+                  |
|    |     |   +---------+    |
|    |     |   |         |    |
|    +-----+   |         |    |
|              |         |    |
|   file       |         |    |
| inheritance  +---------+    |
|                             |
+-----------------------------+

something.png

a table with tags

123
4org-babel6
(message "%S" table)
((1 2 3) (4 "org-babel" 6))

shell script output not in table

echo 1
echo 2
echo 3
1
2
3

inline code block and downstream src blocks

AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA something src_sh{echo eric} CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
echo schulte

EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE

with R

AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA blah blah src_R[:results output]{cat(rnorm(2))} CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC

DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD

updating a table

000
000
000
(setf (nth 1 table) '(2 2 2))
table

space around exported code blocks

try evaluating the following blocks, then removing their results with M-x `org-babel-remove-result’

Verbiage to begin the paragraph

echo eric

and verbiage to end the same paragraph.

echo 1
echo 2

and verbiage to end the same paragraph.

simple ditaa block

+-------+             +--------+
|       |             |        |
| Org   |------------>| Tex    |
|       |             |        |
+-------+             +--------+

work-flow.png

replacing a table

147
258
369
(mapcar (lambda (row) (mapcar (lambda (cell) (* cell 2)) row)) table)

ruby code block

1+2
3

bug with undefined function copy-seq

1:10

tangle before evaluating a code block

wc $TANGLED
2  2 11 it.sh
echo TEST

plot results with org-plot

df
Filesystem1K-blocksUsedAvailableUse%Mountedon
/dev/sda62883583684477121892334431%/
none299707267629963961%/dev
none3006056030060560%/dev/shm
none30060569630059601%/var/run
none3006056030060560%/var/lock
/dev/sda7144176824722256046462742053%/home

premature truncation of emacs-lisp results

'(nil nil nil nil)
(nil nil nil nil)

non-defined code blocks can still tangle

This will still tangle out to a file, and it opens in text mode, which
may be nice.  

expand noweb refs

SOMETHING=nothing
<<def-something>>
echo $SOMETHING

returning file names – interpreted as lists

echo "[[file:./cv.cls]]"
[[file:./cv.cls]]
echo "[[file:./cv.cls]]"

java code block

class myfirstjavaprog
{  
    public static void main(String args[])
    {
        System.out.println("Hello World!");
    }
}
Hello World!

exporting a ditaa example

/---------------\
|    test       |
|        {cBLU} |
\---------------/

blue.png

including noweb refs w/o last newline

<<my-name>> |\
<<capitalize-name>>
echo "eric schulte"
sed 's/^e/E/;s/ s/ S/'

simple sbe example

1
2
3
4
5
6
3.5
(let ((num (car lst)) (nums (cdr lst)))
  (/ (float (+ num (apply #'+ nums))) (1+ (length nums))))

eval never

launch missles

indexing into a list variable

(first lst)
0

or as a noweb reference

  • 0
  • 1
  • 2
echo <<external-list()[0]>>
0

data alias for resname

blahcontent
it
blahcontent

define a block with a name for noweb expansion

something

another block including the first block

<<simple(something="something else")>>

find a resource by global id

it
here it is

I’m the resource

here it is

longtable label and attr lines on code block results

foofoo
barbaz

another test

(* it it)

Here is a call_square(it=4), stuck in the middle of some prose.

Here is another 25^2=call_square(it=25).

multiple variables

Should work call_concat(1, 2, 3) 123 in order.

(format "%S%S%S" a b c)

Should be positive call_lob-minus(4, 3) 1 by order.

un-named variables

(* it it)

first we can name the argument with call_square(it=4) 16

then we can pass the argument unnamed with call_square(4) 16

(- a b)

To ensure that these arguments are passed in the correct order we can use the following call_minus(8, 4) -4

inline call line

(* 2 it)

This is the number src_sh[:var it=double(it=1)]{echo $it} in the middle

The following exports as a normal call line

Now here is an inline call call_double(it=1) stuck in the middle of some prose.

This one should not be exported call_double(it=2) because it is quoted.

Finally this next one should export, even though it starts a line call_double(it=3) because sometimes inline blocks fold with a paragraph.

And, a call with raw results call_double(4)[:results raw] should not have quoted results.

text and graphics from R

print(seq(1,10))
plot(seq(1,10))

example.png

large code in inline blocks

Here is some text with src_emacs-lisp[:var it=big-block]{it} in the middle.

clojure :results scalar

'(1 2 3)

expand variable during tangling

echo $VER

python session

x = 1
for i in range(1,5):
  x = x + i
  print x

print "I throw an error"
... ... ... 2
4
7
11
I throw an error
print y
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'y' is not defined

scalar emacs lisp results

'(1 2 3)
(1 2 3)

named code block export

This has a name which is not exported.
runif(n)

continued code blocks

(message "foo:%S" 1)
(message "un-named")
(message "bar:%S" 1)
(message "foo:%S" 2)
(message "bar:%S" 2)
(with-temp-buffer
  (insert-file-contents "scraps.el")
  (eval-buffer))

ruby with xmpfilter

2 + 2 # =>
3.times{ puts :hello }
2 + 2 # => 4
3.times{ puts :hello }
# >> hello
# >> hello
# >> hello

tangle test

This is
a test

quick testing new session code

echo foo
foo
puts "foo"
foo

:file and python

return 1

/tmp/test.png

simple shell

sleep 10 && ls
_config.yml
data
development.org
elsevier
index.org
paper
publish.org
scraps
scraps.html
scraps.org
scraps.tex
puts [1..4]
nil

testing new data names

123
(* simple 2)

results

data

my data is results

246

default directory examples in lisp

*default-pathname-defaults*
pwd
*default-pathname-defaults*
#P""

lisp body with multiple forms

(format t "~&eric")
(+ 1 2)
3

example #+call line expansion

this code block peeks inside of the `params’ variable which is used by babel during code block evaluation
;; this is cheating and shouldn't be done in user code :)
(or (cdr (assoc :foo params)) 'unset)

this code block evaluates to the following,

unset

this call line,

expands into the following which is evaluated as a normal code block by Babel.

results

this code block evaluates to the following,

awk example

123
456
789
{print $1}
1
4
7

passing values through to STDIN of shell code blocks

123
456
789
awk '{print $1}'
sed 's/4/middle/g'
1
middle
7

don’t match end_src inside of a block

echo '#+end_src'
#+end_src block

append tables

  • first-table
  • second-table
  • third-table
a1
b2
c3
d4
e5
f6
(mapcar #'org-babel-ref-resolve table-names)
(a 1)(b 2)
(c 3)(d 4)
(e 5)(f 6)

new names for results

1
data
1

changing the variable used to label data

(setq org-babel-result-fmt
      "^[ \t]*#\\+\\(TBLNAME\\|RESNAME\\|RESULTS\\|DATA\\):[ \t]*%s[ \t]*$")
2
data
2

ocaml

[3;2;3] @ [3;2;3;4;5];;
32332345

simple latex verbatim wrap example

(setq org-export-latex-verbatim-wrap
      '("{\\scriptsize\n\\begin{verbatim}\n" . "\\end{verbatim}\n}\n"))
echo eric schulte
echo another

inserting complicated results

((lambda (result) (condition-case nil (read result) (error result)))
 "(:return
 (:ok \"{:model #<MINLP f(x,y)={(x[0]-5)^2+(x[1]-3)^2-y*sqrt($x),2}>, :v #<Variables x={ 4.0, 4.0 } y={ 0 }>, :z nil}\")
 13)")
:return(:ok {:model #<MINLP f(x,y)={(x[0]-5)^2+(x[1]-3)^2-y*sqrt($x),2}>, :v #<Variables x={ 4.0, 4.0 } y={ 0 }>, :z nil})13

automatic org-mode formatting

echo "| 1 |"
echo "| 2 |"
(stringp in)
t

units in R plot

x <- -10:10
y <- x^2
plot(x, y, type="l", col="red", lty=1)

test.png

Ocaml appending blocks

block
[|1;2;3|];;
123

simple Oz example

{Browse 'Hello'}

complex numbers in tables and python, reference in table formula

return 'text'
“(0.0331901438056,0.000535222885197)”
“(0.0333434157791,0.000537930174356)”
“(0.0345727512157,0.000559346040457)”
“(0.0353146483908,0.000571501584524)”
“(0.0355522909393,0.000574387067408)”
“(0.0356575682336,0.000574851263615)”
“(0.0357806926897,0.000575051685084)”
text
‘(1 2 3 4)
4
(1 2 3 4)
#ERROR

using vectors to represent complex number is lisp

[1 2]
real:1 complex:2
(format "real:%d complex:%d" (aref it 0) (aref it 1))

reference the table in a table formula

(0.0331901438056,0.000535222885197)
4

externally referencing the table

(0.0331901438056,0.000535222885197)
(0.0333434157791,0.000537930174356)
(0.0345727512157,0.000559346040457)
(0.0353146483908,0.000571501584524)
(0.0355522909393,0.000574387067408)
(0.0356575682336,0.000574851263615)
(0.0357806926897,0.000575051685084)
return data
(0.0331901438056,0.000535222885197)
(0.0333434157791,0.000537930174356)
(0.0345727512157,0.000559346040457)
(0.0353146483908,0.000571501584524)
(0.0355522909393,0.000574387067408)
(0.0356575682336,0.000574851263615)
(0.0357806926897,0.000575051685084)

emacs-lisp printing with output to string

(let ((dog (sqrt 2))
      (cat 7))
  (print (format "%s %f" "Dog: " (eval dog)))
  (print (format "%s %d" "Cat: " (eval cat)) nil)
  (print "Fish."))
"Dog:  1.414214"

"Cat:  7"

"Fish."
(let ((dog (sqrt 2))
      (cat 7))
  `((dog ,dog)
    (cat ,cat)
    (fish)))
dog1.4142135623730951
cat7
fish

headers in R tables during export

conditionMean.offer
1.MMM48.49
2.MMU42.59
3.MUM44.87
4.UMU46.43
5.UUM44.15
6.UUU43.80
MAL46.28
UK44.1
All45.29
str(data)

#+name[135a7f73839b69d118780ca29a64c3840601f7b9]:

'data.frame':	9 obs. of  2 variables:
 $ condition : chr  "1.MMM" "2.MMU" "3.MUM" "4.UMU" ... 
 $ Mean.offer: num  48.5 42.6 44.9 46.4 44.1 ... eric

session associated with R block

x <- 1
y <- 2
y-x
1

detangling example

echo "this is the `sh-for-tangling' code block"
num=`expr 1 + 1`
echo "the value of num is $num"
echo "this is an unnamed code block"

vc-log

A version control log of this file. The vc-log code block lives in the library of babel.

CL example

(defun range (n &optional m)
  "Return the numbers in range."
  (loop for num from (if m n 0) to (if m m (- n 1)) collect num))

(mapcar #'list (mapcar #'1+ (range 10)))
1
2
3
4
5
6
7
8
9
10

tangling out vc information

  rm -rf ./R
  rm -f ./spreadSim.sub
  REVISION=$REV.$STATE
  tar -xf nsa.$REVISION.tar.gz
  $HOME/R/R/R-2.12.0/bin/Rscript --vanilla -e
"source('./R/generateLatinHypercubeScenarios.R'); doIt()"
  for SCENARIO in ./R/scenarios/*.R; do
    export SCENARIO=${SCENARIO#./R/scenarios/}
    qsub nsa.sub
  done

grabbing the current buffer during export

Eric
(message "buffer %S!" buf)

colnames with call lines

xparametervalue
0heat30
1heat30
names(name)
x
x
parameter
value
x
x
parameter
value

caching on export

#+name[e7b83e61596da84f85c5a24e61569576c802f9a2]: testcache

0.5900913320947440.1017504658084360.4871254081372170.92315583024174
0.4832920324988660.4276400723028930.9746361332945530.995571716455743
0.601902333321050.1226382791064680.4379594083875420.015639441087842

conflicting header arguments

code block

call line

eric

macros during tangling

First, add macro expansion to the new `org-babel-tangle-body-hook’.

(add-hook 'org-babel-tangle-body-hook
          (lambda () (org-export-preprocess-apply-macros)))

Then define the macro. Note: you may need to export the buffer before tangling so that the macro definition is noticed and processed by Org-mode.

Then on both export and tangling the macro in the following code block will be replaced.

echo org-mode set CONFIG_PARAMETER to: {{{CONFIG_PARAM01}}}

looks like a pipe in a table

(flet ((clean (in)
              (if (listp in)
                  (mapcar #'clean in)
                (if (stringp in)
                    (replace-regexp-in-string "¦" "|" in)
                  in))))
  (clean in))
first(a¦b)
second(1¦2)
$a; $b;
(1|2)

eval results as a list

return "(mapcar (lambda (el) (+ 1 el)) '(1 2))"
23
return "[1, 2]"
12
return [1, 2]
12
return "%r" % "[1 2]"
[1 2]

export of inline R code

Here I test inline code evaluation in R.
x <- 100
100

Now I want to export the value of x, which should be src_R[:session *R*]{x} .

Did the number 100 show up at the end of the previous sentence on export?

simple mysql

show tables;

leading/trailing spaces

  • ” pass through with space ”
res
 pass through with space 

results org raw wrap

Version 1

This version only prints the org code for the table, but does not interprets it.
cat(
    "|--|--|\n",
    "|name|[[./pdf1.pdf]]|\n",
    "|--|--|\n"
    )

Version 2

This version prints the table including the graph as expected, but :results is used twice as a header argument.
cat(
    "|--|--|\n",
    "|name|[[./pdf1.pdf]]|\n",
    "|--|--|\n"
    )

Version 3

Finally this version does only export the R code
cat(
    "|--|--|\n",
    "|name|[[./pdf1.pdf]]|\n",
    "|--|--|\n"
    )

literal reference in a table with sbe

“eric schulte”12
(length in)

reference to a commented out subtree

I do export

params

strip hline before processing a variables indices

1a
2b
3c
4d
table
hline
colAcolB
a1b1
a2b2
$a; $b;

new block regexp tests

Block 1 (Exports OK)

Block 1

Block 2 (Exports OK - double blank line no white-space in Block)

Block 3 (Fails - single blank line no white-space in Block)

Block 4 (Gets consumed by previous Block)

Block 4

Block 5 (Fails - no lines in Block)

Block 6 (Gets consumed by previous Block

Block 6

pass a vector to calc

y
[1 2 3]
3 y
[3, 6, 9]
(elt data 1)
2
1 * 8
8

don’t interpret tuples as elisp code

return (1,2)
(1, 2)

passing elisp-looking variables to code blocks

printf "passed in %s", $it
passed in (+ 1 1)
1(+ 1 1)
2(a b c)
3(+ 3 3)
$data
(a b c)
data
(a b c)

exporting cache and noweb

Sys.sleep(time=5)
1:10

#+name[e2c9e6c2f84563b590a765502057d92463e50182]: test_sleep

1
2
3
4
5
6
7
8
9
10

source block names in current buffer

(org-babel-src-block-names)

simple python block

foo = 8
foo += 1
9

sh return a list of elements with spaces

echo "eric schulte"
echo "dan davison"
echo "seb vauban"
  • (“eric” “schulte”)
  • (“dan” “davison”)
  • (“seb” “vauban”)
echo "eric schulte"
echo "dan davison"
echo "seb vauban"
eric schulte
dan davison
seb vauban

calc variables inside of parenthesis

testvar - 200
8800
(testvar - 200) 800
7040000

new lists

results embedded inside of a list

  1. this has results
    foo
        
  2. and this doesn’t work
    data
        
    foo
        

reading and writing

  • 1
  • two
  • 3
  • four
(reverse lst)

catch the file name during export

file-name

export of inline code blocks which are silent

(setf org-babel-default-inline-header-args
      '((:session . "none")
        (:results . (if (boundp 'org-current-export-file) "replace" "silent"))
        (:exports . "results")))

Here is an inline code block src_sh{echo 8} <- there

mentions of file names in file contents

directory to search
graph-dir

list all files in dir

find $dir -type f -exec basename {} \;
other
dan
eric
seb

association of files with mentions

for i in $files; do
    for j in `grep -l -r $i $dir`;do
        echo $i, `basename $j`
    done
done
othereric
otherseb
daneric
ericseb
sebdan

graphing with dot

echo "$associations"|awk '{print $1, "->", $2}'
other -> eric
other -> seb
dan -> eric
eric -> seb
seb -> dan
digraph G{
  $data
}

files.png

inline code block

here is an inline block src_R{1+1}

recutils

cat <<EOF > book.rec
# -*- mode: rec -*-
%rec: Book
%mandatory: Title
%type: Location enum loaned home unknown
%doc:
+ A book in my personal collection.

Title: GNU Emacs Manual
Author: Richard M. Stallman
Publisher: FSF
Location: home

Title: The Colour of Magic
Author: Terry Pratchett
Location: loaned

Title: Mio Cid
Author: Anonymous
Location: home

Title: chapters.gnu.org administration guide
Author: Nacho Gonzalez
Author: Jose E. Marchesi
Location: unknown

Title: Yeelong User Manual
Location: home

# End of books.rec
EOF

book.rec

Location = 'loaned'
TitleAuthor
The Colour of MagicTerry Pratchett
  
TitleAuthorAuthor_2
GNU Emacs ManualRichard M. Stallman
The Colour of MagicTerry Pratchett
Mio CidAnonymous
chapters.gnu.org administration guideNacho GonzalezJose E. Marchesi
Yeelong User Manual

SQL — example reading org-mode table into sql

ab
110
211
312
413
514
615
load data infile "$table" into mytable;

passing keywords inside header arguments

lst
:no-expandother

two vars in a properties block – not possible

(message "test1=%S test2=%S" test1 test2)

results in Error

let: Symbol's value as variable is void: test2

an alternative

  • 7
  • 8
(message "test1=%S test2=%S" (first tests) (second tests))
test1=7 test2=8

another alternative

var11
var22
print vars[0][1]
print vars[1][1]

how to set no-expand in properties

:test

tangles to

non-inlined inline code block

The Date is src_sh[:results replace]{date} at the time of this export.

src_sh[:results replace]{ls}

results replace not always working

for i in `seq 4`;do
    echo "- place $i in the list"
done

inline block src_emacs-lisp[:exports code :results replace]{(+ 1 1 1)} here is was

simple calc example

2*3
6

inserting wrappers eats following characters

Test

"\\begin{equation}\\frac{1}{2}\n\\end{equation}"

Watch me die :-(

creating a directory when needed for tangling

(ns something)

a helper function for the above

(defun mkdir-p (file &optional dir)
  "Create any parent directories of FILE if missing and return FILE."
  (make-directory (file-name-directory file) (or dir ".")) file)

allows the following

(ns something)

There is now a new header argument controlling this behavior

(message "contents")

passing arguments to the shell

eric
  schulte
    yes
more
1
2
3
echo "$data"|wc -l
3
(setq org-babel-sh-var-quote-fmt "`cat <<'BABEL_TABLE'\n%s\nBABEL_TABLE\n`")

wrap noweb references in comments

(setq x (+ 4 x))
(let ((x 1))
  (message "x=%s" x)
  <<wrappable>>
  (message "x=%s" x))

replace inline code block

This is src_emacs-lisp{(+ 1 2 3)} an inline block.
(defun replace-inline-block ()
  (interactive)
  (if (save-excursion (re-search-backward "[ \f\t\n\r\v]" nil t)
                      (looking-at org-babel-inline-src-block-regexp))
      (replace-match
       ((lambda (el) (if (stringp el) el (format "%S" el)))
        (org-babel-execute-src-block)) nil nil nil 1)
    (error "not inside of an inline source block.")))

noweb then variables

\begin{itemize}
\item first
\item data
\item third
\end{itemize}
\section{ordinals}
\label{sec:ordinals}
<<replaced-first>>

empty strings as arguments

(concat foo "bar")
bar

call lines

(* n 2)
6
6

language name abbreviations

(add-to-list 'org-src-lang-modes '("clj" . clojure))
(map (partial + 1) (range 20))

eval query

(setq org-confirm-babel-evaluate
      (lambda (lang body) (not (equal "ditaa" lang))))
lambda(lang body)(not (equal ditaa lang))
(message "eval'd")
eval'd
---

new file handling

ls -l

dirlisting

[[1, 2, 3, 4],
 [2, 4, 6, 8]]

ruby-out

(let ((today (replace-regexp-in-string "[ \t]" "-" (current-time-string))))
  (with-temp-file today
    (insert (message "I'm feeling %s"
                     (nth (random 3) (list "good" "bad" "just fine")))))
  today)

Mon-Dec-20-17:27:52-2010

from http://www.graphviz.org/Gallery/directed/fsm.gv.txt

digraph finite_state_machine {
        rankdir=LR;
        size="8,5"
        node [shape = doublecircle]; LR_0 LR_3 LR_4 LR_8;
        node [shape = circle];
        LR_0 -> LR_2 [ label = "SS(B)" ];
        LR_0 -> LR_1 [ label = "SS(S)" ];
        LR_1 -> LR_3 [ label = "S($end)" ];
        LR_2 -> LR_6 [ label = "SS(b)" ];
        LR_2 -> LR_5 [ label = "SS(a)" ];
        LR_2 -> LR_4 [ label = "S(A)" ];
        LR_5 -> LR_7 [ label = "S(b)" ];
        LR_5 -> LR_5 [ label = "S(a)" ];
        LR_6 -> LR_6 [ label = "S(b)" ];
        LR_6 -> LR_5 [ label = "S(a)" ];
        LR_7 -> LR_8 [ label = "S(b)" ];
        LR_7 -> LR_5 [ label = "S(a)" ];
        LR_8 -> LR_6 [ label = "S(b)" ];
        LR_8 -> LR_5 [ label = "S(a)" ];
}

fsa.png

tangle templates

some stuff here
some other stuff here
heading=$(cat<<EOF
<<template-heading>>
EOF
)
footing=$(cat<<EOF
<<template-footing>>
EOF
)
echo $heading
echo "$body"
echo $footing
some stuff here
something new
some other stuff here

missing lines on tangle

,one
,two
,three
,- eric
,- schulte

utf8 and latin-1 encodings

é
babel = unicode (t[0][0],"latin1")
local = unicode ("é","latin1")
22

Python requires a utf-8 coding prefix

s = "é"
é
s = "é"
print(s)
é

empty lines in R session output

x <- 1;
x
x + 1
x + 4
[1] 1
[1] 2
[1] 5

:eval query shows the name

date
Tue Nov 30 22:03:25 MST 2010

sql variables

tablevalueTable0
columnvalueColumn0
typevalueType0
nullabilityvalueNullability0

I want to apply the values onto the following chunk of code:

-- add column `@column' (if column does not exist yet)
IF NOT EXISTS (SELECT *
               FROM INFORMATION_SCHEMA.COLUMNS
               WHERE TABLE_NAME = '@table'
               AND COLUMN_NAME = '@column')
BEGIN
    ALTER TABLE $table
    ADD $column $type @nullability
END

python with return header argument

x = 8
y = 98
2
98

safe lists for Haskell

1first
2second
3third
4fourth
(defun rec-string-wrap (in)
  (if (listp in) (mapcar #'rec-string-wrap in) (format "%S" in)))
(rec-string-wrap data)
map head tbl
1234

add column to table with awk

I want to add a column to the following table.
This is line 1 of the message.
This is line 2 of the message.
This is the last line of the message.

Its value should be dependant on a regexp matching the current row (for example, if 1 is detected in the original column, then write “A” in the new one, “B” if 2 is read, “C” if 3 is read, etc.).

Hence, I’m thinking using AWK as an easy solution.

I'm open to other ideas on how I could do this as easily. Just throw me
ideas, if you have some.

the easiest (for me) would be with the elisp mapcar function

(mapcar (lambda (row) (cons "New col" row)) tbl)
New colThis is line 1 of the message.
New colThis is line 2 of the message.
New colThis is the last line of the message.

First trial: add a column whose cell contents will be fixed (here, equal to New col).

echo "$data" | awk '// {print "| New col | " $0 " |";}'
New colThis is line 1 of the message.
New colThis is line 2 of the message.
New colThis is the last line of the message.

reading from single-quote-delim languages

return [['607', 'Show license short, name on the deed'],
        ['255', "'(message (concat 'hello ' 'world))"]]
607Show license short, name on the deed
255‘(message (concat ‘hello ’ ‘world))
[['607', 'Show license, short name on the deed'],
 ['255', "))'(message (concat 'hello ' 'world"]]
607Show license, short name on the deed
255))’(message (concat ‘hello ’ ‘world
[["'single quotes'", "b"], ["\"double quotes\"", "d"]]
‘single quotes’b
“double quotes”d

un-named R code blocks

8
8
8  
8
xyz
9
[1] 9

introducing wrap header argument

(mapcar (lambda (el) (list el (+ 1 (* el el)))) (number-sequence 0 10))

now indented

  • first
  • second
    "something else"
        

lists as data types

  • org-mode
  • and
  • babel
(reverse lst)

also for a block inside of a list

  1. First element
  2. Second element – has a block
    (+ 1 1 1 1)
        
    4
        
  3. third element

sqlite

select count(*) from temps;
422689

lob calls with header argument pass through

n
15
10

need ob-ref.el to pass through the header arguments in “[]”s

n
8
n
8

clojure code blocks and the lazies

(defun org-babel-execute:clojure (body params)
  (with-temp-buffer
    (insert body)
    (read
     (slime-eval
      `(swank:interactive-eval-region 
        ,(buffer-substring-no-properties (point-min) (point-max)))))))
(map (fn [el] (list el (* el el)))(range 10))
00
11
24
39
416
525
636
749
864
981

playing with calc support

(require 'ob-calc)
some
some
'*
8+8
'+
80
2*(8+8)
32
2*e
5.43656365692
2*something
18

shell blocks returning a file name

date

quick.txt

passing arguments through call lines

plot(1:10, main=myarg)

test.pdf

test.pdf

simple gnuplot tests

11
24
39
416
525
636
749
864
plot "$data"

Plotting data points from a table could look like this:

xy1y2
0.10.4250.375
0.20.31250.3375
0.30.249999930.28333338
0.40.2750.28125
0.50.260.27
0.60.258333380.24999993
0.70.246428450.23928553
0.80.231250.2375
0.90.233333230.2333332
10.22250.22
set title "Putting it All Together"

set xlabel "X"
set xrange [0:1]
set xtics 0,0.1,1

set ylabel "Y"
set yrange [0.2:0.5]
set ytics 0.2,0.05,0.5

plot data u 1:2 w p lw 2 title 'x vs. y1', \
     data u 1:3 w lp lw 1 title 'x vx. y2'

basic-plot.png

latex headers in latex code blocks

Eric Schulte

name1.pdf

Eric Schulte

name2.pdf

export-specific header arguments

out
not latex

security problem with elisp in header arguments

(+ 1 1)

preceding blank lines on tangle

(setq org-babel-tangle-pad-newline nil)
# something
echo "else"

very very large numbers

1
2
12
45
166
12567890
231231282371983279389999999
(mapcar
 (lambda (line)
     (let ((number (car line)))
       (list number (type-of number))))
   numbers)
1integer
2integer
12integer
45integer
166integer
12567890integer
2.3123128237198328e+26float

weaving with noweb links

(message "eric")
;; name
<<name>>

index into a scalar

a
b
scalar
a

cycle – the input is the output

and the rhythm is the base and the base is the treble
one
two
three
(append (last table) (butlast table))

Letter

,My body includes a list:

,- one
,- two

,and a small table:

,| first | second |
,| other | last   |

,Not more.
\documentclass[11pt]{isodoc}
\usepackage[utf8x]{inputenc}
\usepackage[T1]{fontenc}

\setupdocument{
    to = {Eric},
    subject = {Tough to understand what to do...},
    opening = {Hi},
    closing = {Best}
}

\begin{document}
\letter{%
<<body()>>
}
\end{document}

splitting code blocks

  • with indentation
    ;;;###autoload
    (defun org-babel-previous-src-block (&optional arg)
      "Jump to the previous source block.
    With optional prefix argument ARG, jump backward ARG many source blocks."
      (interactive "P")
      (condition-case nil
          (re-search-backward org-babel-src-block-regexp nil nil (or arg 1))
        (error (error "No previous code blocks")))
      (goto-char (match-beginning 0)) (org-show-context))
        
    ;;;###autoload
    (defun org-babel-split-block-maybe (&optional arg)
      "Split the current source code block on the cursor."
      (interactive "p")
      ((lambda (info)
         (if info
             (let ((lang (nth 0 info))
                   (indent (nth 6 info))
                   (stars (make-string (org-current-level) ?*)))
               (insert (concat (if (looking-at "^") "" "\n")
                               (make-string indent ? ) "#+end_src\n"
                               (if arg stars (make-string indent ? )) "\n"
                               (make-string indent ? ) "#+begin_src " lang
                               (if (looking-at "[\n\r]") "" "\n  "))))
           (message "Not in src block.")))
       (org-babel-get-src-block-info)))
    
    ;; other stuff
        

header arguments on call line

8
8

maybe the following with the new proposed header arguments

empty-string results

test me one two 3

More test

(mapcar
 (lambda (pair)
   (list (car pair) (cdr pair)))
 params)
:cacheno
:colnamesno
:comments
:exportscode
:hlinesyes
:nowebno
:resultsreplace
:sessionnone
:shebang
:tangleno

tangle org-mode block

- one
- two
- three
"
<<org-list()>>
"

remove results when nil is returned

(progn (+ 1 1) nil)

comparative speed of python evaluation

2+2
4
return 2+2
4
def add(a,b):
   return a+b
def sub(a,b):
   return a-b
add(sub(10,1),sub(10,2))
org_babel_python_eoe

customizable comment formats

(setq org-babel-tangle-comment-format-beg "{-# LINE %start-line \"%file\" #-}"
      org-babel-tangle-comment-format-end ""
      org-babel-tangle-pad-newline)
test = length
main = print $ test [1,2,3]

I would like the following output in the tangled file Main.hs:

{-# LINE 4 "Haskell.org" #-}
test = length
main = print $ test [1,2,3]

tangling with full comments

The top block
(message "first block")

here’s some text which won’t be tangled

subheading

another block
1first
2second
(message "second")

and finally a block with a :noweb header argument

(progn
  <<tangle-el-the-second>>)

quoting header args (e.g. :cmdline)

int main(int argc, char **argv){
  printf("argv[1] %s\n", argv[1]);
  return 0;
}
argv[1] 1

:var (buffer-file-name)

during export (buffer-file-name) will return nil because the temporary export buffer is not visiting any file.

file=(vc-working-revision (buffer-file-name))

file=(vc-working-revision (or (buffer-file-name) org-current-export-file))

:session evaluation on export

This first block is evaluated but doesn’t appear in export.

:session *R* :exports none

This second block does appear in export.

ditaa with tilda in path

+--------------+
|              |
|              |
|              |
|              |
|              |
+--------------+

conditional tangling

(setq tangle-tag "right")

first subheading

"first"

second subheading

"second"

scheme sessions

(+ number 0)
9
(+ number 1)
10

pulling information from tags

color
blue

initial scheme support

(map (lambda (el) (+ el 1)) '(1 2 3))
234
(map (lambda (el) (- el 1)) numbers)
123

initial javascript support

using node.js
var n = 0;
n = n+1;
return n
1
var cars = ["Saab","Volvo","BMW"];
return cars;
SaabVolvoBMW
return cars[0][0];
Saab
return cars[0].length;
3

duplicate results on execute subtree

- first
- second
- third

eval for side effect on export

  • one plus one
  • plus one is
    (+ 1 two)
        

trying out plantuml

setup
(require 'ob-plantuml)
(setq org-plantuml-jar-path "~/src/org/contrib/scripts/plantuml.jar")

usage – sequence diagram

Alice -> Bob: synchronous call
Alice ->> Bob: asynchronous call

tryout.png

wrapping up raw/org results

- first
- second
- third

not caching

cat("random result:", runif(1), "\n")
Sys.sleep(2)
alarm()
cat("random result:", runif(1), "\n")
Sys.sleep(2)
alarm()

cache on export

do we export cached blocks

#+name[46632b4fe2e3a23e847953c95adcba58c270b381]:

490528137

looks like this is a problem with info collection

(format "%S" info)

#+name[4184710f118ac768ea0d90632508792d695efd7a]:

:cacheyes
:colnamesno
:commentsyes
:exportsresults
:hlinesyes
:nowebno
:resultsoutput replace scalar
:sessionR
:shebang
:tangleyes

#+name[0427db66afdc95462d1c8514b662829987d71ff5]:

0427db66afdc95462d1c8514b662829987d71ff5

eval and noeval

date, should export both, but won’t output results because of presence of the :noeval header argument.
date

should export code, so no need to do anything

date

should export nothing, and should not query

date

should export results, and should trigger query above

issues with shell evaluation

cd ~/src/org/
make

org results and replace

  "| 1 | 2 |
| 2 | 3 |"
12
23
rnorm(1)
numbers <- matrix(c(51,43,22,92,28,21,68,22,9),ncol=3,byrow=TRUE)
numbers
514322
922821
68229
numbers <- matrix(c(51,43,22,92,28,21,68,22,9),ncol=3,byrow=TRUE)
numbers
V1V2V3
514322
922821
68229

ledger example output text

09-Aug-21 CHEQUE : 9953055                    Expenses:Unknown                                    166.70 EUR            166.70 EUR
09-Sep-17 CHEQUE : 7691785                    Expenses:Unknown                                    100.00 EUR            266.70 EUR
09-Oct-16 REMISE CHEQUE N 8686318 001 105     Expenses:Unknown                                   -525.00 EUR           -258.30 EUR
echo "$stuff"

importing the output of ledger

09-Aug-21 CHEQUE : 9953055                    Expenses:Unknown                                    166.70 EUR            166.70 EUR
09-Sep-17 CHEQUE : 7691785                    Expenses:Unknown                                    100.00 EUR            266.70 EUR
09-Oct-16 REMISE CHEQUE N 8686318 001 105     Expenses:Unknown                                   -525.00 EUR           -258.30 EUR
(with-temp-buffer
  (insert ledger)
  (message ledger)
  (org-table-convert-region (point-min) (point-max) 2)
  (org-table-to-lisp))
09-Aug-21 CHEQUE : 9953055Expenses:Unknown166.70 EUR166.70 EUR
09-Sep-17 CHEQUE : 7691785Expenses:Unknown100.00 EUR266.70 EUR
09-Oct-16 REMISE CHEQUE N 8686318 001 105Expenses:Unknown-525.00 EUR-258.30 EUR

lob – writing results out to files

(mapcar
 (lambda (el) (number-sequence el (+ el 3)))
 (number-sequence 0 4))

writes the results out as csv file

writes the results out as tab separated file

write the results out as a normal org-mode file

lisp

(mapcar (lambda (el) (* el el)) (append '(1 7 3 4) (list n)))
14991625
1
2
3
(+ 1 (length lst))
4

comments in R blocks

# this is a comment
x <- rnorm(1)
# this is another comment
x
[1] 1.320853

tangle R and load

evaluate this

(setq org-babel-post-tangle-hook nil)
(add-hook 'org-babel-post-tangle-hook
          (lambda () (ess-load-file (buffer-file-name))))

then tangle

x <- 10
y <- 9
y <- 9

colnames to specific variables

onetwothee
123
threetwoone
321
return nospec
onetwothee
threetwoone
321

caption on code block

SELECT 6*9;

palendromic primes

Note that because Haskell is funny about what can be typed into the interpreter, the following should be loaded with org-babel-load-in-session.
palendromic_primes = [x | x <- [1..], prime x, palendrome x]
    where
      factors n = [x | x <- [1..floor(sqrt(fromIntegral(n)))], n `mod` x == 0]
      prime n = factors n == [1]
      primes = [x | x <- [2..], prime x]
      palendrome n = show(n) == reverse(show(n))

palendromic_prime_distances = map (\(x,y)-> y-x) neighbors
    where
      neighbors = (zip palendromic_primes (tail palendromic_primes))
take 180 (zip [1..] palendromic_prime_distances)

For high-quality png output from gnuplot, the following sequence of graphing to a .eps file, and then converting to a .png can be useful.

set term postscript landscape color enhanced
set log y
set title "distance between consecutive palendromic primes"
plot "$data" with fs notitle

The convert command is part of the imagemagick suite.

convert -depth 300 -rotate 90 $input pps.png
echo "pps.png"

input from an example block

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut
enimad minim veniam, quis nostrud exercitation ullamco laboris nisi
ut aliquip ex ea commodo consequat. Duis aute irure dolor in
reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
pariatur. Excepteur sint occaecat cupidatat non proident, sunt in
culpa qui officia deserunt mollit anim id est laborum.
(message "%d words in Lorem" (length (split-string lorem)))
68 words in Lorem
1
2
3
4
lst
1

fixing result insertion

needs to replace the results when there is a new hash

normal results

date
Mon Jul 12 22:18:16 PDT 2010

unnamed source block results

(+ 1 2 3 4)

#+name[16a776d6d139e1d39e99d736536a546df115c2dc]:

10
(list '(1 2 3) '(4 5 6))

#+name[53f489ed6977857b9945d79d06e575b2cbbebf11]:

123
456

named source block results

(sleep-for 2)
(list '(1 2 3) '(4 5 8))
(+ 1 2 3 4 8)

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enimad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

#+name[d053f6643d9dc52a0e804c15f2a762da73a00a07]: something

18

#+name[5fac69648ab749ef9ee88ea65b3d49d93f3f6cc8]: something-w-table

123
458

example w/o source name

delete emacs-lisp below for errors

(* (+ 1 1 1) (+ 1 1 1) (+ 1 1 1) (+ 1 1 1) (+ 1 1 1) (+ 1 1 1) (+ 1 1 1))

limited precision

EffectDFnDFdSSnSSdFpp<.05pes
Days9153166235.12250176151101.03861530318.70269793263838.99534541600196e-21*0.52384550792003
(mapcar
 (lambda (row)
   (mapcar
    (lambda (cell) (if (numberp cell) (format "%.4f" cell) cell))
    row))
 tab)

#+name[16ac354f1e7a65594bb59e252ab221e6a4b10f80]:

EffectDFnDFdSSnSSdFpp<.05pes
Days9.0000153.0000166235.1225151101.038618.70278.99534541600196e-21*0.5238

export blocks w/o languages

should raise an error

source

;; this is a comment
(+ 1 1 1)

broken source

(+ 2 2 2)

example

this is exampled
# this is the first
[1, 2, 3, 4, 5].map{|r| r+1}

scratch

and now for src_emacs-lisp{87} an inline block

looking at paths

(buffer-file-name)

dot

digraph data_relationships {
  "data_requirement" [shape=Mrecord, label="{DataRequirement|description\lformat\l}"]
  "data_product" [shape=Mrecord, label="{DataProduct|name\lversion\lpoc\lformat\l}"]
  "data_requirement" -> "data_product"
}

models.png

Tom found a bug

(list 1 (+ 2 3))
15

python errors

[1, [2], 3, 4]
1(2)34
[1, 2, 3, 4, 6].map{|n| puts n}
1
2
3
4
6
print 9
one
1
"something"
[1] "something"
1
2
3
4
[1] 1
[1] 2
[1] 3
[1] 4
print "8\n";
print "9\n";
8
9
(+ 8 7)
15
(println "eric")
nil
8
8
printf("eric schulte\n");
eric schulte
echo 78
78

tangle R and load

z <- 0
x <- 8
y <- 9
x+y+z

table comment issue

save me!

  #+TBLNAME: AutresFPNVE
  #+ATTR_LaTeX: align=lrrrrr
,  |   |                                          | Montant total (\EUR) | Taux amort (\%) | Part pro. (\%) | Déduc (\%) | NVE (\EUR) |
,  |---+------------------------------------------+----------------------+-----------------+----------------+------------+------------|
,  |   | Documentation et formation               |                51.05 |                 |                |            |       0.00 |
,  |   | Communications GSM                       |               831.16 |             100 |             25 |        100 |     207.79 |
,  |   | Internet (Dommel)                        |               167.88 |             100 |             33 |        100 |      55.40 |
,  |   | Fournitures à amortir (ordinateur + GSM) |               762.51 |              33 |             80 |        100 |     201.30 |
,  |   | Restaurant                               |               304.70 |             100 |            100 |         69 |     210.24 |
,  |---+------------------------------------------+----------------------+-----------------+----------------+------------+------------|
,  |   | Total                                    |                      |                 |                |            |    1062.02 |
,  | ^ |                                          |                      |                 |                |            |      Total |
  #+TBLFM: $7=$3*$4*$5*$6/1000000;%.2f::@2$3=51.05::@3$3=9.00+184.88+51.22+201.82+45.67+69.03+62.93+54.16+38.87+39.77+36.35+37.46::@4$3=12*13.99::@6$3=146.50+158.20;%.2f::@7$7=vsum(@-I..@-II);%.2f
#+tblname: example
| 1 | 2 |

latex literals in export

./composite-pattern.png

captions

AB
12

booktabs

numAbbrev.
1Jan.
2Feb.
3Mar.

complex

wget --quiet -qO- "http://ogdi.cloudapp.net/v1/dc/RecreationParks?format=json"
(mapcar
  (lambda (lis) (mapcar (lambda (key) (cdr (assoc key lis))) keys))
  (cdr (car (with-temp-buffer
              (insert data) (goto-char (point-min))
              (json-read)))))
data.map{|f| [f[0], 2.59 * f[1]]}
plot(parkData)
title(main="Park size by Ward")

parks.png

table-label

1
2
3

haskell issues

length [1, 2]
2
1
2
3
4
5
6
7
length this
7

possible prefixes

prefixremaining characters
ob-5
org-b-2
orgb-3
org-bbl-0
bbl-4
babel-2
(-
 ;; length w/o .el
 (- 13 (length ".el"))
 ;; length of prefix
 (length prefix))

hlines in python

abc
def
ghi
return tab

protecting block bodies

neither of these work as expected
#+TITLE: stuff

#+begin_src emacs-lisp
,  (message "something")
#+end_src

,more stuffs

#+resname: something
,: value

,# and a comment
* example org

,# this is a comment
,this is not a comment
* escaped org-mode markup

,this should be exported as is
#+results: escaping-example
,: 24
#comment

final

multiple evals for refs

(setq counter 0)
0
(setq counter (+ 1 counter))
counter
counter_val
3

tangling

date
echo $USER
(message "BAM")
1+8

cache on export

do we export cached blocks

#+name[06ed73c6d8d022cf9c323d92af885952865add17]:

Thu Jun 17 07:35:19 PDT 2010

foo org

Figure \ref{fig:one} (p. \pageref{fig:one}) is produced by the following code
plot(x, y)
abline(out1)

Note that x, y, and out1 are remembered from the preceding code chunk. We don’t have to regenerate them. All code chunks are part of one R “session”. and more stuff here and then the results

fig1.pdf

comments not commented

  1. a source block inside of an enumerate
    (message "don't eat me")
        

can cause problems

  1. how about this one…

don’t eat me!

  1. a source block inside of an enumerate
    I’m hungryI’m hungry
    I’m hungryI’m hungry
    I’m hungryI’m hungry
    (message "don't eat me")
        

    can cause problems

  2. source blocks should be able to be on adjacent lines

simple reference

123
456
789
data
5

exporting with call lines

(def binary-operators '(\+ \- \* \/))
(def unary-operators '(\s))
(defn rpn-to-alg [chars stack]
  (if (> (.size chars) 0)
    (let [el (first chars)]
      (if (some #{el} binary-operators)
        (rpn-to-alg (rest chars)
                    (cons
                     (apply str "(" (or (second stack) 1) " " el " " (or (first stack) 1) ")")
                     (rest (rest stack))))
        (if (some #{el} unary-operators)
          (rpn-to-alg (rest chars)
                      (cons
                       (apply str "(" el " " (or (first stack) 1) ")")
                       (rest (rest stack))))
          (rpn-to-alg (rest chars) (cons el stack)))))
    (first stack)))
(println (apply str (rpn-to-alg (seq alg) '())))
73*x11/+4/++51xxx13*y/++6y5*6/6-+xx+*

can’t open indented results

\begin{preview}
\ovalbox{
\begin{tikzpicture}
\node{$n$}
  child {
    node{$\left(\frac{n}{2}\right)^2$}
      child{
        node{$\left(\frac{n}{4}\right)^2$}
        node{$\left(\frac{n}{4}\right)^2$}
      }
    }
  child{
    node{$\left(\frac{n}{2}\right)^2$}
    child{
      node{$\left(\frac{n}{4}\right)^2$}
      node{$\left(\frac{n}{4}\right)^2$}
    }
  };
\end{tikzpicture}
}
\end{preview}

recursion.pdf

indented source-code blocks and indented results

;; (list (list (current-time-string)))
(current-time-string)
  
123
123
Thu Jun 10 14:13:21 2010
Thu Jun 10 14:13:21 2010
: Thu Jun 10 14:13:21 2010
: Thu Jun 10 14:13:21 2010
: Thu Jun 10 14:13:21 2010
nil
nil
Thu Jun 10 14:11:22 2010
Thu Jun 10 14:11:20 2010
nil
nil
Thu Jun 10 14:06:04 2010
Thu Jun 10 14:06:03 2010
Thu Jun 10 14:05:51 2010
Thu Jun 10 14:05:57 2010
Thu Jun 10 14:06:00 2010

not expand inlines in examples

src_emacs-lisp{(+ 1 2 3)}
src_emacs-lisp{(+ 1 2 3)}

src_emacs-lisp{(+ 1 2 3)}

src_emacs-lisp{(+ 1 2 3)}

indented source names

(message "i am indented")
i am indented
(length output)
13
eric

updating results “in-situ”

update me in place please -- Mon Jun  7 16:44:44 2010
update me in place please -- Mon Jun  7 16:44:43 2010
update me in place please -- Mon Jun  7 16:44:42 2010
update me in place please -- Mon Jun  7 16:44:37 2010
update me in place please -- Mon Jun  7 16:42:14 2010
update me in place please (at the bottom) -- Mon Jun  7 16:44:59 2010
update me in place please (at the bottom) -- Mon Jun  7 16:45:00 2010
update me in place please (at the bottom) -- Mon Jun  7 16:45:02 2010

the results should be above the block

(format "update me in place please -- %s"
        (current-time-string))
(format "update me in place please (at the bottom) -- %s"
        (current-time-string))

inhibiting evaluation on export

executing emacs-lisp on export

(error "eric")

stripping existing results

I shouldn't be exported

Neither of the result strings for the following two code blocks should be included in the export. And only one of the bodies should be included…

(+ 1 1 1 1)
don't include me in the export!!!!!!!

export with existing results

12
34

/tmp/eric.png

non-empty comint prompt

8 + 9

unwind-protect with narrowing

I’m not in the subtree

I’m in the subtree

(+ 6 "I'm not a number!!")

commas on tangling test

test comma protection on tangling
(org-babel-add-interpreter "org")
(add-to-list 'org-babel-tangle-langs '("org" "org"))
* org-mode
,  :PROPERTIES:
,  :CUSTOM_ID: comma-protect
,  :END:

#+begin_src emacs-lisp
,  protected?
#+end_src
* this should be
# commented out

and maybe not this...

simple table

'((1 2 3) (4 5 6) (7 8 900))
123
456
78900

inline expressions

x<-4

the sum of 1 and x is equal to src_R{x+1}, now I’ll sneakily reset this value in a hidden inline block src_R[:exports none]{x<-2}, so it’s value is now src_R{x}.

adding file names to literal values on export

9

appending tangle

append all these block
(message "block %d" 1)
(message "block %d" 2)
(message "block %d" 3)

visibility affecting execution

folding

lets test folding

folded

(message "folded1")
folded1
(message "folded2")
folded2

unfolded

(message "unfolded1")
unfolded1
(message "unfolded2")
unfolded2

empty code blocks – and latex vs. LaTeX

eric
  

michael

  

schulte

(message "error")

colnames

abc
def
ghi
return [[val + '*' for val in row] for row in tab]
abc
d*e*f*
g*h*i*
abc
def
ghi
tab.map{|r| r.map{|e| e+"*"} }
abc
d*e*f*
g*h*i*

lisps not fully eval’d

(message "one")
(message "two")
two
(println "one")
(println "two")
(+ 1 2)
3

tangling org

* first
,| eric   | me     |
,| patton | my dog |

* second

,some more stuff...

#+HTML: <b>I bet this is quoted</b>
# this is a comment
eric.map{|l| puts l}

colnames mismatched sizes

ab
18
29
310
411
return [[1, 2, 3]]
123
return [[1, 2]]
ab
12
return [1,2]
12

variable indexing

XY
00
11
24
39
416
525
Sum55
01491625
55
:results silent :exports none
  reset
  set label "Sum: %.0f",sum at graph 0.03, graph 0.93
  plot data with linespoints

hline processing

abc
def
ghi
1
2
3
123
(message "%S" tab)
;; (remove 'hline tab)
;; (flet ((rem-hline (el)
;;                   (if (listp el)
;;                       (remove nil (mapcar #'rem-hline el))
;;                     (if (equal 'hline el) nil el))))
;;   (rem-hline tab))
tab
1
2
3
1 + 2
3
return tab
1
2
3
tab
1
2
3
(message "%S" tab)
(("" "c1" "c2" "c3") hline ("r1" 1 4 7) ("r2" 2 5 8) ("r3" 3 6 9))
c1c2c3
r1147
r2258
r3369

functions

(defun org-babel-del-hlines (table)
  "Remove all 'hlines from TABLE."
  (remove 'hline table))

(defun org-babel-get-colnames (table)
  "Return a cons cell, the `car' of which contains the TABLE
      less colnames, and the `cdr' of which contains a list of the
      column names"
  (if (equal 'hline (second table))
      (cons (cddr table) (car table))
    table))
  
(defun org-babel-get-rownames (table)
  "Return a cons cell, the `car' of which contains the TABLE less
   colnames, and the `cdr' of which contains a list of the column
   names.  Note: this function removes any hlines in TABLE"
  (flet ((trans (table) (apply #'mapcar* #'list table)))
    (let ((table (trans (remove 'hline table))))
      (cons (cdr table) (car table)))))

(defun org-babel-put-colnames (table colnames)
  "Add COLNAMES to TABLE if they exist."
  (if colnames (apply 'list colnames 'hline table) table))

(defun org-babel-put-rownames (table rownames)
  "Add ROWNAMES to TABLE if they exist."
  (if rownames
      (mapcar (lambda (row)
                (if (listp row)
                    (cons (or (pop rownames) "") row)
                  row)) table)
    table))

test gnuplot

plot sin(x), x+5

evaluate references

(message "var is %S" var)
(+ 1 2)
3
+ 1 2
nil

tangling and variable resolution

(concat "This is the entry ID: " id)
This is the entry ID: 18b4f1be-bb1d-49bc-a651-c97406a35bdd

latex attributes

+---------------------------+
|                           |
|       latex               |
|                           |
|      +------------+       |
|      |            |       |
|      |            |       |
|      |       cBLU |       |
|      +------------+       |
|                      cPNK |
+---------------------------+

access to variables set in property drawers

"(org-entry-get nil "special" t)"
(+ special 1)
90
special  
schulte

variables into shell scripts

usernameguest
passwordnothing
echo "$username -p $password"
username -p nothing
9
for i in `seq $num`; do
    echo $i
done
1
2
3
4
5
6
7
8
9

results lines for function calls

8
(message "fib(5)=%d" fib)
fib(5)=8

haskell variables

playing with Haskell

9
num + 1
num + 1
10

list index w/function style name

0
1
2
3
4
5
6
7
8
9
(message "%S" data)
((1) (2) (3) (4))

looking at source name exports

(defun fib (n)
  (if (> n 1)
      (+ (fib (- n 1)) (fib (- n 2)))
      1))
(fib input)
1

now applying our Fibonacci function

short shell test

date
Sun Feb  7 10:17:44 MST 2010
11
21
32
43
55
68
echo "$table" |wc
6      12      24
echo "$table"
11
21
32
43
55
68
echo "$table" | head -1
1--1

tables to shell scripts ideas

HelloWorld
  1. allowing the user to specify a separator with a header argument as follows
    cat <<EOF
    $table
    EOF
        

    which would result in something like

    "Hello, World"
        
  2. writing the table to a tab or comma separated file and then replacing $table in the source block body with the path to the file name, s.t. something like
    wc $table
        

    would return reasonable results

tangling w/o comments and shebang

(message "I should have no comments")
(setq my-shebang "foo")
foo
puts :nonstandard_shebang

exporting to a file

this is the contents

and a block

(println "is a nice lisp")

ah, it works!

ditaa blocks

-------------

#+name[4fbfc78b37abd8a788958d28a7335445e6042c96]: communication.png

babel block overwrite

The first block overwrites

(def overwriter "I'll show up everywhere")

this second block

3719d3718
<       movl    $1024, 8(%esp)

load to session

(in-ns 'asm-gp)
puts :eric
5 + 1 
6 + 1
date
eric
plot sin(x)

links

can LaTeX link itself to the middle of a paragraph with a simple inline link like <<keystone>> if not then we would probably need to wrap source-code blocks in figures to make them referable.

how about a link back to keystone

The above appears to work in LaTeX, but not in HTML.

fancier export

(* input input)

exporting org-source

,lets see how this org-mode code exports to html

,is this [[link]] blue?

#+begin_src emacs-lisp
,  (+ 1 2)
#+end_src

exporting and caching

data/example.png

no noweb by default

(message "sample")
<<sample>>
sample

looking at double quotes

testthis89
return data
testthis89

quoted session name

echo 'name-me'
name-me

eval-buffer

(+ 1 2)
3
(+ 3 4)
7

gnuplot variable expansion

"sin(x)"
plot $fun

debug hints

from mailing list
  • edebug-defun: (in emacs-lisp mode, C-u C-M-x) will mark the function so that when it is called, the interpreter stops and you can then single-step through it with <SPACE>. At each point, you can press “e” and evaluate variables (actually arbitrary expressions).
  • Insert a strategically placed (debug) call and then call the function. If/when the debug call is executed, you are dropped into the debugger and you can then evaluate arbitrary expressions.

sql exports to latex

example from email list

ECM

  • faire un script Bash (et isql) envoyant un listing de stagiaires;
DECLARE @dateFmtStyleIn int; SET @dateFmtStyleIn = 120 -- ODBC canonical
DECLARE @dateFmtStyleOut int; SET @dateFmtStyleOut = 103 -- French dd/mm/yyyy

DECLARE @firstDayOfThisMonth smalldatetime
SET @firstDayOfThisMonth = CONVERT(smalldatetime,
                                   CAST(YEAR(GETDATE()) AS char(4)) + '-'
                                   + CAST(MONTH(GETDATE()) AS char(2)) + '-'
                                   + '01' + ' 00:00:00',
                                   @dateFmtStyleIn)

DECLARE @now smalldatetime
SET @now = CONVERT(smalldatetime,
                   CAST(YEAR(GETDATE()) AS char(4)) + '-'
                   + CAST(MONTH(GETDATE()) AS char(2)) + '-'
                   + CAST(DAY(GETDATE()) AS char(2)) + ' '
                   + CAST(DATEPART(hh, GETDATE()) AS char(2)) + ':'
                   + CAST(DATEPART(mi, GETDATE()) AS char(2)) + ':'
                   + '00',
                   @dateFmtStyleIn)

SELECT pfiID
FROM dossier

whitespace/newline results issues

echo output

This

echo output

text here

results in

t#+results:

output

ext here

(+ 1 1)
2

sh with sessions

cd ~/Desktop
cd ~/Desktop/clj/
ls *.clj
“ants.clj”””“concurrent.clj”””“hello.clj”””“spell-checker.clj”

testing srcname aliases

2
(+ input 1)

#+name[1ec6c8d3de6aaeac7b2720f1d801402e762875ea]:

3

hiding results

(mapcar (lambda (el) (list el)) (number-sequence 0 20))
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

elisp references

(setq first 10)
(eval (intern name))
return a + 10

elisp variables

+-----------+
|           |
|           |
|           |
|           |
+-----------+

45.png

haskell and tables

sumListCond :: Int -> Int -> [Int] -> Int
sumListCond l n xs
    | foldl (+) 0 (take l xs) <= n = sumListCond (l + 1) n xs
    | otherwise = foldl (+) 0 (take (l - 1) xs)
  

latex pngs

$x \mapsto y$

Theorem

$|consts(t)| \leq sizes(t)$
  • by induction on the structure of t
  • base cases are $t ∈ [true, false, 0]$:
    • $|consts(t)| = |[t]| = 1 = size(t)$
  • inductive size
    • $t ∈ [succ(t_1), pred(t_1), iszero(t_1)]$:
      • $|consts(t)| = |consts(t_1)| = |[t]| \leq size(t_1) < size(t)$
    • $t = if\, t_1 \, then \, t_2 \, else t_3$
      • $|consts(t)| = |consts(t_1) ∪ consts(t_1) ∪ consts(t_1)|$
      • $\leq |consts(t_1)| + |consts(t_1)| + |consts(t_1)|$
      • $\leq size(t_1) + size(t_1) + size(t_1)$
      • $< size(t)$

indexing into gnuplot

11
24
39
416
525
636
plot data using 1:2 with lines
11
24
39
416
525
636
2191
plot data using 1:2 with lines

multiple arguments

(+ first second)
19

indexing into results

eric
michael
schulte
is
my
name
data
schulte
is
my
12
34
56
78
910
data
12
34
56
78

cached results

(setq org-babel-default-header-args '((:session . "none")
                                      (:results . "replace")
                                      (:exports . "code")(:cache)))

#+name[937269632ae5b5eee5c93f9eb50e0bc55e34520d]:

(:session . none)(:results . replace)(:exports . code)(:cache)
(+ 5 7 1)

#+name[005b04829608b3d22b61686e90309af3a9a6fe7c]: eric-schulte

13
+--------------------+
|                    |     +-----------+
|                    |     |           |
|                    |     |           |
|      +----+        |     |           |
|      |    |        |     +-----------+
|      +----+        |
|                    |
+--------------------+

#+name[fd11ddbfd00f6038e6e37db71ddaf43d65b0e200]: caching-example.png

switches and references

class Schulte
  def self.eric
    puts :imp # (ref:imp)
  end
end
Schulte.eric

#+resname[bb4cebabe38a5d3d43835acebdbe17aa3314cef6]:

imp

Line no. (imp) is important!

class Schulte
  def self.eric
    puts :imp # (ref:imp)
  end
end
Schulte.eric # (ref:output)
imp

unresolved noweb references

(setq org-babel-noweb-error-langs '("ruby"))
1 + 2
<<i-have-a-name>> + 3
6

clojure

(list 8 9)

reference parts of tables

11
24
39
416
525
636
749
864
981
10100
11121
12144
13169
14196
15225
16256
17289
18324
set title "Implementing Gnuplot"
plot data using 1:2 with lines

results switches

10.times do |n|
  puts "-"*n
end
-
--
---
----
-----
------
-------
--------
---------
10.times do |n|
  puts "-"*n
end
-
--
---
----
-----
------
-------
--------
---------

xml and n3

introduce org-babel to xml and n3

(add-to-list 'org-babel-interpreters "xml")
(add-to-list 'org-babel-interpreters "n3")

inform org-babel-tangle of their existence and file extensions

(add-to-list 'org-babel-tangle-langs '("xml" "xml"))
(add-to-list 'org-babel-tangle-langs '("n3" "n3"))
<first>
</first>
n3 stuff

noweb referernces

a = 28
# <<noweb-example>>
a + 4
32

pp results

python

['one', 'two', 'three', 'one', 'two', 'three', 'one', 'two', 'three']
['one', 'two', 'three', 'one', 'two', 'three', 'one', 'two', 'three']

ruby

class Schulte
  attr_accessor :name, :age
end

eric = Schulte.new
eric.name = "eric"
eric.age = 27

eric
a = [1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]
a
[1,
 2,
 3,
 1,
 2,
 3,
 1,
 2,
 3,
 1,
 2,
 3,
 1,
 2,
 3,
 1,
 2,
 3,
 1,
 2,
 3,
 1,
 2,
 3,
 1,
 2,
 3]

empty output results for emacs-lisp

8

:table results param

8
8

code results

emacs lisp

(mapcar (lambda (el) (lambda (item) (+ item el))) '(1 2 3 4 5))
((lambda
   (item)
   (+ item el))
 (lambda
   (item)
   (+ item el))
 (lambda
   (item)
   (+ item el))
 (lambda
   (item)
   (+ item el))
 (lambda
   (item)
   (+ item el)))
(mapcar (lambda (el) (* el el)) '(1 2 3 89))
(1 4 9 7921)

ruby

[1, 2, 33, 4].map{|n| "the number #{n}"}
["the number 1", "the number 2", "the number 33", "the number 4"]
[1, 2, 33, 4].map{|n| n + 10 }
[11, 12, 43, 14]

python

['one', 'two', 'three']
['one', 'two', 'three']
[1, 2, 33, 4]
[1, 2, 33, 4]
[1, 2, 33, 4]
[1, 2, 33, 4]

indentation

9

persistent python

import types
types.FunctionType
function

more persistent python

import types
types.FunctionType
function

quoted latex

The following latex isn’t exported correctly

data BTree = Leaf a
           | Node Tree Tree

pretty print

'(1 2 3 4)

simple scalar

(+ 1 3)
4

lua export

local s1, s2 = intersecting_segs[1], intersecting_segs[2]
local n1 = table_find_segment(cell.neighbors, s1)
local n2 = table_find_segment(cell.neighbors, s2)

I got:

\lstset{language=lua}
\begin{lstlisting}
local s1, s2 = intersecting_segs[1], intersecting_segs[2]
local n1 = table_find_segment(cell.neighbors, s1)
local n2 = table_find_segment(cell.neighbors, s2)
\end{lstlisting}

Emacs -Q got:

\begin{verbatim}
local s1, s2 = intersecting_segs[1], intersecting_segs[2]
local n1 = table_find_segment(cell.neighbors, s1)
local n2 = table_find_segment(cell.neighbors, s2)
\end{verbatim}

Emacs -Q + Org-babel got:

\begin{verbatim}
local s1, s2 = intersecting_segs[1], intersecting_segs[2]
local n1 = table_find_segment(cell.neighbors, s1)
local n2 = table_find_segment(cell.neighbors, s2)
\end{verbatim}

simple R

8
8

changing source name

8
8
8

advanced table

DATAWHATWHEREHOW MUCH
[2009-09-25 Fri]28.95
foodsupermarket7.85
ticket bus2.3
tea + iceice uno4.4
ticket14.4
[2009-09-26 Sat]41
(let ((total 0) (responding t) purchases)
  (while responding
    (setq purchases
          (cons
           (list ""
                 (read-from-minibuffer "What: ")
                 (read-from-minibuffer "Where: ")
                 (read-minibuffer "How Much: "))
           purchases))
    (setq responding (y-or-n-p "more? ")))
  (append 
   purchases
   (list
    (list
     (format-time-string "%Y-%m-%d" (current-time))
     "" "" (progn
             (mapc (lambda (purchase)
                     (setq total (+ total (fourth purchase))))
                   purchases)
             total)))))
””“fish and chips”“diner”9.78
””“food”“subway”5.45
“2009-09-29”””””15.23

haskell

powerSet :: [a] -> [[a]]
powerSet = foldr (\ x ps -> map (\ y -> x : y) ps ++ ps ) [[]]
powerSet [1, 2, 3]

indented

(message "I ran!!")   
I ran!!

dynamic table

Clock summary at [2009-09-15 Tue 08:51], for Tuesday, September 15, 2009.

LHeadlineTime
Total time1:10
1top1:101
2show all1:00
2later0:10
(message "table is %S" data)
table is (("L" "Headline" "Time" "") hline ("" "*Total time*" "*1:10*" "") hline (1 "[[file:/Users/eschulte/Desktop/test.org::top][top]]" "1:10" 1) (2 "[[file:/Users/eschulte/Desktop/test.org::show%20all][show all]]" "" "1:00") (2 "[[file:/Users/eschulte/Desktop/test.org::later][later]]" "" "0:10"))
pie(times[2:length(times),4], labels = times[2:length(times),2])

show all

+----------------------+
|                      |
|                      |
|          +-----------+
|          |           |
|          |           |
|          |           |
|          +-----------+
|                      |
+----------------------+

later

stuff here

and then more

and more stuffs here

asymptote

import graph;

size(0,4cm);

real f(real t) {return 1+cos(t);}

path g=polargraph(f,0,2pi,operator ..)--cycle;
filldraw(g,pink);

xaxis("$x$",above=true);
yaxis("$y$",above=true);

dot("$(a,0)$",(1,0),N);
dot("$(2a,0)$",(2,0),N+E);

asymptote-test.png

asymptote cosine

import graph;

size(0,4cm);

real f(real t) {return cos(t);}

path g=polargraph(f,0,2pi,operator ..)--cycle;
filldraw(g,pink);

for(int i=0; i < 8; ++i) {
  real j = 0.125 + 0.125*i;
  real h(real t) {return j;};
  path k=polargraph(h, -(acos(j)), acos(j), operator ..);
  draw(k,blue);
}

xaxis("$x$",above=true);
yaxis("$y$",above=true);

dot("$(pi,0)$",(1,0),N);

gnuplot

plot cosx

tools

Map over all scraps and export each to a separate file. Note that this relies on the fontification in the original Org-mode buffer, so before exporting expand the entire buffer, and scroll through from top to bottom so that everything will be fontified.

(defun dump-subtree-to-file ()
  (let* ((replacements '((" "   . "-")
                         ("w/o" . "without")
                         ("w/"  . "with-")
                         ("/"   . "-")
                         ("\""  . "")
                         ("="   . "")
                         ("'"   . "")))
         (full-title (nth 4 (org-heading-components)))
         (title ((lambda (title)
                   (dolist (rep replacements)
                     (setq title (replace-regexp-in-string
                                  (car rep) (cdr rep) title)))
                   (downcase title))
                 full-title))
         (date (org-entry-get (point) "DATE"))
         (path (expand-file-name (concat date "-" title ".html") "scraps"))
         buf)
    (unless (file-exists-p path)
      (call-interactively #'org-copy-subtree)
      (with-temp-buffer
        (call-interactively #'yank) (setq buf (htmlize-buffer)))
      (set-buffer buf)
      (goto-char (point-min))
      (write-file path)
      (kill-buffer))))

(org-id-goto "96eaa17f-f1b6-4958-acb1-e271045fdfa2")
(org-map-entries #'dump-subtree-to-file "+LEVEL=2")

add date properties to all subheadings using the git log

(defun set-date-from-git-log ()
  (org-entry-put (point) "DATE"
   (org-babel-trim
    (shell-command-to-string
     (format
      "git log --date=short --summary -1 %s|grep Date|awk '{print $2}'"
      (git-blame-current-commit))))))

(defun do-date-tree ()
  (org-map-entries #'set-date-from-git-log nil 'tree))