Merge branch 'master' of git@github.com:eschulte/org-babel
[org-mode.git] / org-babel.org
blob93f9805db1f351a918831471f3d161e0f1935762
1 #+TITLE: org-babel --- facilitating communication between programming languages and people
2 #+SEQ_TODO: PROPOSED TODO STARTED | DONE DEFERRED REJECTED
3 #+OPTIONS:    H:3 num:nil toc:2 \n:nil @:t ::t |:t ^:t -:t f:t *:t TeX:t LaTeX:t skip:nil d:(HIDE) tags:not-in-toc
4 #+STARTUP: oddeven hideblocks
6 #+begin_html 
7   <div id="subtitle">
8     <p>executable source code blocks in org-mode</p>
9   </div>
10   <div id="logo">
11     <p>
12       <img src="images/tower-of-babel.png"  alt="images/tower-of-babel.png" />
13       <div id="attr">from <a href="http://www.flickr.com/photos/23379658@N05/" title=""><b>Martijn Streefkerk</b></a></div>
14     </p>  
15   </div>
16 #+end_html
18 Org-Babel makes source-code blocks in Org-Mode executable and allows
19 data to pass seamlessly between different programming languages,
20 Org-Mode constructs (tables, file links, example text) and interactive
21 comint buffers.
23 In this document:
24 - The [[* Introduction][Introduction]] :: provides a brief overview of the design and use
25      of Org-Babel including tutorials and examples.
26 - In [[* Getting started][Getting Started]] :: find instructions for installing org-babel
27      into your emacs configuration.
28 - The [[* Tasks][Tasks]] :: section contains current and past tasks roughly ordered
29      by TODO state, then importance or date-completed.  This would be
30      a good place to suggest ideas for development.
31 - The [[* Bugs][Bugs]] :: section contains bug reports.
32 - The [[* Tests][Tests]] :: section consists of a large table which can be
33      evaluated to run Org-Babel's functional test suite.  This
34      provides a good overview of the current functionality with
35      pointers to example source blocks.
36 - The [[* Sandbox][Sandbox]] :: demonstrates much of the early/basic functionality
37      through commented source-code blocks.
39 Also see the [[file:library-of-babel.org][Library of Babel]], an extensible collection of ready-made
40 and easily-shortcut-callable source-code blocks for handling common
41 tasks.
43 * Introduction
45 Org-Babel enables *communication* between programming languages and
46 between people.
48 Org-Babel provides:
49 - communication between programs :: Data passes seamlessly between
50      different programming languages, Org-Mode constructs (tables,
51      file links, example text) and interactive comint buffers.
52 - communication between people :: Data and calculations are embedded
53      in the same document as notes explanations and reports.
55 ** communication between programs
57 Org-Mode supports embedded blocks of source code (in any language)
58 inside of Org documents.  Org-Babel allows these blocks of code to be
59 executed from within Org-Mode with natural handling of their inputs
60 and outputs.
62 *** simple execution
63 with both scalar, file, and table output
65 *** reading information from tables
67 *** reading information from other source blocks (disk usage in your home directory)
69 This will work for Linux and Mac users, not so sure about shell
70 commands for windows users.
72 To run place the cursor on the =#+begin_src= line of the source block
73 labeled directory-pie and press =\C-c\C-c=.
75 #+srcname: directories
76 #+begin_src bash :results replace
77 cd ~ && du -sc * |grep -v total
78 #+end_src
80 #+resname: directories
81 |       64 | "Desktop"   |
82 | 11882808 | "Documents" |
83 |  8210024 | "Downloads" |
84 |   879800 | "Library"   |
85 |    57344 | "Movies"    |
86 |  7590248 | "Music"     |
87 |  5307664 | "Pictures"  |
88 |        0 | "Public"    |
89 |      152 | "Sites"     |
90 |        8 | "System"    |
91 |       56 | "bin"       |
92 |  3274848 | "mail"      |
93 |  5282032 | "src"       |
94 |     1264 | "tools"     |
96 #+srcname: directory-pie
97 #+begin_src R :var dirs = directories :session R-pie-example
98 pie(dirs[,1], labels = dirs[,2])
99 #+end_src
106 *** operations in/on tables
108 #+tblname: grades-table
109 | student | grade | letter |
110 |---------+-------+--------|
111 |       1 |    99 | A      |
112 |       2 |    59 | F      |
113 |       3 |    75 | C      |
114 |       4 |    15 | F      |
115 |       5 |     7 | F      |
116 |       6 |    13 | F      |
117 #+TBLFM: $2='(sbe random-score-generator)::$3='(sbe assign-grade (score $2))
119 #+srcname: assign-grade
120 #+begin_src ruby :var score=99
121 case score
122    when 0..59: "F"
123    when 60..69: "D"
124    when 70..79: "C"
125    when 80..89: "B"
126    when 90..100: "A"
127    else "Invalid Score"
129 #+end_src
131 #+srcname: random-score-generator
132 #+begin_src ruby 
133 rand(100)
134 #+end_src
136 #+srcname: show-distribution
137 #+begin_src R :var grades=grades-table :session *R*
138 hist(grades$grade)
139 #+end_src
145 ** communication between people
146 Quick overview of Org-Mode's exportation abilities, with links to the
147 online Org-Mode documentation, a focus on source-code blocks, and the
148 exportation options provided by Org-Babel.
150 *** Interactive tutorial
151 This would demonstrate applicability to Reproducible Research, and
152 Literate Programming.
154 *** Tests embedded in documentation
155 org-babels own functional tests are contained in a large org-mode
156 table, allowing the test suite to be run be evaluation of the table
157 and the results to be collected in the same table.
159 *** Emacs initialization files stored in Org-Mode buffers
160 Using `org-babel-tangle' it is possible to embed your Emacs
161 initialization into org-mode files.  This allows for folding,
162 note-taking, todo's etc... embedded with the source-code of your Emacs
163 initialization, and through org-mode's publishing features aids in
164 sharing your customizations with others.
166 It may be worthwhile to create a fork of Phil Hagelberg's
167 [[http://github.com/technomancy/emacs-starter-kit/tree/master][emacs-starter-kit]] which uses literate org-mode files for all of the
168 actual elisp customization.  These org-mode files could then be
169 exported to html and used to populate the repositories wiki on [[http://github.com/][github]].
172 ** features
174 *** code evaluation (comint buffer sessions and external processes)
175 There are two main ways to evaluate source blocks with org-babel.
177 - external :: By default (if the =:session= header argument is not
178               present) all source code blocks are evaluated in
179               external processes.  In these cases an external process
180               is used to evaluate the source-code blocks.
181 - session :: Session based evaluation uses persistent sessions in
182              comint buffers.  Sessions can be used across multiple
183              source blocks setting and accessing variables in the
184              global environment.
186              Evaluating source blocks in sessions also allows for
187              interaction with the code.  To jump to the session of a
188              source block use the `org-babel-pop-to-session' command
189              or press =M-[down]= while inside of a source code block.
190              When called with a prefix argument
191              `org-babel-pop-to-session' will evaluate all header
192              arguments before jumping to the source-code block.
194 *** results (values and outputs)
195 Either the *value* or the *output* of source code blocks can be
196 collected after evaluation.
198 - value :: The default way to collect results from a source-code block
199            is to return the value of the last statement in the block.
200            This can be thought of as the return value of the block.
201            In this case any printed output of the block is ignored.
202            This can be though of a similar to a "functional" value of
203            evaluation.
204 - output :: Another way of generating results from a source-code block
205             is to collect the output generated by the execution of the
206             block.  In this case all printed output is collected
207             throughout the execution of the block.  This can be
208             thought of as similar to a "script" style of evaluation.
211 * Getting started
212 Add the following lines to your .emacs, replacing the path as
213 appropriate. A good place to check that things are up and running
214 would then be [[#sandbox][the sandbox]].
215 #+begin_src emacs-lisp
216   (add-to-list 'load-path "/path/to/org-babel/lisp")
217   (require 'org-babel-init)
218 #+end_src
220   
221 * Tasks [43/63]
222 ** TODO source-name visible in LaTeX and html exports
223 Maybe this should be done in backend specific manners.
225 The listings package may provide for naming a source-code block...
227 ** PROPOSED allow `anonymous' function block with function call args?
228    My question here is simply whether we're going to allow
229 #+begin_src python(arg=ref)
230 # whatever
231 #+end_src
233 but with preference given to
234 #+srcname blockname(arg=ref)
235 ** PROPOSED allow :result as synonym for :results?
236 ** PROPOSED allow 'output mode to return stdout as value?
237    Maybe we should allow this. In fact, if block x is called
238    with :results output, and it references blocks y and z, then
239    shouldn't the output of x contain a concatenation of the outputs of
240    y and z, together with x's own output? That would raise the
241    question of what happens if y is defined with :results output and z
242    with :results value. I guess z's (possibly vector/tabular) output
243    would be inside a literal example block containing the whole lot.
244 ** PROPOSED optional timestamp for output
245    Add option to place an (inactive) timestamp at the #+resname, to
246    record when that output was generated.
248 *** source code block timestamps (optional addition)
249     [Eric] If we did this would we then want to place a timestamp on the
250     source-code block, so that we would know if the results are
251     current or out of date?  This would have the effect of caching the
252     results of calculations and then only re-running if the
253     source-code has changed.  For the caching to work we would need to
254     check not only the timestamp on a source-code block, but also the
255     timestamps of any tables or source-code blocks referenced by the
256     original source-code block.
258     [Dan] I do remember getting frustrated by Sweave always having to
259     re-do everything, so this could be desirable, as long as it's easy
260     to over-ride of course. I'm not sure it should be the default
261     behaviour unless we are very confident that it works well.
263 **** maintaining source-code block timestamps
264      It may make sense to add a hook to `org-edit-special' which could
265      update the source-code blocks timestamp.  If the user edits the
266      contents of a source-code block directly I can think of no
267      efficient way of maintaining the timestamp.
268 ** TODO make tangle files read-only?
269    With a file-local variable setting, yea that makes sense.  Maybe
270    the header should reference the related org-mode file.
272 ** TODO support for working with =*Org Edit Src Example*= buffers [4/6]
273 *** STARTED Patch against org source. 
274     I've worked on several related changes to source code edit buffer
275     behaviour in the org core.  My current patch (below) does the
276     following. Detailed explanation / working notes are below.
277     - C-x s offers to save edit buffers
278     - C-x C-c offers to save edit buffers
279     - C-x k warns that you're killing an edit buffer
280     - If you do kill an edit buffer, the overlay in the parent buffer is removed
281     - Edit buffers are named *Org Src <orgbuf>[<lang>]*, where
282       <orgbuf> is the name of the org-mode buffer containing this
283       source code block, and lang is the language major mode. The
284       latter might be unnecessary?
286 #+begin_example 
287 diff --git a/lisp/org-src.el b/lisp/org-src.el
288 index 2083c77..2be21e6 100644
289 --- a/lisp/org-src.el
290 +++ b/lisp/org-src.el
291 @@ -113,7 +113,7 @@ but which mess up the display of a snippet in Org exported files.")
293  (defvar org-src-mode-map (make-sparse-keymap))
294  (define-key org-src-mode-map "\C-c'" 'org-edit-src-exit)
295 -(define-key org-src-mode-map "\C-x\C-s" 'org-edit-src-save)
296 +;; (define-key org-src-mode-map "\C-x\C-s" 'org-edit-src-save)
297  (defvar org-edit-src-force-single-line nil)
298  (defvar org-edit-src-from-org-mode nil)
299  (defvar org-edit-src-picture nil)
300 @@ -168,7 +168,8 @@ the edited version."
301             (if (boundp 'org-edit-src-overlay)
302                 (org-delete-overlay org-edit-src-overlay)))
303           (kill-buffer buffer))
304 -       (setq buffer (generate-new-buffer "*Org Edit Src Example*"))
305 +       (setq buffer (generate-new-buffer
306 +                     (concat "*Org Src " (file-name-nondirectory buffer-file-name) "[" lang "]*")))
307         (setq ovl (org-make-overlay beg end))
308         (org-overlay-put ovl 'face 'secondary-selection)
309         (org-overlay-put ovl 'edit-buffer buffer)
310 @@ -186,8 +187,7 @@ the edited version."
311                                 '(display nil invisible nil intangible nil))
312         (org-do-remove-indentation)
313         (let ((org-inhibit-startup t))
314 -         (funcall lang-f)
315 -         (org-src-mode))
316 +         (funcall lang-f))
317         (set (make-local-variable 'org-edit-src-force-single-line) single)
318         (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
319         (when lfmt
320 @@ -201,6 +201,7 @@ the edited version."
321         (org-set-local 'org-edit-src-end-marker end)
322         (org-set-local 'org-edit-src-overlay ovl)
323         (org-set-local 'org-edit-src-nindent nindent)
324 +       (org-src-mode)
325         (and org-edit-src-persistent-message
326              (org-set-local 'header-line-format msg)))
327        (message "%s" msg)
328 @@ -400,12 +401,13 @@ the language, a switch telling of the content should be in a single line."
329  (defun org-edit-src-exit ()
330    "Exit special edit and protect problematic lines."
331    (interactive)
332 -  (unless (string-match "\\`*Org Edit " (buffer-name (current-buffer)))
333 -    (error "This is not an sub-editing buffer, something is wrong..."))
334 +  (unless org-edit-src-from-org-mode
335 +    (error "This is not a sub-editing buffer, something is wrong..."))
336    (let ((beg org-edit-src-beg-marker)
337         (end org-edit-src-end-marker)
338         (ovl org-edit-src-overlay)
339         (buffer (current-buffer))
340 +       (buffer-file-name nil)
341         (nindent org-edit-src-nindent)
342         code line)
343      (untabify (point-min) (point-max))
344 @@ -464,6 +466,17 @@ the language, a switch telling of the content should be in a single line."
345      (goto-char (min p (point-max)))
346      (message (or msg ""))))
348 +(defun org-src-mode-configure-buffer ()
349 +  (setq buffer-offer-save t)
350 +  (setq buffer-file-name
351 +       (concat (buffer-file-name (marker-buffer org-edit-src-beg-marker))
352 +               "[" (buffer-name) "]"))
353 +  (setq write-contents-functions '(org-edit-src-save))
354 +  (org-add-hook 'kill-buffer-hook
355 +               '(lambda () (org-delete-overlay org-edit-src-overlay)) nil 'local))
357 +(org-add-hook 'org-src-mode-hook 'org-src-mode-configure-buffer)
359  (provide 'org-src)
361  ;; arch-tag: 6a1fc84f-dec7-47be-a416-64be56bea5d8
362       
363 #+end_example
365 **** Detailed working notes to go with that patch
366 ***** Recap of current org-src-mode
367       
368       If you use C-c ' to work on code in a begin_source block, the code
369       buffer is put in minor mode org-src-mode, which features the
370       following two useful key-bindings:
372       | C-x s | org-edit-src-save | save the code in the source code block in the parent org file |
373       | C-c ' | org-edit-src-exit | return to the parent org file with new code                   |
375       Furthermore, while the edit buffer is alive, the originating code
376       block is subject to a special overlay which links to the edit
377       buffer when you click on it.
379       This is all excellent, and I use it daily, but I think there's
380       still a couple of improvements that we should make.
382 ***** Proposed bug I
383       C-x k kills the buffer without questions; the overlay remains, but
384       now links to a deleted buffer.
385 ***** Proposed bug II
386       C-x C-c kills a modified edit buffer silently, without offering to
387       save your work. I have lost work like that a number of times
388       recently.
389 ***** Proposed bug III
390       C-x s does not offer to save a modified edit buffer
391 ***** Notes on solution
392 ****** write-contents-functions
393        A good start seems to be to use org-src-mode-hook to add
394        org-edit-src-save to the write-contents-functions list. This
395        means that when it comes to saving, org-edit-src-save will be
396        called and no subsequent attempt will be made to save the buffer
397        in the normal way. (This should obviate the remapping of C-x C-s
398        to org-edit-src-save in org-src.el)
399 ****** buffer-offer-save
400        We also want to set this to t.
402 ****** Where does this get us?
404        - C-x s still does *not* offer to save the edit buffer. That's
405          because buffer-file-name is nil.
406        
407        - C-x C-c does ask us whether we want to save the
408          edit buffer. However, since buffer-file-name is nil it asks us
409          for a file name. The check in org-edit-src-exit throws an error
410          unless the buffer is named '* Org Edit '...
412        - C-x k kills the buffer silently, leaving a broken overlay
413          link. If buffer-file-name were set, it would have warned that
414          the buffer was modified.
416 ****** buffer-file-name
417        So, that all suggests that we need to set buffer-file-name, even
418        though we don't really want to associate this buffer with a file
419        in the normal way. As for the file name, my current suggestion
420        is parent-org-filename[edit-buffer-name].
421        
422        [I had to move the (org-src-mode) call to the end of
423        org-edit-src-code to make sure that the required variables were
424        defined when the hook was called.]
425        
426 ****** And so where are we now?
427        - C-x s *does* offer to save the edit buffer, but in saving
428          produces a warning that the edit buffer is modified.
429        - C-x k now gives a warning that the edit buffer is modified
430          (even if it's not).
431        - C-x C-c is working as desired, except that again we get
432          warnings that the edit buffer is modified, once when we save,
433          and again just before exiting emacs.
434        - And C-c ' now issues a warning that the edit buffer is
435          modified when we leave it, which we don't want.
436 ****** So, we need to get rid of the buffer modification warnings.
437        I've made buffer-file-name nil inside the let binding in
438        org-edit-src-exit.
439 ****** And?
440        - C-x s behaves as desired, except that as was already the case,
441          the edit buffer is always considered modified, and so repeated
442          invocations keep saving it.
443        - As was already the case, C-x k always gives a warning that the
444          edit buffer has been modified.
445        - C-x C-c is as desired (offers to save the edit buffer) except
446          that it warns of the modified buffer just before exiting.
447        - C-c ' is as it should be (silent)
448 ***** Conclusion
449       We've got the desired behaviour, at the cost of being forced to
450       assign a buffer-file-name to the edit buffer. The consequence is
451       that the edit buffer is considered to always be modified, since
452       a file of that name is never actually written to (doesn't even
453       exist). I couldn't see a way to trick emacs into believing that
454       the buffer was unmodified since last save. But in any case, I
455       think there's an argument that these modifications warnings are
456       a good thing, because one should not leave active edit buffers
457       around: you should always have exited with C-c ' first.
459 *** DONE name edit buffer according to #+srcname (and language?)
460     See above patch agains org.
461 *** DONE optionally evaluate header references when we switch to =*Org Edit Src*= buffer
462 That seems to imply that the header references need to be evaluated
463 and transformed into the target language object when we hit C-c ' to
464 enter the *Org Edit Src* buffer [DED]
466 Good point, I heartily agree that this should be supported [Eric]
468 (or at least before the first time we attempt to evaluate code in that
469 buffer -- I suppose there might be an argument for lazy evaluation, in
470 case someone hits C-c ' but is "just looking" and not actually
471 evaluating anything.) Of course if evaluating the reference is
472 computationally intensive then the user might have to wait before they
473 get the *Org Edit Src* buffer. [DED]
475 I fear that it may be hard to anticipate when the references will be
476 needed, some major-modes do on-the-fly evaluation while the buffer is
477 being edited.  I think that we should either do this before the buffer
478 is opened or not at all, specifically I think we should resolve
479 references if the user calls C-c ' with a prefix argument.  Does that
480 sound reasonable? [Eric]
482 Yes [Dan]
484 [Dan] So now that we have org-src-mode and org-src-mode-hook, I guess
485 org-babel should do this by using the hook to make sure that, when C-c
486 C-' is issued on a source block, any references are resolved and
487 assignments are made in the appropriate session.
489 #+tblname: my-little-table
490 | 1 | 2 |
491 | 3 | 4 |
493 #+srcname: resolve-vars-on-edit
494 #+begin_src ruby :var table=my-little-table :results silent :session test
495   table.size.times.do |n|
496     puts n
497   end
498 #+end_src
501 *** TODO set buffer-local-process variables appropriately [DED]
502     I think something like this would be great. You've probably
503 already thought of this, but just to note it down: it would be really
504 nice if org-babel's notion of a buffer's 'session/process' played
505 nicely with ESS's notion of the buffer's session/process. ESS keeps
506 the current process name for a buffer in a buffer-local variable
507 ess-local-process-name. So one thing we will probably want to do is
508 make sure that the *Org Edit Src Example* buffer sets that variable
509 appropriately. [DED]
511 I had not thought of that, but I agree whole heartedly. [Eric]
513 Once this is done every variable should be able to dump regions into
514 their inferior-process buffer using major-mode functions.
515 *** REJECTED send code to inferior process
516 Another thought on this topic: I think we will want users to send
517 chunks of code to the interpreter from within the *Org Edit Src*
518 buffer, and I think that's what you have in mind already. In ESS that
519 is done using the ess-eval-* functions. [DED]
521 I think we can leave this up to the major-mode in the source code
522 buffer, as almost every source-code major mode will have functions for
523 doing things like sending regions to the inferior process.  If
524 anything we might need to set the value of the buffer local inferior
525 process variable. [Eric]
527 *** DONE some possible requests/proposed changes for Carsten [4/4]
528     While I remember, some possible requests/proposed changes for Carsten
529     come to mind in that regard:
531 **** DONE Remap C-x C-s to save the source to the org buffer?
532      I've done this personally and I find it essential. I'm using 
533 #+begin_src emacs-lisp
534 (defun org-edit-src-save ()
535   "Update the parent org buffer with the edited source code, save
536 the parent org-buffer, and return to the source code edit
537 buffer."
538   (interactive)
539   (let ((p (point)))
540     (org-edit-src-exit)
541     (save-buffer)
542     (org-edit-src-code)
543     (goto-char p)))
545 (define-key org-exit-edit-mode-map "\C-x\C-s" 'org-edit-src-save)
546 #+end_src     
547     which seems to work.
549 I think this is great, but I think it should be implemented in the
550 org-mode core
552 **** DEFERRED Rename buffer and minor mode?
553      Something shorter than *Org Edit Src Example* for the buffer
554      name. org-babel is bringing org's source code interaction to a
555      level of maturity where the 'example' is no longer
556      appropriate. And if further keybindings are going to be added to
557      the minor mode then maybe org-edit-src-mode is a better name than
558      org-exit-edit-mode.
560      Maybe we should name the buffer with a combination of the source
561      code and the session.  I think that makes sense.
563      [ES] Are you also suggesting a new org-edit-src minor mode?
564      [DED] org-exit-edit-mode is a minor mode that already exists:
566      Minor mode installing a single key binding, "C-c '" to exit special edit.
568      org-edit-src-save now has a binding in that mode, so I guess all
569      I'm saying at this stage is that it's a bit of a misnomer. But
570      perhaps we will also have more functionality to add to that minor
571      mode, making it even more of a misnomer. Perhaps something like
572      org-src-mode would be better.
573 **** DONE Changed minor mode name and added hooks
574      
575 **** DONE a hook called when the src edit buffer is created
576      This should be implemented in the org-mode core
577 ** TODO resolve references to other org buffers/files
578    This would allow source blocks to call upon tables, source-blocks,
579    and results in other org buffers/files.
580    
581    See...
582    - [[file:lisp/org-babel-ref.el::TODO%20allow%20searching%20for%20names%20in%20other%20buffers][org-babel-ref.el:searching-in-other-buffers]]
583    - [[file:lisp/org-babel.el::defun%20org-babel%20find%20named%20result%20name][org-babel.el#org-babel-find-named-result]]
584 ** TODO resolve references to other non-org files
585    - tabular data in .csv, .tsv etc format
586    - files of interpreted code: anything stopping us giving such files
587      similar status to a source code block?
588    - Would be nice to allow org and non-org files to be remote
589 ** TODO figure out how to handle errors during evaluation
590    I expect it will be hard to do this properly, but ultimately it
591    would be nice to be able to specify somewhere to receive STDERR,
592    and to be warned if it is non-empty.
594    Probably simpler in non-session evaluation than session? At least
595    the mechanism will be different I guess.
597    R has a try function, with error handling, along the lines of
598    python. I bet ruby does too. Maybe more of an issue for functional
599    style; in my proposed scripting style the error just gets dumped to
600    the org buffer and the user is thus alerted.
601 ** STARTED figure out how to handle graphic output
602    
603 This is listed under [[* graphical output][graphical output]] in out objectives.
605 This should take advantage of the =:results file= option, and
606 languages which almost always produce graphical output should set
607 =:results file= to true by default (this is currently done for the
608 gnuplot and ditaa languages).  That would handle placing these results
609 in the buffer.  Then if there is a combination of =silent= and =file=
610 =:results= headers we could drop the results to a temp buffer and pop
611 open that buffer...
613 Display of file results is addressed in the [[* =\C-c \C-o= to open results of source block][open-results-task]].
615 *** TODO R graphics to screen means session evaluation
616     If R graphical output is going to screen then evaluation must be
617     in a session, otherwise the graphics will disappear as soon as the
618     R process dies.
620 *** Adding to a discussion started in email
621     I'm not deeply wedded to these ideas, just noting them down. I'm
622     probably just thinking of R and haven't really thought about how
623     this fits with the other graphics-generating languages.
624 Dan:
625 > I used the approach below to get graphical file output
626 > today, which is one idea at least. Maybe it could be linked up with
627 > your :results file variable. (Or do we need a :results image for R?)
629 Eric:
630 I don't think we need a special image results variable, but I may be
631 missing what the code below accomplishes.  Would the task I added about
632 adding org-open-at-point functionality to source code blocks take care
633 of this need?
635 Dan: I'm not sure. I think the ability for a script to generate both
636 text and graphical output might be a natural expectation, at least for
637 R users.
640 > Dan
642 > #+srcname: cohort-scatter-plots-2d(org_babel_graphical_output_file="cohort-scatter-plots-2d.png")
643 > #+begin_src R 
644 >   if(exists("org_babel_output_file"))
645 >       png(filename=org_babel_graphical_output_file, width=1000, height=1000)
646 >   ## plotting code in here
647 >   if(exists("org_babel_graphical_output_file")) dev.off()
648 > #+end_src
650 Dan: Yes, the results :file option is nice for dealing with graphical
651 output, and that could well be enough. Something based on the scheme
652 above would have a couple of points in its favour:
653 1. It's easy to switch between output going to on-screen graphics and
654    output going to file: Output will go to screen unless a string variable
655    with a standard name (e.g. ""org_babel_graphical_output_file"")
656    exists in which case it will go to the file indicated by the value
657    of that variable.
658 2. The block can return a result / script output, as well as produce
659    graphical output.
661 In interactive use we might want to allow the user to choose between
662 screen and file output. In non-interactive use such as export, it
663 would be file output (subject to the :exports directives).
664 ** TODO Finalise behaviour regarding vector/scalar output
665 *** DONE Stop spaces causing vector output
666 This simple example of multilingual chaining produces vector output if
667 there are spaces in the message and scalar otherwise.
669 [Not any more]
671 #+srcname: msg-from-R(msg=msg-from-python)
672 #+begin_src R
673 paste(msg, "und R", sep=" ")
674 #+end_src
676 #+resname:
677 : org-babel speaks elisp y python und R
679 #+srcname: msg-from-python(msg=msg-from-elisp)
680 #+begin_src python
681 msg + " y python"
682 #+end_src
684 #+srcname: msg-from-elisp(msg="org-babel speaks")
685 #+begin_src emacs-lisp
686 (concat msg " elisp")
687 #+end_src
688 ** STARTED share org-babel [1/6]
689 how should we share org-babel?
690 *** DONE post to org-mode
691 *** TODO post to ess mailing list
692 *** TODO create a org-babel page on worg
693 *** TODO create a short screencast demonstrating org-babel in action
694 *** PROPOSED a peer-reviewed publication?
696     The following notes are biased towards statistics-oriented
697     journals because ESS and Sweave are written by people associated
698     with / in statistics departments. But I am sure there are suitable
699     journals out there for an article on using org mode for
700     reproducible research (and literate programming etc).
702     Clearly, we would invite Carsten to be involved with this.
704      ESS is described in a peer-reviewed journal article:
705      Emacs Speaks Statistics: A Multiplatform, Multipackage Development Environment for Statistical Analysis  [Abstract]
706      Journal of Computational & Graphical Statistics 13(1), 247-261
707      Rossini, A.J, Heiberger, R.M., Sparapani, R.A., Maechler, M., Hornik, K. (2004) 
708      [[http://www.amstat.org/publications/jcgs.cfm][Journal of Computational and Graphical Statistics]]
710      Also [[http://www.amstat.org/publications/jss.cfm][Journal of Statistical Software]] Established in 1996, the
711      Journal of Statistical Software publishes articles, book reviews,
712      code snippets, and software reviews. The contents are freely
713      available online. For both articles and code snippets, the source
714      code is published along with the paper.
716     Sweave has a paper: 
718     Friedrich Leisch and Anthony J. Rossini. Reproducible statistical
719     research. Chance, 16(2):46-50, 2003. [ bib ]
721     also
723     Friedrich Leisch. Sweave: Dynamic generation of statistical reports
724     using literate data analysis. In Wolfgang Härdle and Bernd Rönz,
725     editors, Compstat 2002 - Proceedings in Computational Statistics,
726     pages 575-580. Physica Verlag, Heidelberg, 2002. ISBN 3-7908-1517-9.
728     also
730     We could also look at the Journals publishing these [[http://www.reproducibleresearch.net/index.php/RR_links#Articles_about_RR_.28chronologically.29][Reproducible
731     Research articles]].
732     
733 *** PROPOSED an article in [[http://journal.r-project.org/][The R Journal]]
734 This looks good.  It seems that their main topic to software tools for
735 use by R programmers, and Org-babel is certainly that.
737 *** existing similar tools
738 try to collect pointers to similar tools 
740 Reproducible Research
741 - [[http://en.wikipedia.org/wiki/Sweave][Sweave]]
743 Literate Programming
744 - [[http://www.cs.tufts.edu/~nr/noweb/][Noweb]]
745 - [[http://www-cs-faculty.stanford.edu/~knuth/cweb.html][Cweb]]
746 - [[http://www.lri.fr/~filliatr/ocamlweb/][OCamlWeb]]
748 Meta Functional Programming
749 - ?
751 Programmable Spreadsheet
752 - ?
754 *** examples
755 we need to think up some good examples
757 **** interactive tutorials
758 This could be a place to use [[* org-babel assertions][org-babel assertions]].
760 for example the first step of a tutorial could assert that the version
761 of the software-package (or whatever) is equal to some value, then
762 source-code blocks could be used with confidence (and executed
763 directly from) the rest of the tutorial.
765 **** answering a text-book question w/code example
766 org-babel is an ideal environment enabling both the development and
767 demonstrationg of the code snippets required as answers to many
768 text-book questions.
770 **** something using tables
771 maybe something along the lines of calculations from collected grades
773 **** file sizes
774 Maybe something like the following which outputs sizes of directories
775 under the home directory, and then instead of the trivial =emacs-lisp=
776 block we could use an R block to create a nice pie chart of the
777 results.
779 #+srcname: sizes
780 #+begin_src bash :results replace
781 du -sc ~/*
782 #+end_src
784 #+begin_src emacs-lisp :var sizes=sizes :results replace
785 (mapcar #'car sizes)
786 #+end_src
787 ** TODO command line execution
788 Allow source code blocks to be called form the command line.  This
789 will be easy using the =sbe= function in [[file:lisp/org-babel-table.el][org-babel-table.el]].
791 This will rely upon [[* resolve references to other buffers][resolve references to other buffers]].
793 ** TODO inline source code blocks [3/5]
794    Like the =\R{ code }= blocks
796    not sure what the format should be, maybe just something simple
797    like =src_lang[]{}= where lang is the name of the source code
798    language to be evaluated, =[]= is optional and contains any header
799    arguments and ={}= contains the code.
801    (see [[* (sandbox) inline source blocks][the-sandbox]])
803 *** DONE evaluation with \C-c\C-c
804 Putting aside the header argument issue for now we can just run these
805 with the following default header arguments
806 - =:results= :: silent
807 - =:exports= :: results
809 *** DONE inline exportation
810 Need to add an interblock hook (or some such) through org-exp-blocks
811 *** DONE header arguments
812 We should make it possible to use header arguments.
814 *** TODO fontification
815 we should color these blocks differently
817 *** TODO refine html exportation
818 should use a span class, and should show original source in tool-tip
819 ** TODO LoB: re-implement plotting and analysis functions from org-R
820    I'll do this soon, now that we things are a bit more settled and we
821    have column names in R.
822 ** PROPOSED Creating presentations
823    The [[mairix:t:@@9854.1246500519@gamaville.dokosmarshall.org][recent thread]] containing posts by Nick Dokos and Sebastian
824    Vaubán on exporting to beamer looked very interesting, but I
825    haven't had time to try it out yet. I would really like it if,
826    eventually, we can generate a presentation (with graphics generated
827    by code blocks) from the same org file that contains all the notes
828    and code etc. I just wanted that to be on record in this document;
829    I don't have anything more profound to say about it at the moment,
830    and I'm not sure to what extent it is an org-babel issue.
831 ** PROPOSED conversion between org-babel and noweb (e.g. .Rnw) format
832    I haven't thought about this properly. Just noting it down. What
833    Sweave uses is called "R noweb" (.Rnw).
834    
835    I found a good description of noweb in the following article (see
836    the [[http://www.cs.tufts.edu/~nr/pubs/lpsimp.pdf][pdf]]).
837    
838    I think there are two parts to noweb, the construction of
839    documentation and the extraction of source-code (with notangle).
841    *documentation*: org-mode handles all of our documentation needs in
842    a manner that I believe is superior to noweb.
843    
844    *source extraction* At this point I don't see anyone writing large
845    applications with 100% of the source code contained in org-babel
846    files, rather I see org-babel files containing things like
847    - notes with active code chunks
848    - interactive tutorials
849    - requirements documents with code running test suites
850    - and of course experimental reports with the code to run the
851      experiment, and perform analysis
853    Basically I think the scope of the programs written in org-babel
854    (at least initially) will be small enough that it wont require the
855    addition of a tangle type program to extract all of the source code
856    into a running application.
858    On the other hand, since we already have named blocks of source
859    code which reference other blocks on which they rely, this
860    shouldn't be too hard to implement either on our own, or possibly
861    relying on something like noweb/notangle.
863 ** PROPOSED support for passing paths to files between source blocks
864 Maybe this should be it's own result type (in addition to scalars and
865 vectors).  The reason being that some source-code blocks (for example
866 ditaa or anything that results in the creation of a file) may want to
867 pass a file path back to org-mode which could then be inserted into
868 the org-mode buffer as a link to the file...
870 This would allow for display of images upon export providing
871 functionality similar to =org-exp-blocks= only in a more general
872 manner.
873 ** DEFERRED Support rownames and other org babel table features?
875    The full org table features are detailed in the manual [[http://orgmode.org/manual/Advanced-features.html#Advanced-features][here]].
877 *** rownames
878    Perhaps add a :rownames header arg. This would be an integer
879     (usually 1) which would have the effect of post-processing all the
880     variables created in the R session in the following way: if the
881     integer is j, set the row names to the contents of column j and
882     delete column j. Perhaps it is artificial to allow this integer to
883     take any value other than 1. The default would be nil which would
884     mean no such behaviour.
886     Actually I don't know about that. If multiple variables are passed
887     in, it's not appropriate to alter them all in the same way. The
888     rownames specification would normally refer to just one of the
889     variables. For now maybe just say this has to be done in R. E.g.
891 #+TBLNAME: sample-sizes
892   | collection      | size | exclude | include | exclude2 | include2 |
893   |-----------------+------+---------+---------+----------+----------|
894   | 58C             | 2936 |       8 |    2928 |      256 |     2680 |
895   | MS              | 5852 |     771 |    5081 |      771 |     5081 |
896   | NBS             | 2929 |      64 |    2865 |      402 |     2527 |
897   | POBI            | 2717 |       1 |    2716 |        1 |     2716 |
898   | 58C+MS+NBS+POBI |      |         |   13590 |          |    13004 |
899 #+TBLFM: @2$4=@2$2 - @2$3::@2$6=@2$2 - @2$5::@3$4=@3$2-@3$3::@3$6=@3$2 - @3$5::@4$4=@4$2 - @4$3::@4$6=@4$2 - @4$5::@5$4=@5$2-@5$3::@5$6=@5$2 - @5$5::@6$4=vsum(@2$4..@5$4)::@6$6=vsum(@2$6..@5$6)
901 #+srcname: make-size-table(size=sample-sizes)
902 #+begin_src R 
903   rownames(size) <- size[,1]
904   size <- size[,-1]
905 #+end_src
908 *** Old notes
909     [I don't think it's as problematic as this makes out]
910     This is non-trivial, but may be worth doing, in particular to
911     develop a nice framework for sending data to/from R.
912 **** Notes
913     In R, indexing vector elements, and rows and columns, using
914     strings rather than integers is an important part of the
915     language.
916  - elements of a vector may have names
917  - matrices and data.frames may have "column names" and "row names"
918    which can be used for indexing
919  - In a data frame, row names *must* be unique
920 Examples
921 #+begin_example
922 > # a named vector
923 > vec <- c(a=1, b=2)
924 > vec["b"]
927 > mat <- matrix(1:4, nrow=2, ncol=2, dimnames=list(c("r1","r2"), c("c1","c2")))
928 > mat
929    c1 c2
930 r1  1  3
931 r2  2  4
932 > # The names are separate from the data: they do not interfere with operations on the data
933 > mat * 3
934    c1 c2
935 r1  3  9
936 r2  6 12
937 > mat["r1","c2"]
938 [1] 3
939 > df <- data.frame(var1=1:26, var2=26:1, row.names=letters)
940 > df$var2
941  [1] 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10  9  8  7  6  5  4  3  2  1
942 > df["g",]
943   var1 var2
944 g    7   20
945 #+end_example
947  So it's tempting to try to provide support for this in org-babel. For example
948  - allow R to refer to columns of a :var reference by their names
949  - When appropriate, results from R appear in the org buffer with "named
950    columns (and rows)"
952    However none (?) of the other languages we are currently supporting
953    really have a native matrix type, let alone "column names" or "row
954    names". Names are used in e.g. python and perl to refer to entries
955    in dicts / hashes.
957    It currently seems to me that support for this in org-babel would
958    require setting rules about when org tables are considered to have
959    named columns/fields, and ensuring that (a) languages with a notion
960    of named columns/fields use them appropriately and (b) languages
961    with no such notion do not treat then as data.
963  - Org allows something that *looks* like column names to be separated
964    by a hline
965  - Org also allows a row to *function* as column names when special
966    markers are placed in the first column. An hline is unnecessary
967    (indeed hlines are purely cosmetic in org [correct?]
968  - Org does not have a notion of "row names" [correct?]
969     
970    The full org table functionality exeplified [[http://orgmode.org/manual/Advanced-features.html#Advanced-features][here]] has features that
971    we would not support in e.g. R (like names for the row below).
972    
973 **** Initial statement: allow tables with hline to be passed as args into R
974    This doesn't seem to work at the moment (example below). It would
975    also be nice to have a natural way for the column names of the org
976    table to become the column names of the R data frame, and to have
977    the option to specify that the first column is to be used as row
978    names in R (these must be unique). But this might require a bit of
979    thinking about.
982 #+TBLNAME: egtable
983 | col1 | col2    | col3 |
984 |------+---------+------|
985 |    1 | 2       |    3 |
986 |    4 | schulte |    6 |
988 #+TBLNAME: egtable2
989 | 1 |         2 | 3 |
990 | 4 | schulte   | 6 |
992 #+begin_src R :var tabel=egtable :colnames t
993 tabel
994 #+end_src
996 #+resname:
997 | "col1" | "col2"    | "col3" |
998 |--------+-----------+--------|
999 |      1 | 2         |      3 |
1000 |      4 | "schulte" |      6 |
1003 Another example is in the [[*operations%20in%20on%20tables][grades example]].
1004 ** DEFERRED use textConnection to pass tsv to R?
1005    When passing args from the org buffer to R, the following route is
1006    used: arg in buffer -> elisp -> tsv on file -> data frame in R. I
1007    think it would be possible to avoid having to write to file by
1008    constructing an R expression in org-babel-R-assign-elisp, something
1009    like this
1011 #+begin_src emacs-lisp
1012 (org-babel-R-input-command
1013  (format  "%s <- read.table(textConnection(\"%s\"), sep=\"\\t\", as.is=TRUE)"
1014           name (orgtbl-to-tsv value '(:sep "\t" :fmt org-babel-R-quote-tsv-field))))
1015 #+end_src
1017    I haven't tried to implement this yet as it's basically just
1018    fiddling with something that works. The only reason for it I can
1019    think of would be efficiency and I haven't tested that.
1021    This Didn't work after an initial test.  I still think this is a
1022    good idea (I also think we should try to do something similar when
1023    writing out results frmo R to elisp) however as it wouldn't result
1024    in any functional changes I'm bumping it down to deferred for
1025    now. [Eric]
1027 for quick tests
1029 #+tblname: quick-test
1030 | 1 | 2 | 3 |
1032 #+srcname: quick-test-src-blk
1033 #+begin_src R :var vec=quick-test
1034 mean(mean(vec))
1035 #+end_src
1037 #+resname:
1038 : 2
1041 : 2
1043 ** DEFERRED Rework Interaction with Running Processes [2/5]
1044 *** DONE robust to errors interrupting execution
1046 #+srcname: long-runner-ruby
1047 #+begin_src ruby :results silent
1048   sleep(10)
1049   :patton_is_an_grumpy
1050 #+end_src
1052 *** DEFERRED use =C-g= keyboard-quit to push processing into the background
1053 This may be possible using the `run-with-timer' command.
1055 I have no idea how this could work...
1057 #+srcname: long-runner-ruby
1058 #+begin_src ruby :results silent
1059   sleep(10)
1060   :patton_is_an_grumpy
1061 #+end_src
1063 *** TODO ability to select which of multiple sessions is being used
1064     Increasingly it is looking like we're going to want to run all
1065     source code blocks in comint buffer (sessions).  Which will have
1066     the benefits of
1067     1) allowing background execution
1068     2) maintaining state between source-blocks
1069        - allowing inline blocks w/o header arguments 
1071 **** R sessions
1072      (like ess-switch-process in .R buffers)
1073      
1074      Maybe this could be packaged into a header argument, something
1075      like =:R_session= which could accept either the name of the
1076      session to use, or the string =prompt=, in which case we could use
1077      the =ess-switch-process= command to select a new process.
1078      
1079 *** TODO evaluation of shell code as background process? 
1080     After C-c C-c on an R code block, the process may appear to
1081     block, but C-g can be used to reclaim control of the .org buffer,
1082     without interrupting the R evalution. However I believe this is not
1083     true of bash/sh evaluation. [Haven't tried other languages] Perhaps
1084     a solution is just to background the individual shell commands.
1086     The other languages (aside from emacs lisp) are run through the
1087     shell, so if we find a shell solution it should work for them as
1088     well.
1089     
1090     Adding an ampersand seems to be a supported way to run commands in
1091     the background (see [[http://www.emacswiki.org/emacs/ExecuteExternalCommand#toc4][external-commands]]).  Although a more extensible
1092     solution may involve the use of the [[elisp:(progn (describe-function 'call-process-region) nil)][call-process-region]] function.
1093     
1094     Going to try this out in a new file [[file:lisp/org-babel-proc.el][org-babel-proc.el]].  This should
1095     contain functions for asynchronously running generic shell commands
1096     in the background, and then returning their input.
1098 **** partial update of org-mode buffer
1099     The sleekest solution to this may be using a comint buffer, and
1100     then defining a filter function which would incrementally interpret
1101     the results as they are returned, including insertion into the
1102     org-mode buffer.  This may actually cause more problems than it is
1103     worth, what with the complexities of identifying the types of
1104     incrementally returned results, and the need for maintenance of a
1105     process marker in the org buffer.
1107 **** 'working' spinner
1108      It may be nice and not too difficult to place a spinner on/near the
1109      evaluating source code block
1111 *** TODO conversion of output from interactive shell, R (and python) sessions to org-babel buffers
1112     [DED] This would be a nice feature I think. Although an org-babel
1113     purist would say that it's working the wrong way round... After
1114     some interactive work in a *R* buffer, you save the buffer, maybe
1115     edit out some lines, and then convert it to org-babel format for
1116     posterity. Same for a shell session either in a *shell* buffer, or
1117     pasted from another terminal emulator. And python of course.
1118 ** DEFERRED improve the source-block snippet
1119 any real improvement seems somewhat beyond the ability of yasnippet
1120 for now.
1122 [[file:~/src/emacs-starter-kit/src/snippets/text-mode/rst-mode/chap::name%20Chapter%20title][file:~/src/emacs-starter-kit/src/snippets/text-mode/rst-mode/chap::name Chapter title]]
1123 #+begin_example
1124 ,#name : Chapter title
1125 ,# --
1126 ${1:Chapter}
1127 ${1:$(make-string (string-width text) ?\=)}
1130 #+end_example
1132 [[file:snippets/org-mode/sb][sb -- snippet]]
1134 waiting for guidance from those more familiar with yasnippets
1136 ** REJECTED re-implement R evaluation using ess-command or ess-execute
1137    I don't have any complaints with the current R evaluation code or
1138    behaviour, but I think it would be good to use the ESS functions
1139    from a political point of view. Plus of course it has the normal
1140    benefits of an API (insulates us from any underlying changes etc). [DED]
1142    I'll look into this.  I believe that I looked at and rejected these
1143    functions initially but now I can't remember why.  I agree with
1144    your overall point about using API's where available.  I will take
1145    a look back at these and either switch to using the ess commands,
1146    or at least articulate under this TODO the reasons for using our
1147    custom R-interaction commands. [Eric]
1149    ess-execute
1151    Lets just replace =org-babel-R-input-command= with =ess-execute=.
1153    I tried this, and although it works in some situations, I find that
1154    =ess-command= will often just hang indefinitely without returning
1155    results.  Also =ess-execute= will occasionally hang, and pops up
1156    the buffer containing the results of the command's execution, which
1157    is undesirable.  For now these functions can not be used.  Maybe
1158    someone more familiar with the ESS code can recommend proper usage
1159    of =ess-command= or some other lower-level function which could be
1160    used in place of [[file:lisp/org-babel-R.el::defun%20org-babel%20R%20input%20command%20command][org-babel-R-input-command]].
1162 *** ess functions
1163    
1164 #+begin_quote ess-command
1165 (ess-command COM &optional BUF SLEEP NO-PROMPT-CHECK)
1167 Send the ESS process command COM and delete the output
1168 from the ESS process buffer.  If an optional second argument BUF exists
1169 save the output in that buffer. BUF is erased before use.
1170 COM should have a terminating newline.
1171 Guarantees that the value of .Last.value will be preserved.
1172 When optional third arg SLEEP is non-nil, `(sleep-for (* a SLEEP))'
1173 will be used in a few places where `a' is proportional to `ess-cmd-delay'.
1174 #+end_quote
1176 #+begin_quote ess-execute
1177 (ess-execute COMMAND &optional INVERT BUFF MESSAGE)
1179 Send a command to the ESS process.
1180 A newline is automatically added to COMMAND.  Prefix arg (or second arg
1181 INVERT) means invert the meaning of
1182 `ess-execute-in-process-buffer'.  If INVERT is 'buffer, output is
1183 forced to go to the process buffer.  If the output is going to a
1184 buffer, name it *BUFF*.  This buffer is erased before use.  Optional
1185 fourth arg MESSAGE is text to print at the top of the buffer (defaults
1186 to the command if BUFF is not given.)
1187 #+end_quote
1189 *** out current setup
1191     1) The body of the R source code block is wrapped in a function
1192     2) The function is called inside of a =write.table= function call
1193        writing the results to a table
1194     3) The table is read using =org-table-import=
1195 ** DONE new results types (org, html, latex)
1196    Thanks to Tom Short for this recommendation.
1198    - raw or org :: in which case the results are implemented raw, unquoted
1199                    into the org-mode file.  This would also handle links as
1200                    source block output.
1201    - html :: the results are inserted inside of a #+BEGIN_HTML block
1202    - latex :: the results are inserted inside of a #+BEGIN_LATEX block
1204    It might look like:
1205 : #+begin_src R :session *R* :results org
1206 : cat("***** This is a table\n")
1207 : cat("| 1 | 2 | 3 |\n")
1208 : cat("[[http://google.com][Google it here]]\n"
1209 : #+end_src
1210 :        
1211 : #+resname:
1212 : ***** This is a table
1213 : | 1 | 2 | 3 |
1214 [[http://google.com][: Google it here]]
1216 We actually might want to remove the =#+resname= line if the results
1217 type is org-mode, not sure...  Either way I don't think there is a
1218 good way to capture/remove org type results.
1220 *** LaTeX
1221 #+srcname: latex-results
1222 #+begin_src emacs-lisp :results latex
1223 "this should be inside of a LaTeX block"
1224 #+end_src
1226 #+resname:
1227 #+BEGIN_LaTeX
1228 this should be inside of a LaTeX block
1229 #+END_LaTeX
1231 *** Html
1232 #+srcname: html-results
1233 #+begin_src emacs-lisp :results html
1234 "this should be inside of a HTML block
1238 and more
1242 is long"
1243 #+end_src
1245 #+resname:
1246 #+BEGIN_HTML
1247 this should be inside of a HTML block
1251 and more
1255 is long
1256 #+END_HTML
1258 *** raw
1260 Added a =raw= results header argument, which will insert the results
1261 of a source-code block into an org buffer un-escaped.  Also, if the
1262 results look like a table, then the table will be aligned.
1264 #+srcname: raw-table-demonstration
1265 #+begin_src ruby :results output raw
1266   puts "| root | square |"
1267   puts "|---"
1268   10.times do |n|
1269     puts "| #{n} | #{n*n} |"
1270   end
1271 #+end_src
1273 #+resname:
1274 | root | square |
1275 |------+--------|
1276 |    0 |      0 |
1277 |    1 |      1 |
1278 |    2 |      4 |
1279 |    3 |      9 |
1280 |    4 |     16 |
1281 |    5 |     25 |
1282 |    6 |     36 |
1283 |    7 |     49 |
1284 |    8 |     64 |
1285 |    9 |     81 |
1287 Not sure how/if this would work, but it may be desirable.
1288 ** DONE org-bable-tangle: no default extension if one already exists
1289 ** DONE take default values for header args from properties
1290    Use file-wide and subtree wide properties to set default values for
1291    header args.
1292    
1293    [DED] One thing I'm finding when working with R is that an org file
1294    may contain many source blocks, but that I just want to evaluate a
1295    subset of them. Typically this is in order to take up where I left
1296    off: I need to recreate a bunch of variables in the session
1297    environment. I'm thinking maybe we want to use a tag-based
1298    mechanism similar to :export: and :noexport: to control evaluation
1299    on a per-subtree basis.
1301 *** test-header with properties
1302     :PROPERTIES:
1303     :tangle:   yes
1304     :var:      def=8
1305     :END:
1307 Ahh... as is so often the case, just had to wrap
1308 `org-babel-params-from-properties' in a `save-match-data' form.
1310 #+tblname: why-def-props-cause-probs
1311 | 1 | 2 | 3 | 4 |
1313 #+srcname: default-props-implementation
1314 #+begin_src emacs-lisp :tangle no :var my-lis=why-def-props-cause-probs :results silent
1315 (+ (length my-lis) def)
1316 #+end_src
1318 ** DONE new reference syntax *inside* source code blocks
1319 This is from an email discussion on the org-mode mailing list with
1320 Sébastien.  The goal here is to mimic the source-block reference style
1321 of Noweb.  Upon export and/or tangle these references could be
1322 replaced with the actual body of the referenced source-code block.
1324 See the following for an example.
1326 #+srcname: ems-ruby-print-header
1327 #+begin_src ruby 
1328 puts "---------------------------header---------------------------"
1329 #+end_src
1331 #+srcname: emacs-ruby-print-footer
1332 #+begin_src ruby 
1333 puts "---------------------------footer---------------------------"
1334 #+end_src
1336 #+srcname: ems-ruby-print-message
1337 #+begin_src ruby :file ruby-noweb.rb
1338   # <<ems-ruby-print-header>>
1339   puts "                            Ruby                            "
1340   # <<ems-ruby-print-footer>>
1341 #+end_src
1343 Upon export the previous source-code block would result in a file
1344 being generated at =ruby-noweb.rb= with the following contents
1346 : puts "---------------------------header---------------------------"
1347 : puts "                            Ruby                            "
1348 : puts "---------------------------footer---------------------------"
1350 the body of a source-code block with all =<<src-name>>= references
1351 expanded can now be returned by `org-babel-expand-noweb-references'.
1352 This function is now called by default on all source-code blocks on
1353 export.
1355 ** DONE re-work tangling system
1356 Sometimes when tangling a file (e.g. when extracting elisp from a
1357 org-mode file) we want to get nearly every source-code block.
1359 Sometimes we want to only extract those source-code blocks which
1360 reference a indicate that they should be extracted (e.g. traditional
1361 literate programming along the Noweb model)
1363 I'm not sure how we can devise a single simple tangling system that
1364 naturally fits both of these use cases.
1366 *** new setup
1367 the =tangle= header argument will default to =no= meaning source-code
1368 blocks will *not* be exported by default.  In order for a source-code
1369 block to be tangled it needs to have an output file specified.  This
1370 can happen in two ways...
1372 1) a file-wide default output file can be passed to `org-babel-tangle'
1373    which will then be used for all blocks
1374 2) if the value of the =tangle= header argument is anything other than
1375    =no= or =yes= then it is used as the file name
1377 #+srcname: test-new-tangling
1378 #+begin_src emacs-lisp 
1379   (org-babel-load-file "test-tangle.org")
1380   (if (string= test-tangle-advert "use org-babel-tangle for all your emacs initialization files!!")
1381       "succeed"
1382     "fail")
1383 #+end_src
1385 #+resname:
1386 : succeed
1388 ** DONE =\C-c \C-o= to open results of source block
1389 by adding a =defadvice= to =org-open-at-point= we can use the common
1390 =\C-c \C-o= keybinding to open the results of a source-code block.
1391 This would be especially useful for source-code blocks which generate
1392 graphical results and insert a file link as the results in the
1393 org-mode buffer.  (see [[* figure out how to handle graphic output][TODO figure out how to handle graphic output]]).
1394 This could also act reasonably with other results types...
1396 - file :: use org-open-at-point to open the file
1397 - scalar :: open results unquoted in a new buffer
1398 - tabular :: export the table to a new buffer and open that buffer
1400 when called with a prefix argument the block is re-run
1402 #+srcname: task-opening-results-of-blocks
1403 #+begin_src ditaa :results replace :file blue.png :cmdline -r
1404 +---------+
1405 | cBLU    |
1406 |         |
1407 |    +----+
1408 |    |cPNK|
1409 |    |    |
1410 +----+----+
1411 #+end_src
1413 #+resname:
1414 [[file:blue.png][blue.png]]
1416 #+srcname: task-open-vector
1417 #+begin_src emacs-lisp
1418 '((1 2) (3 4))
1419 #+end_src
1421 #+resname:
1422 | 1 | 2 |
1423 | 3 | 4 |
1425 #+srcname: task-open-scalar
1426 #+begin_src ruby :results output
1427   8.times do |n|
1428     puts "row #{n}"
1429   end
1430 #+end_src
1432 #+resname:
1433 : row 0
1434 : row 1
1435 : row 2
1436 : row 3
1437 : row 4
1438 : row 5
1439 : row 6
1440 : row 7
1442 ** DONE Stop spaces causing vector output
1443 This simple example of multilingual chaining produces vector output if
1444 there are spaces in the message and scalar otherwise.
1446 [Not any more]
1448 #+srcname: msg-from-R(msg=msg-from-python)
1449 #+begin_src R
1450 paste(msg, "und R", sep=" ")
1451 #+end_src
1453 #+resname:
1454 : org-babel speaks elisp y python und R
1456 #+srcname: msg-from-python(msg=msg-from-elisp)
1457 #+begin_src python
1458 msg + " y python"
1459 #+end_src
1461 #+srcname: msg-from-elisp(msg="org-babel speaks")
1462 #+begin_src emacs-lisp
1463 (concat msg " elisp")
1464 #+end_src
1466 ** DONE add =:tangle= family of header arguments
1467 values are
1468 - no :: don't include source-code block when tangling
1469 - yes :: do include source-code block when tangling
1471 this is tested in [[file:test-tangle.org::*Emacs%20Lisp%20initialization%20stuff][test-tangle.org]]
1473 ** DONE extensible library of callable source blocks
1474 *** Current design
1475     This is covered by the [[file:library-of-babel.org][Library of Babel]], which will contain
1476     ready-made source blocks designed to carry out useful common tasks.
1477 *** Initial statement [Eric]
1478     Much of the power of org-R seems to be in it's helper functions for
1479     the quick graphing of tables.  Should we try to re-implement these
1480     functions on top of org-babel?
1482     I'm thinking this may be useful both to add features to org-babel-R and
1483     also to potentially suggest extensions of the framework.  For example
1484     one that comes to mind is the ability to treat a source-code block
1485     like a function which accepts arguments and returns results. Actually
1486     this can be it's own TODO (see [[* source blocks as functions][source blocks as functions]]).
1487 *** Objectives [Dan]
1488     - We want to provide convenient off-the-shelf actions
1489       (e.g. plotting data) that make use of our new code evaluation
1490       environment but do not require any actual coding.
1491 *** Initial Design proposal [Dan]
1492     - *Input data* will be specified using the same mechanism as :var
1493       references, thus the input data may come from a table, or
1494       another source block, and it is initially available as an elisp
1495       data structure.
1496     - We introduce a new #+ line, e.g.  #+BABELDO. C-c C-c on that
1497       line will apply an *action* to the referenced data.
1498     - *Actions correspond to source blocks*: our library of available
1499       actions will be a library of org-babel source blocks. Thus the
1500       code for executing an action, and the code for dealing with the
1501       output of the action will be the same code as for executing
1502       source blocks in general
1503     - Optionally, the user can have the relevant source block inserted
1504       into the org buffer after the (say) #+BABELDO line. This will
1505       allow the user to fine tune the action by modifying the code
1506       (especially useful for plots).
1507     - So maybe a #+BABELDO line will have header args
1508       - :data (a reference to a table or source code block)
1509       - :action (or should that be :srcname?) which will be something
1510         like :action pie-chart, referring to a source block which will
1511         be executed with the :data referent passed in using a :var arg.
1512       - :showcode or something controlling whether to show the code
1513       
1514 *** Modification to design
1515     I'm implementing this, at least initially, as a new interpreter
1516     named 'babel', which has an empty body. 'babel' blocks take
1517     a :srcname header arg, and look for the source-code block with
1518     that name. They then execute the referenced block, after first
1519     appending their own header args on to the target block's header
1520     args.
1522     If the target block is in the library of babel (a.o.t. e.g. the
1523     current buffer), then the code in the block will refer to the
1524     input data with a name dictated by convention (e.g. __data__
1525     (something which is syntactically legal in all languages...). Thus
1526     the babel block will use a :var __data__ = whatever header arg to
1527     reference the data to be plotted.
1529 ** DONE Column names in R input/output
1530    This has been implemented: Automatic on input to R; optional in
1531    output. Note that this equates column names with the header row in
1532    an org table; whereas org actually has a mechanism whereby a row
1533    with a '!' in the first field defines column names. I have not
1534    attempted to support these org table mechanisms yet. See [[*Support%20rownames%20and%20other%20org%20babel%20table%20features][this
1535    DEFERRED todo item]].
1536 ** DONE use example block for large amounts of stdout output?
1537    We're currently `examplizing' with : at the beginning of the line,
1538    but should larger amounts of output be in a
1539    \#+begin_example...\#+end_example block? What's the cutoff? > 1
1540    line?  This would be nice as it would allow folding of lengthy
1541    output. Sometimes one will want to see stdout just to check
1542    everything looks OK, and then fold it away.
1544    I'm addressing this in branch 'examplizing-output'.
1545    Yea, that makes sense.  (either that or allow folding of large
1546    blocks escaped with =:=).
1548    Proposed cutoff of 10 lines, we can save this value in a user
1549    customizable variable.
1550 *** DONE add ability to remove such results
1551 ** DONE exclusive =exports= params
1552    
1553 #+srcname: implement-export-exclusivity
1554 #+begin_src ruby 
1555 :this_is_a_test
1556 #+end_src
1558 #+resname:
1559 : :this_is_a_test
1560 ** DONE LoB: allow output in buffer
1561 ** DONE allow default header arguments by language
1562 org-babel-default-header-args:lang-name
1564 An example of when this is useful is for languages which always return
1565 files as their results (e.g. [[*** ditaa][ditaa]], and [[*** gnuplot][gnuplot]]).
1566 ** DONE singe-function tangling and loading elisp from literate org-mode file [3/3]
1568 This function should tangle the org-mode file for elisp, and then call
1569 `load-file' on the resulting tangled file.
1571 #+srcname: test-loading-embedded-emacs-lisp
1572 #+begin_src emacs-lisp :results replace
1573   (setq test-tangle-advert nil)
1574   (setq test-tangle-loading nil)
1575   (setq results (list :before test-tangle-loading test-tangle-advert))
1576   (org-babel-load-file "test-tangle.org")
1577   (setq results (list (list :after test-tangle-loading test-tangle-advert) results))
1578   (delete-file "test-tangle.el")
1579   (reverse results)
1580 #+end_src
1582 #+resname: test-loading-embedded-emacs-lisp
1583 | :before | nil                 | nil                                                              |
1584 | :after  | "org-babel tangles" | "use org-babel-tangle for all your emacs initialization files!!" |
1586 *** DONE add optional language limiter to org-babel-tangle
1587 This should check to see if there is any need to re-export
1589 *** DONE ensure that org-babel-tangle returns the path to the tangled file(s)
1591 #+srcname: test-return-value-of-org-babel-tangle
1592 #+begin_src emacs-lisp :results replace
1593   (mapcar #'file-name-nondirectory (org-babel-tangle-file "test-tangle.org" "emacs-lisp"))
1594 #+end_src
1596 #+resname:
1597 | "test-tangle.el" |
1599 *** DONE only tangle the file if it's actually necessary
1600 ** DONE add a function to jump to a source-block by name
1601    I've had an initial stab at that in org-babel-find-named-block
1602    (library-of-babel branch).
1604    At the same time I introduced org-babel-named-src-block-regexp, to
1605    match src-blocks with srcname.
1607    This is now working with the command
1608    `org-babel-goto-named-source-block', all we need is a good key
1609    binding.
1611 ** DONE add =:none= session argument (for purely functional execution) [4/4]
1612 This would allow source blocks to be run in their own new process
1614 - These blocks could then also be run in the background (since we can
1615   detach and just wait for the process to signal that it has terminated)
1616 - We wouldn't be drowning in session buffers after running the tests
1617 - we can re-use much of the session code to run in a more /functional/
1618   mode
1620 While session provide a lot of cool features, like persistent
1621 environments, [[* DONE function to bring up inferior-process buffer][pop-to-session]], and hints at exportation for
1622 org-babel-tangle, they also have some down sides and I'm thinking that
1623 session-based execution maybe shouldn't be the default behavior.
1625 Down-sides to sessions
1626 - *much* more complicated than functional evaluation
1627   - maintaining the state of the session has weird issues
1628   - waiting for evaluation to finish
1629   - prompt issues like [[* TODO weird escaped characters in shell prompt break shell evaluation][shell-prompt-escapes-bug]]
1630 - can't run in background
1631 - litter emacs with session buffers
1633 *** DONE ruby
1635 #+srcname: ruby-task-no-session
1636 #+begin_src ruby :results replace output
1637 puts :eric
1638 puts :schulte
1639 [1, 2, 3]
1640 #+end_src
1642 #+resname: ruby-task-no-session
1643 | "eric"    |
1644 | "schulte" |
1645 *** DONE python
1647 #+srcname: task-python-none-session
1648 #+begin_src python :session none :results replace value
1649 print 'something'
1650 print 'output'
1651 [1, 2, 3]
1652 #+end_src
1654 #+resname: task-python-none-session
1655 | 1 | 2 | 3 |
1657 *** DONE sh
1659 #+srcname: task-session-none-sh
1660 #+begin_src sh :results replace
1661 echo "first"
1662 echo "second"
1663 #+end_src
1665 #+resname: task-session-none-sh
1666 | "first"  |
1667 | "second" |
1669 *** DONE R
1671 #+srcname: task-no-session-R
1672 #+begin_src R :results replace output
1673 a <- 8
1674 b <- 9
1675 a + b
1676 b - a
1677 #+end_src
1679 #+resname: task-no-session-R
1680 | "[1]" | 17 |
1681 | "[1]" |  1 |
1683 ** DONE fully purge org-babel-R of direct comint interaction
1684 try to remove all code under the [[file:lisp/org-babel-R.el::functions%20for%20evaluation%20of%20R%20code][;; functions for evaluation of R code]] line
1686 ** DONE Create objects in top level (global) environment [5/5]
1687 *sessions*
1689 *** initial requirement statement [DED]
1690    At the moment, objects created by computations performed in the
1691    code block are evaluated in the scope of the
1692    code-block-function-body and therefore disappear when the code
1693    block is evaluated {unless you employ some extra trickery like
1694    assign('name', object, env=globalenv()) }. I think it will be
1695    desirable to also allow for a style wherein objects that are
1696    created in one code block persist in the R global environment and
1697    can be re-used in a separate block.
1699    This is what Sweave does, and while I'm not saying we have to be
1700    the same as Sweave, it wouldn't be hard for us to provide the same
1701    behaviour in this case; if we don't, we risk undeservedly being
1702    written off as an oddity by some.
1704    IOW one aspect of org-babel is that of a sort of functional
1705    meta-programming language. This is crazy, in a very good
1706    way. Nevertheless, wrt R I think there's going to be a lot of value
1707    in providing for a working style in which the objects are stored in
1708    the R session, rather than elisp/org buffer. This will be a very
1709    familiar working style to lots of people.
1711    There are no doubt a number of different ways of accomplishing
1712    this, the simplest being a hack like adding
1714 #+begin_src R
1715 for(objname in ls())
1716     assign(objname, get(objname), envir=globalenv())
1717 #+end_src
1719 to the source code block function body. (Maybe wrap it in an on.exit() call).
1721 However this may deserve to be thought about more carefully, perhaps
1722 with a view to having a uniform approach across languages. E.g. shell
1723 code blocks have the same semantics at the moment (no persistence of
1724 variables across code blocks), because the body is evaluated in a new
1725 bash shell process rather than a running shell. And I guess the same
1726 is true for python. However, in both these cases, you could imagine
1727 implementing the alternative in which the body is evaluated in a
1728 persistent interactive session. It's just that it's particularly
1729 natural for R, seeing as both ESS and org-babel evaluate commands in a
1730 single persistent R session.
1732 *** sessions [Eric]
1734 Thanks for bringing this up.  I think you are absolutely correct that we
1735 should provide support for a persistent environment (maybe called a
1736 *session*) in which to evaluate code blocks.  I think the current setup
1737 demonstrates my personal bias for a functional style of programming
1738 which is certainly not ideal in all contexts.
1740 While the R function you mention does look like an elegant solution, I
1741 think we should choose an implementation that would be the same across
1742 all source code types.  Specifically I think we should allow the user to
1743 specify an optional *session* as a header variable (when not present we
1744 assume a default session for each language).  The session name could be
1745 used to name a comint buffer (like the *R* buffer) in which all
1746 evaluation would take place (within which variables would retain their
1747 values --at least once I remove some of the functional method wrappings
1748 currently in place-- ).
1750 This would allow multiple environments to be used in the same buffer,
1751 and once this setup was implemented we should be able to fairly easily
1752 implement commands for jumping between source code blocks and the
1753 related session buffers, as well as for dumping the last N commands from
1754 a session into a new or existing source code block.
1756 Please let me know if you foresee any problems with this proposed setup,
1757 or if you think any parts might be confusing for people coming from
1758 Sweave.  I'll hopefully find some time to work on this later in the
1759 week.
1761 *** can functional and interpreted/interactive models coexist?
1763 Even though both of these use the same =*R*= buffer the value of =a=
1764 is not preserved because it is assigned inside of a functional
1765 wrapper.
1767 #+srcname: task-R-sessions
1768 #+begin_src R 
1769 a <- 9
1770 b <- 21
1771 a + b
1772 #+end_src
1774 #+srcname: task-R-same-session
1775 #+begin_src R 
1777 #+end_src
1779 This functional wrapper was implemented in order to efficiently return
1780 the results of the execution of the entire source code block.  However
1781 it inhibits the evaluation of source code blocks in the top level,
1782 which would allow for persistence of variable assignment across
1783 evaluations.  How can we allow *both* evaluation in the top level, and
1784 efficient capture of the return value of an entire source code block
1785 in a language independent manner?
1787 Possible solutions...
1788 1) we can't so we will have to implement two types of evaluation
1789    depending on which is appropriate (functional or imperative)
1790 2) we remove the functional wrapper and parse the source code block
1791    into it's top level statements (most often but not always on line
1792    breaks) so that we can isolate the final segment which is our
1793    return value.
1794 3) we add some sort of "#+return" line to the code block
1795 4) we take advantage of each languages support for meta-programming
1796    through =eval= type functions, and use said to evaluate the entire
1797    blocks in such a way that their environment can be combined with the
1798    global environment, and their results are still captured.
1799 5) I believe that most modern languages which support interactive
1800    sessions have support for a =last_result= type function, which
1801    returns the result of the last input without re-calculation.  If
1802    widely enough present this would be the ideal solution to a
1803    combination of functional and imperative styles.
1805 None of these solutions seem very desirable, but for now I don't see
1806 what else would be possible.
1808 Of these options I was leaning towards (1) and (4) but now believe
1809 that if it is possible option (5) will be ideal.
1811 **** (1) both functional and imperative evaluation
1812 Pros
1813 - can take advantage of built in functions for sending regions to the
1814   inferior process
1815 - retains the proven tested and working functional wrappers
1817 Cons
1818 - introduces the complication of keeping track of which type of
1819   evaluation is best suited to a particular context
1820 - the current functional wrappers may require some changes in order to
1821   include the existing global context
1823 **** (4) exploit language meta-programming constructs to explicitly evaluate code
1824 Pros
1825 - only one type of evaluation
1827 Cons
1828 - some languages may not have sufficient meta-programming constructs
1830 **** (5) exploit some =last_value= functionality if present
1832 Need to ensure that most languages have such a function, those without
1833 will simply have to implement their own similar solution...
1835 | language   | =last_value= function       |
1836 |------------+-----------------------------|
1837 | R          | .Last.value                 |
1838 | ruby       | _                           |
1839 | python     | _                           |
1840 | shell      | see [[* last command for shells][last command for shells]] |
1841 | emacs-lisp | see [[* emacs-lisp will be a special case][special-case]]            |
1843 #+srcname: task-last-value
1844 #+begin_src ruby
1845 82 + 18
1846 #+end_src
1848 ***** last command for shells
1849 Do this using the =tee= shell command, and continually pipe the output
1850 to a file.
1852 Got this idea from the following [[http://linux.derkeiler.com/Mailing-Lists/Fedora/2004-01/0898.html][email-thread]].
1854 suggested from mailing list
1856 #+srcname: bash-save-last-output-to-file
1857 #+begin_src sh 
1858 while read line 
1859 do 
1860   bash -c "$line" | tee /tmp/last.out1 
1861   mv /tmp/last.out1 /tmp/last.out 
1862 done
1863 #+end_src
1865 another proposed solution from the above thread
1867 #+srcname: bash-save-in-variable
1868 #+begin_src sh 
1869 #!/bin/bash 
1870 # so - Save Output. Saves output of command in OUT shell variable. 
1871 OUT=`$*` 
1872 echo $OUT 
1873 #+end_src
1875 and another
1877 #+begin_quote
1878 .inputrc: 
1879 "^[k": accept-line 
1880 "^M": " | tee /tmp/h_lastcmd.out ^[k" 
1882 .bash_profile: 
1883 export __=/tmp/h_lastcmd.out 
1885 If you try it, Alt-k will stand for the old Enter; use "command $__" to 
1886 access the last output. 
1888 Best, 
1892 Herculano de Lima Einloft Neto
1893 #+end_quote
1895 ***** emacs-lisp will be a special case
1896 While it is possible for emacs-lisp to be run in a console type
1897 environment (see the =elim= function) it is *not* possible to run
1898 emacs-lisp in a different *session*.  Meaning any variable set top
1899 level of the console environment will be set *everywhere* inside
1900 emacs.  For this reason I think that it doesn't make any sense to
1901 worry about session support for emacs-lisp.
1903 *** Further thoughts on 'scripting' vs. functional approaches
1905     These are just thoughts, I don't know how sure I am about this.
1906     And again, perhaps I'm not saying anything very radical, just that
1907     it would be nice to have some options supporting things like
1908     receiving text output in the org buffer.
1910     I can see that you've already gone some way down the road towards
1911     the 'last value' approach, so sorry if my comments come rather
1912     late. I am concerned that we are not giving sufficient attention
1913     to stdout / the text that is returned by the interpreters. In
1914     contrast, many of our potential users will be accustomed to a
1915     'scripting' approach, where they are outputting text at various
1916     points in the code block, not just at the end. I am leaning
1917     towards thinking that we should have 2 modes of evaluation:
1918     'script' mode, and 'functional' mode.
1920     In script mode, evaluation of a code block would result in *all*
1921     text output from that code block appearing as output in the org
1922     buffer, presumably as an #+begin_example...#+end_example. There
1923     could be an :echo option controlling whether the input commands
1924     also appear in the output. [This is like Sweave].
1926     In functional mode, the *result* of the code block is available as
1927     an elisp object, and may appear in the org buffer as an org
1928     table/string, via the mechanisms you have developed already.
1930     One thing I'm wondering about is whether, in script mode, there
1931     simply should not be a return value. Perhaps this is not so
1932     different from what exists: script mode would be new, and what
1933     exists currently would be functional mode.
1935     I think it's likely that, while code evaluation will be exciting
1936     to people, a large majority of our users in a large majority of
1937     their usage will not attempt to actually use the return value from
1938     a source code block in any meaningful way. In that case, it seems
1939     rather restrictive to only allow them to see output from the end
1940     of the code block.
1942     Instead I think the most accessible way to introduce org-babel to
1943     people, at least while they are learning it, is as an immensely
1944     powerful environment in which to embed their 'scripts', which now
1945     also allows them to 'run' their 'scripts'. Especially as such
1946     people are likely to be the least capable of the user-base, a
1947     possible design-rule would be to make the scripting style of usage
1948     easy (default?), perhaps requiring a special option to enable a
1949     functional style. Those who will use the functional style won't
1950     have a problem understanding what's going on, whereas the 'skript
1951     kiddies' might not even know the syntax for defining a function in
1952     their language of choice. And of course we can allow the user to
1953     set a variable in their .emacs controlling the preference, so that
1954     functional users are not inconveniennced by having to provide
1955     header args the whole time.
1957     Please don't get the impression that I am down-valuing the
1958     functional style of org-babel. I am constantly horrified at the
1959     messy 'scripts' that my colleagues produce in perl or R or
1960     whatever! Nevertheless that seems to be how a lot of people work.
1961     
1962     I think you were leaning towards the last-value approach because
1963     it offered the possibility of unified code supporting both the
1964     single evaluation environment and the functional style. If you
1965     agree with any of the above then perhaps it will impact upon this
1966     and mean that the code in the two branches has to differ a bit. In
1967     that case, functional mode could perhaps after all evaluate each
1968     code block in its own environment, thus (re)approaching 'true'
1969     functional programming (side-effects are hard to achieve).
1971 #+begin_src sh
1972 ls > files
1973 echo "There are `wc -l files` files in this directory"
1975 #+end_src
1977 *** even more thoughts on evaluation, results, models and options
1979 Thanks Dan, These comments are invaluable.
1981 What do you think about this as a new list of priorities/requirements
1982 for the execution of source-code blocks.
1984 - Sessions
1985    1)  we want the evaluation of the source code block to take place in a
1986        session which can persist state (variables, current directory,
1987        etc...).
1988    2)  source code blocks can specify their session with a header argument
1989    3)  each session should correspond to an Emacs comint buffer so that the
1990        user can drop into the session and experiment with live code
1991        evaluation.
1992 - Results
1993   1) each source-code block generates some form of results which (as
1994      we have already implemented) is transfered into emacs-lisp
1995      after which it can be inserted into the org-mode buffer, or
1996      used by other source-code blocks
1997   2) when the results are translated into emacs-lisp, forced to be
1998      interpreted as a scalar (dumping their raw values into the
1999      org-mode buffer), as a vector (which is often desirable with R
2000      code blocks), or interpreted on the fly (the default option).
2001      Note that this is very nearly currently implemented through the
2002      [[* DONE results-type header (vector/file)][results-type-header]].
2003   3) there should be *two* means of collecting results from the
2004      execution of a source code block.  *Either* the value of the
2005      last statement of the source code block, or the collection of
2006      all that has been passed to STDOUT during the evaluation.
2008 **** header argument or return line (*header argument*)
2010    Rather than using a header argument to specify how the return value
2011    should be passed back, I'm leaning towards the use of a =#+RETURN=
2012    line inside the block.  If such a line *is not present* then we
2013    default to using STDOUT to collect results, but if such a line *is
2014    present* then we use it's value as the results of the block.  I
2015    think this will allow for the most elegant specification between
2016    functional and script execution.  This also cleans up some issues
2017    of implementation and finding which statement is the last
2018    statement.
2020    Having given this more thought, I think a header argument is
2021    preferable.  The =#+return:= line adds new complicating syntax for
2022    something that does little more than we would accomplish through
2023    the addition of a header argument.  The only benefit being that we
2024    know where the final statement starts, which is not an issue in
2025    those languages which contain 'last value' operators.
2027    new header =:results= arguments
2028    - script :: explicitly states that we want to use STDOUT to
2029                initialize our results
2030    - return_last :: stdout is ignored instead the *value* of the final
2031                     statement in the block is returned
2032    - echo :: means echo the contents of the source-code block along
2033              with the results (this implies the *script* =:results=
2034              argument as well)
2036 *** DONE rework evaluation lang-by-lang [4/4]
2038 This should include...
2039 - functional results working with the comint buffer
2040 - results headers
2041   - script :: return the output of STDOUT
2042     - write a macro which runs the first redirection, executes the
2043       body, then runs the second redirection
2044   - last :: return the value of the last statement
2045     - 
2047 - sessions in comint buffers
2049 **** DONE Ruby [4/4]
2050 - [X] functional results working with comint
2051 - [X] script results
2052 - [X] ensure scalar/vector results args are taken into consideration
2053 - [X] ensure callable by other source block
2055 #+srcname: ruby-use-last-output
2056 #+begin_src ruby :results replace
2057 a = 2
2058 b = 4
2059 c = a + b
2060 [a, b, c, 78]
2061 #+end_src
2063 #+resname: ruby-use-last-output
2064 | 2 | 4 | 6 | 78 |
2066 #+srcname: task-call-use-last-output
2067 #+begin_src ruby :var last=ruby-use-last-output :results replace
2068 last.flatten.size + 1
2069 #+end_src
2071 #+resname: task-call-use-last-output
2072 : 5
2074 ***** ruby sessions
2076 #+srcname: first-ruby-session-task
2077 #+begin_src ruby :session schulte :results silent
2078 schulte = 27
2079 #+end_src
2081 #+srcname: second-ruby-session-task
2082 #+begin_src ruby :session schulte :results silent
2083 schulte + 3
2084 #+end_src
2086 #+srcname: without-the-right-session
2087 #+begin_src ruby :results silent
2088 schulte
2089 #+end_src
2091 **** DONE R [4/4]
2093 - [X] functional results working with comint
2094 - [X] script results
2095 - [X] ensure scalar/vector results args are taken into consideration
2096 - [X] ensure callable by other source block
2098 To redirect output to a file, you can use the =sink()= command.
2100 #+srcname: task_R_B
2101 #+begin_src R :results value vector silent
2102 a <- 9
2103 b <- 10
2104 b - a
2105 a + b
2106 #+end_src
2108 #+srcname: task-R-use-other-output
2109 #+begin_src R :var twoentyseven=task_R_B() :results replace value
2111 twoentyseven + 9
2112 #+end_src
2114 #+resname: task-R-use-other-output
2115 : 28
2117 **** DONE Python [4/4]
2118 - [X] functional results working with comint
2119 - [X] script results
2120 - [X] ensure scalar/vector results args are taken into consideration
2121 - [X] ensure callable by other source block
2123 #+srcname: task-new-eval-for-python
2124 #+begin_src python :results silent output scalar
2128 #+end_src
2130 #+srcname: task-use-new-eval
2131 #+begin_src python :var tasking=task-new-eval-for-python() :results replace
2132 tasking + 2
2133 #+end_src
2135 #+resname: task-use-new-eval
2136 : 12
2138 **** DONE Shells [4/4]
2139 - [X] functional results working with comint
2140 - [X] script results
2141 - [X] ensure scalar/vector results args are taken into consideration
2142 - [X] ensure callable by other source block
2144 #+srcname: task-shell-new-evaluation
2145 #+begin_src sh :results silent value scalar
2146 echo 'eric'
2147 date
2148 #+end_src
2150 #+srcname: task-call-other-shell
2151 #+begin_src sh :var other=task-shell-new-evaluation() :results replace  scalar
2152 echo $other ' is the old date'
2153 #+end_src
2155 #+resname: task-call-other-shell
2156 : $ Fri Jun 12 13:08:37 PDT 2009  is the old date
2158 *** DONE implement a *session* header argument [4/4]
2159 =:session= header argument to override the default *session* buffer
2161 **** DONE ruby
2163 #+srcname: task-ruby-named-session
2164 #+begin_src ruby :session schulte :results replace
2165 schulte = :in_schulte
2166 #+end_src
2168 #+resname: task-ruby-named-session
2169 : :in_schulte
2171 #+srcname: another-in-schulte
2172 #+begin_src ruby :session schulte 
2173 schulte
2174 #+end_src
2176 #+resname: another-in-schulte
2177 : :in_schulte
2178 : :in_schulte
2179 : :in_schulte
2181 **** DONE python
2183 #+srcname: python-session-task
2184 #+begin_src python :session what :results silent
2185 what = 98
2186 #+end_src
2188 #+srcname: python-get-from-session
2189 #+begin_src python :session what :results replace
2190 what
2191 #+end_src
2193 #+resname: python-get-from-session
2194 : 98
2196 **** DONE shell
2198 #+srcname: task-shell-sessions
2199 #+begin_src sh :session what
2200 WHAT='patton'
2201 #+end_src
2203 #+srcname: task-shell-sessions-what
2204 #+begin_src sh :session what :results replace
2205 echo $WHAT
2206 #+end_src
2208 #+resname: task-shell-sessions-what
2209 : patton
2211 **** DONE R
2213 #+srcname: task-R-session
2214 #+begin_src R :session what :results replace
2215 a <- 9
2216 b <- 8
2217 a + b
2218 #+end_src
2220 #+resname: task-R-session
2221 : 17
2223 #+srcname: another-task-R-session
2224 #+begin_src R :session what :results replace
2225 a + b
2226 #+end_src
2228 *** DONE function to bring up inferior-process buffer [4/4]
2230 This should be callable from inside of a source-code block in an
2231 org-mode buffer.  It should evaluate the header arguments, then bring
2232 up the inf-proc buffer using =pop-to-buffer=.
2234 For lack of a better place, lets add this to the `org-metadown-hook'
2235 hook.
2237 To give this a try, place the cursor on a source block with variables,
2238 (optionally git a prefix argument) then hold meta and press down.
2240 **** DONE ruby
2242 #+srcname: task-ruby-pop-to-session
2243 #+begin_src ruby :var num=9 :var another="something else"
2244 num.times{|n| puts another}
2245 #+end_src
2247 **** DONE python
2249 #+srcname: task-python-pop-to-session
2250 #+begin_src python :var num=9 :var another="something else"
2251 another * num
2252 #+end_src
2253 **** DONE R
2255 #+srcname: task-R-pop-to-session
2256 #+begin_src R :var a=9 :var b=8
2257 a * b
2258 #+end_src
2260 **** DONE shell
2262 #+srcname: task-shell-pop-sessions
2263 #+begin_src sh :var NAME="eric"
2264 echo $NAME
2265 #+end_src
2267 *** DEFERRED function to dump last N lines from inf-proc buffer into the current source block
2269 Callable with a prefix argument to specify how many lines should be
2270 dumped into the source-code buffer.
2272 *** REJECTED comint notes
2274 Implementing comint integration in [[file:lisp/org-babel-comint.el][org-babel-comint.el]].
2276 Need to have...
2277 - handling of outputs
2278   - split raw output from process by prompts
2279   - a ring of the outputs, buffer-local, `org-babel-comint-output-ring'
2280   - a switch for dumping all outputs to a buffer
2281 - inputting commands
2283 Lets drop all this language specific stuff, and just use
2284 org-babel-comint to split up our outputs, and return either the last
2285 value of an execution or the combination of values from the
2286 executions.
2288 **** comint filter functions
2289 : ;;  comint-input-filter-functions     hook    process-in-a-buffer
2290 : ;;  comint-output-filter-functions    hook    function modes.
2291 : ;;  comint-preoutput-filter-functions   hook
2292 : ;;  comint-input-filter                       function ...
2294 #+srcname: obc-filter-ruby
2295 #+begin_src ruby :results last
2301 #+end_src
2303 ** DONE Remove protective commas from # comments before evaluating
2304    org inserts protective commas in front of ## comments in language
2305    modes that use them. We need to remove them prior to sending code
2306    to the interpreter.
2308 #+srcname: testing-removal-of-protective-comas
2309 #+begin_src ruby
2310 ,# this one might break it??
2311 :comma_protection
2312 #+end_src
2314 ** DONE pass multiple reference arguments into R
2315    Can we do this? I wasn't sure how to supply multiple 'var' header
2316    args. Just delete this if I'm being dense.
2318    This should be working, see the following example...
2320 #+srcname: two-arg-example
2321 #+begin_src R :var n=2 :var m=8
2322 n + m
2323 #+end_src
2325 #+resname: two-arg-example
2326 : 10
2328 ** DONE ensure that table ranges work
2329 when a table range is passed to org-babel as an argument, it should be
2330 interpreted as a vector.
2332 | 1 | 2 | simple       |
2333 | 2 | 3 | Fixnum:1     |
2334 | 3 | 4 | Array:123456 |
2335 | 4 | 5 |              |
2336 | 5 | 6 |              |
2337 | 6 | 7 |              |
2338 #+TBLFM: @1$3='(sbe simple-sbe-example (n 4))::@2$3='(sbe task-table-range (n @1$1..@6$1))::@3$3='(sbe task-table-range (n (@1$1..@6$1)))
2340 #+srcname: simple-sbe-example
2341 #+begin_src emacs-lisp 
2342 "simple"
2343 #+end_src
2345 #+srcname: task-table-range
2346 #+begin_src ruby :var n=simple-sbe-example
2347 "#{n.class}:#{n}"
2348 #+end_src
2350 #+srcname: simple-results
2351 #+begin_src emacs-lisp :var n=task-table-range(n=(1 2 3))
2353 #+end_src
2355 #+resname: simple-results
2356 : Array:123
2358 #+srcname: task-arr-referent
2359 #+begin_src ruby :var ar=(1 2 3)
2360 ar.size
2361 #+end_src
2363 #+resname: task-arr-referent
2364 : 3
2366 ** DONE global variable indicating default to vector output
2367 how about an alist... =org-babel-default-header-args= this may already
2368 exist... just execute the following and all source blocks will default
2369 to vector output
2371 #+begin_src emacs-lisp 
2372 (setq org-babel-default-header-args '((:results . "vector")))
2373 #+end_src
2375 ** DONE name named results if source block is named
2376 currently this isn't happening although it should be
2378 #+srcname: test-naming-named-source-blocks
2379 #+begin_src emacs-lisp 
2380 :namer
2381 #+end_src
2383 #+resname: test-naming-named-source-blocks
2384 : :namer
2385 ** DONE (simple caching) check for named results before source blocks
2386 see the TODO comment in [[file:lisp/org-babel-ref.el::TODO%20This%20should%20explicitly%20look%20for%20resname%20lines%20before][org-babel-ref.el#org-babel-ref-resolve-reference]]
2387 ** DONE set =:results silent= when eval with prefix argument
2389 #+begin_src emacs-lisp
2390 'silentp
2391 #+end_src
2392 ** DONE results-type header (vector/file) [3/3]
2393    In response to a point in Dan's email.  We should allow the user to
2394    force scalar or vector results.  This could be done with a header
2395    argument, and the default behavior could be controlled through a
2396    configuration variable.
2397    
2398 #+srcname: task-trivial-vector
2399 #+begin_src ruby :results replace vector
2400 :scalar
2401 #+end_src
2403 #+resname:
2404 | ":scalar" |
2406    since it doesn't make sense to turn a vector into a scalar, lets
2407    just add a two values...
2408    
2409    - vector :: forces the results to be a vector (potentially 1 dimensional)
2410    - file :: this throws an error if the result isn't a string, and
2411              tries to treat it as a path to a file.
2413    I'm just going to cram all of these into the =:results= header
2414    argument.  Then if we allow multiple header arguments it should
2415    work out, for example one possible header argument string could be
2416    =:results replace vector file=, which would *replace* any existing
2417    results forcing the results into an org-mode table, and
2418    interpreting any strings as file paths.
2420 *** DONE multiple =:results= headers
2422 #+srcname: multiple-result-headers
2423 #+begin_src ruby :results replace silent
2424 :schulte
2425 #+end_src
2427 #+resname:
2429 *** DONE file result types
2430 When inserting into an org-mode buffer create a link with the path
2431 being the value, and optionally the display being the
2432 =file-name-nondirectory= if it exists.
2434 #+srcname: task-file-result
2435 #+begin_src python :results replace file
2436 "something"
2437 #+end_src
2439 #+resname:
2440 [[something][something]]
2443 This will be useful because blocks like =ditaa= and =dot= can return
2444 the string path of their files, and can add =file= to their results
2445 header.
2447 *** DONE vector result types
2449 #+srcname: task-force-results
2450 #+begin_src emacs-lisp :results vector
2452 #+end_src
2454 #+resname:
2455 | 8 |
2457 ** DONE results name
2458     In order to do this we will need to start naming our results.
2459     Since the source blocks are named with =#+srcname:= lines we can
2460     name results with =#+resname:= lines (if the source block has no
2461     name then no name is given to the =#+resname:= line on creation,
2462     otherwise the name of the source block is used).
2464     This will have the additional benefit of allowing results and
2465     source blocks to be located in different places in a buffer (and
2466     eventually in different buffers entirely).
2468 #+srcname: developing-resnames
2469 #+begin_src emacs-lisp  :results silent
2470 'schulte
2471 #+end_src
2473     Once source blocks are able to find their own =#+resname:= lines
2474     we then need to...
2476 #+srcname: sbe-w-new-results
2477 #+begin_src emacs-lisp :results replace
2478 (sbe "developing-resnames")
2479 #+end_src
2481 #+resname:
2482 : schulte
2484 *** TODO change the results insertion functions to use these lines
2486 *** TODO teach references to resolve =#+resname= lines.
2488 ** DONE org-babel tests org-babel [1/1]
2489 since we are accumulating this nice collection of source-code blocks
2490 in the sandbox section we should make use of them as unit tests.
2491 What's more, we should be able to actually use org-babel to run these
2492 tests.
2494 We would just need to cycle over every source code block under the
2495 sandbox, run it, and assert that the return value is equal to what we
2496 expect.
2498 I have the feeling that this should be possible using only org-babel
2499 functions with minimal or no additional elisp.  It would be very cool
2500 for org-babel to be able to test itself.
2502 This is now done, see [[* Tests]].
2504 *** DEFERRED org-babel assertions (may not be necessary)
2505 These could be used to make assertions about the results of a
2506 source-code block.  If the assertion fails then the point could be
2507 moved to the block, and error messages and highlighting etc... could
2508 ensue
2510 ** DONE make C-c C-c work anywhere within source code block?
2511    This seems like it would be nice to me, but perhaps it would be
2512    inefficient or ugly in implementation? I suppose you could search
2513    forward, and if you find #+end_src before you find #+begin_src,
2514    then you're inside one. [DED]
2516    Agreed, I think inside of the =#+srcname: line= would be useful as
2517    well.
2519 #+srcname: testing-out-cc
2520 #+begin_src emacs-lisp
2521 'schulte
2522 #+end_src
2524 ** DONE integration with org tables
2525 We should make it easy to call org-babel source blocks from org-mode
2526 table formulas.  This is practical now that it is possible to pass
2527 arguments to org-babel source blocks.
2529 See the related [[* (sandbox) integration w/org tables][sandbox]] header for tests/examples.
2531 *** digging in org-table.el
2532 In the past [[file:~/src/org/lisp/org-table.el::org%20table%20el%20The%20table%20editor%20for%20Org%20mode][org-table.el]] has proven difficult to work with.
2534 Should be a hook in [[file:~/src/org/lisp/org-table.el::defun%20org%20table%20eval%20formula%20optional%20arg%20equation][org-table-eval-formula]].
2536 Looks like I need to change this [[file:~/src/org/lisp/org-table.el::if%20lispp][if statement]] (line 2239) into a cond
2537 expression.
2539 ** DONE source blocks as functions
2541 Allow source code blocks to be called like functions, with arguments
2542 specified.  We are already able to call a source-code block and assign
2543 it's return result to a variable.  This would just add the ability to
2544 specify the values of the arguments to the source code block assuming
2545 any exist.  For an example see 
2547 When a variable appears in a header argument, how do we differentiate
2548 between it's value being a reference or a literal value?  I guess this
2549 could work just like a programming language.  If it's escaped or in
2550 quotes, then we count it as a literal, otherwise we try to look it up
2551 and evaluate it.
2553 ** DONE folding of code blocks? [2/2]
2554    [DED] In similar way to using outline-minor-mode for folding function
2555    bodies, can we fold code blocks?  #+begin whatever statements are
2556    pretty ugly, and in any case when you're thinking about the overall
2557    game plan you don't necessarily want to see the code for each Step.
2559 *** DONE folding of source code block
2560     Sounds good, and wasn't too hard to implement.  Code blocks should
2561     now be fold-able in the same manner as headlines (by pressing TAB
2562     on the first line).
2564 *** REJECTED folding of results
2565     So, lets do a three-stage tab cycle... First fold the src block,
2566     then fold the results, then unfold.
2567     
2568     There's no way to tell if the results are a table or not w/o
2569     actually executing the block which would be too expensive of an
2570     operation.
2572 ** DONE selective export of text, code, figures
2573    [DED] The org-babel buffer contains everything (code, headings and
2574    notes/prose describing what you're up to, textual/numeric/graphical
2575    code output, etc). However on export to html / LaTeX one might want
2576    to include only a subset of that content. For example you might
2577    want to create a presentation of what you've done which omits the
2578    code.
2580    [EMS] So I think this should be implemented as a property which can
2581    be set globally or on the outline header level (I need to review
2582    the mechanics of org-mode properties).  And then as a source block
2583    header argument which will apply only to a specific source code
2584    block.  A header argument of =:export= with values of
2585    
2586    - =code= :: just show the code in the source code block
2587    - =none= :: don't show the code or the results of the evaluation
2588    - =results= :: just show the results of the code evaluation (don't
2589                   show the actual code)
2590    - =both= :: show both the source code, and the results
2592 this will be done in [[* (sandbox) selective export][(sandbox) selective export]].
2594 ** DONE a header argument specifying silent evaluation (no output)
2595 This would be useful across all types of source block.  Currently
2596 there is a =:replace t= option to control output, this could be
2597 generalized to an =:output= option which could take the following
2598 options (maybe more)
2600 - =t= :: this would be the default, and would simply insert the
2601          results after the source block
2602 - =replace= :: to replace any results which may already be there
2603 - =silent= :: this would inhibit any insertion of the results
2605 This is now implemented see the example in the [[* silent evaluation][sandbox]]
2607 ** DONE assign variables from tables in R
2608 This is now working (see [[* (sandbox table) R][(sandbox-table)-R]]).  Although it's not that
2609 impressive until we are able to print table results from R.
2611 ** DONE insert 2-D R results as tables
2612 everything is working but R and shell
2614 *** DONE shells
2616 *** DONE R
2618 This has already been tackled by Dan in [[file:existing_tools/org-R.el::defconst%20org%20R%20write%20org%20table%20def][org-R:check-dimensions]].  The
2619 functions there should be useful in combination with [[http://cran.r-project.org/doc/manuals/R-data.html#Export-to-text-files][R-export-to-csv]]
2620 as a means of converting multidimensional R objects to emacs lisp.
2622 It may be as simple as first checking if the data is multidimensional,
2623 and then, if so using =write= to write the data out to a temporary
2624 file from which emacs can read the data in using =org-table-import=.
2626 Looking into this further, is seems that there is no such thing as a
2627 scalar in R [[http://tolstoy.newcastle.edu.au/R/help/03a/3733.html][R-scalar-vs-vector]]  In that light I am not sure how to
2628 deal with trivial vectors (scalars) in R.  I'm tempted to just treat
2629 them as vectors, but then that would lead to a proliferation of
2630 trivial 1-cell tables...
2632 ** DONE allow variable initialization from source blocks
2633 Currently it is possible to initialize a variable from an org-mode
2634 table with a block argument like =table=sandbox= (note that the
2635 variable doesn't have to named =table=) as in the following example
2637 #+TBLNAME: sandbox
2638 | 1 |       2 | 3 |
2639 | 4 | schulte | 6 |
2641 #+begin_src emacs-lisp :var table=sandbox :results replace
2642 (message (format "table = %S" table))
2643 #+end_src
2645 : "table = ((1 2 3) (4 \"schulte\" 6))"
2647 It would be good to allow initialization of variables from the results
2648 of other source blocks in the same manner.  This would probably
2649 require the addition of =#+SRCNAME: example= lines for the naming of
2650 source blocks, also the =table=sandbox= syntax may have to be expanded
2651 to specify whether the target is a source code block or a table
2652 (alternately we could just match the first one with the given name
2653 whether it's a table or a source code block).
2655 At least initially I'll try to implement this so that there is no need
2656 to specify whether the reference is to a table or a source-code block.
2657 That seems to be simpler both in terms of use and implementation.
2659 This is now working for emacs-lisp, ruby and python (and mixtures of
2660 the three) source blocks.  See the examples in the [[* (sandbox) referencing other source blocks][sandbox]].
2662 This is currently working only with emacs lisp as in the following
2663 example in the [[* emacs lisp source reference][emacs lisp source reference]].
2666 ** TODO Add languages [11/15]
2667 I'm sure there are many more that aren't listed here.  Please add
2668 them, and bubble any that you particularly care about up to the top.
2670 Any new language should be implemented in a org-babel-lang.el file.
2671 Follow the pattern set by [[file:lisp/org-babel-script.el][org-babel-script.el]], [[file:lisp/org-babel-shell.el][org-babel-shell.el]] and
2672 [[file:lisp/org-babel-R.el][org-babel-R.el]].
2674 *** STARTED ocaml [2/3]
2676 - [X] Working for the simple case (no arguments, simple output)
2677 - [X] correct handling of vector/list output
2678 - [ ] ability to import arguments
2680 #+begin_src ocaml
2681 let rec fib x =
2682   match x with
2683     | 0 -> 1
2684     | 1 -> 1
2685     | n -> fib(n - 1) + fib(n - 2) in
2686   fib 12
2687 #+end_src
2689 #+resname:
2690 : 233
2692 #+begin_src ocaml
2693 "string"
2694 #+end_src
2696 #+resname:
2697 : "string"
2699 #+begin_src ocaml
2700 [1; 2; 3; 4]
2701 #+end_src
2703 #+resname:
2704 | 1 | 2 | 3 | 4 |
2706 #+begin_src ocaml
2707 [|"ocaml"; "array"|]
2708 #+end_src
2710 #+resname:
2711 | "ocaml" | "array" |
2713 *** TODO perl
2714 This could probably be added to [[file:lisp/org-babel-script.el][org-babel-script.el]]
2715 *** TODO java
2716 *** STARTED SQL
2717 Things left to do
2718 - support for sessions
2719 - add more useful header arguments (user, passwd, database, etc...)
2720 - support for more engines (currently only supports mysql)
2721 - what's a reasonable way to drop table data into SQL?
2723 #+srcname: sql-example
2724 #+begin_src sql :engine mysql
2725   show databases
2726 #+end_src
2728 #+resname:
2729 | "Database"           |
2730 | "information_schema" |
2731 | "test"               |
2733 *** DONE SASS
2734 Sass is a very nice extension of CSS, which is much nicer to read and
2735 write (see [[http://sass-lang.com/][sass-lang]]).
2737 #+srcname: sass-example
2738 #+begin_src sass :file stylesheet.css :results file
2739   #me
2740     position: absolute
2741     top: 1em
2742     left: 1em
2743     .head
2744       text-align: center
2745 #+end_src
2747 #+resname:
2748 [[file:stylesheet.css][stylesheet.css]]
2750 *** DONE CSS
2751 trivial [[file:lisp/langs/org-babel-css.el][org-babel-css.el]]
2753 *** DONE ditaa
2754 (see [[* file result types][file result types]])
2756 #+srcname: implementing-ditaa
2757 #+begin_src ditaa :results replace :file blue.png :cmdline -r
2758 +---------+
2759 | cBLU    |
2760 |         |
2761 |    +----+
2762 |    |cPNK|
2763 |    |    |
2764 +----+----+
2765 #+end_src
2767 #+resname: implementing-ditaa
2768 [[file:blue.png][blue.png]]
2770 *** DONE gnuplot [7/7]
2771 (see [[* file result types][file result types]])
2773 #+PLOT: title:"Citas" ind:1 deps:(3) type:2d with:histograms set:"yrange [0:]"
2774 #+TBLNAME: gnuplot-data
2775 | independent var | first dependent var | second dependent var |
2776 |-----------------+---------------------+----------------------|
2777 |             0.1 |               0.425 |                0.375 |
2778 |             0.2 |              0.3125 |               0.3375 |
2779 |             0.3 |          0.24999993 |           0.28333338 |
2780 |             0.4 |               0.275 |              0.28125 |
2781 |             0.5 |                0.26 |                 0.27 |
2782 |             0.6 |          0.25833338 |           0.24999993 |
2783 |             0.7 |          0.24642845 |           0.23928553 |
2784 |             0.8 |             0.23125 |               0.2375 |
2785 |             0.9 |          0.23333323 |            0.2333332 |
2786 |               1 |              0.2225 |                 0.22 |
2787 |             1.1 |          0.20909075 |           0.22272708 |
2788 |             1.2 |          0.19999998 |           0.21458333 |
2789 |             1.3 |          0.19615368 |           0.21730748 |
2791 #+srcname: implementing-gnuplot
2792 #+begin_src gnuplot :var data=gnuplot-data :results silent
2793 set title "Implementing Gnuplot"
2794 plot data using 1:2 with lines
2795 #+end_src
2797 **** DONE add variables
2798      gnuplot 4.2 and up support user defined variables.  This is how
2799      we will handle variables with org-babel (meaning we will need to
2800      require gnuplot 4.2 and up for variable support, which can be
2801      install using [[http://www.macports.org/install.php][macports]] on Mac OSX).
2803      - scalar variables should be replaced in the body of the gnuplot code
2804      - vector variables should be exported to tab-separated files, and
2805        the variable names should be replaced with the path to the files
2807 **** DONE direct plotting w/o session
2808 **** DEFERRED gnuplot support for column/row names
2809 This should be implemented along the lines of the [[* STARTED Column (and row) names of tables in R input/output][R-colname-support]].
2811 We can do something similar to the :labels param in org-plot, we just
2812 have to be careful to ensure that each label is aligned with the
2813 related data file.
2815 This may be walking too close to an entirely prebuilt plotting tool
2816 rather than straight gnuplot code evaluation.  For now I think this
2817 can wait.
2819 **** DONE a =file= header argument
2820 to specify a file holding the results
2822 #+srcname: gnuplot-to-file-implementation
2823 #+begin_src gnuplot :file plot.png :var data=gnuplot-data
2824 plot data using 1:2, data using 1:3 with lines
2825 #+end_src
2827 #+resname:
2828 [[file:plot.png][plot.png]]
2830 **** DONE helpers from org-plot.el
2831 There are a variety of helpers in org-plot which can be fit nicely
2832 into custom gnuplot header arguments.
2834 These should all be in place by now.
2836 **** DEFERRED header argument specifying 3D data
2838 #+tblname: org-grid
2839 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
2840 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
2841 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
2842 | 0 | 0 | 1 | 1 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 1 | 0 | 0 |
2843 | 0 | 1 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 1 | 0 |
2844 | 0 | 1 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 1 | 0 |
2845 | 0 | 1 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 1 | 1 | 0 |
2846 | 0 | 1 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 |
2847 | 0 | 1 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 |
2848 | 0 | 1 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 1 | 0 |
2849 | 0 | 1 | 0 | 0 | 1 | 0 | 1 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 0 |
2850 | 0 | 0 | 1 | 1 | 0 | 0 | 1 | 0 | 1 | 1 | 0 | 0 | 1 | 1 | 1 | 0 | 0 |
2851 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
2852 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
2854 #+srcname: implementing-gnuplot-grid-plots
2855 #+begin_src gnuplot :vars data=org-grid
2857 #+end_src
2859 **** DONE gnuplot sessions
2860 Working on this, we won't support multiple sessions as `gnuplot-mode'
2861 isn't setup for such things.
2863 Also we can't display results with the default :none session, so for
2864 gnuplot we really want the default behavior to be :default, and to
2865 only run a :none session when explicitly specified.
2867 #+srcname: implementing-gnuplot-sessions
2868 #+begin_src gnuplot :var data=gnuplot-data :session none :file session.png
2869 set title "Implementing Gnuplot Sessions"
2870 plot data using 1:2 with lines
2871 #+end_src
2873 #+resname:
2874 [[file:session.png][session.png]]
2876 *** DONE dot
2877 (see [[* file result types][file result types]])
2879 #+srcname: implementing-dot-support
2880 #+begin_src dot :file test-dot.png :cmdline -Tpng
2881 digraph data_relationships {
2882   "data_requirement" [shape=Mrecord, label="{DataRequirement|description\lformat\l}"]
2883   "data_product" [shape=Mrecord, label="{DataProduct|name\lversion\lpoc\lformat\l}"]
2884   "data_requirement" -> "data_product"
2886 #+end_src
2888 #+resname:
2889 [[file:test-dot.png][test-dot.png]]
2891 *** DONE asymptote
2892 (see [[* file result types][file result types]])
2894 for information on asymptote see http://asymptote.sourceforge.net
2896 #+begin_src asymptote :file asymptote-test.png
2897 import graph;
2899 size(0,4cm);
2901 real f(real t) {return 1+cos(t);}
2903 path g=polargraph(f,0,2pi,operator ..)--cycle;
2904 filldraw(g,pink);
2906 xaxis("$x$",above=true);
2907 yaxis("$y$",above=true);
2909 dot("$(a,0)$",(1,0),N);
2910 dot("$(2a,0)$",(2,0),N+E);
2911 #+end_src
2913 #+resname:
2914 [[file:asymptote-test.png][asymptote-test.png]]
2916 *** DONE ruby
2917 *** DONE python
2918 *** DONE R
2919 *** DONE emacs-lisp
2920 *** DONE sh
2923 * Bugs [39/43]
2924 ** DONE stripping indentation from source-code blocks
2925 This is a problem in [[file:lisp/org-babel-exp.el][org-babel-exp.el]].
2927 ** DONE failing to write srcname to resname when evaluating a named block
2929 #+srcname: please-name-my-result
2930 #+begin_src emacs-lisp 
2931 "I'm the result"
2932 #+end_src
2934 #+resname: please-name-my-result
2935 : I'm the result
2938 ** DONE Python session evaluation bug
2939    The following block evaluates correctly with :session none
2940    (set :results to output), but fails with session-based evaluation
2941    (with :results value, as below, you see the error message)
2943    I edebug'ed it and it seems fine until [[file:lisp/langs/org-babel-python.el::comint%20session%20evaluation%20org%20babel%20comint%20in%20buffer%20buffer%20let%20full%20body][we go to comint]].
2945 #+begin_src python :session pysession :results value
2946   import os
2947   from subprocess import *
2948   
2949   chunk = 10000
2950   format = '.gen.gz'
2951   
2952   cc = [('58C','NBS'),
2953         ('58C','POBI'),
2954         ('NBS','POBI')]
2955   
2956   for outdir in ['none', 'noscots', 'lax', 'strict']:
2957       outdir = os.path.join('exclusion-study', outdir)
2958       for case, control in cc:
2959           outfile = os.path.join(outdir, '%s-vs-%s-direct' % (case, control))
2960           cmd = 'snptest %s -frequentist 1 -hwe ' % ('-gen_gz' if format == '.gen.gz' else '')
2961           cmd += '-cases %s %s ' % (case + format, case + '.sample')
2963           cmd += '-controls %s %s ' % (control + format, control + '.sample')
2964           cmd += '-exclude_samples %s ' % os.path.join(outdir, 'exclusions')
2965           cmd += '-o %s ' % outfile
2966           cmd += '-chunk %d ' % chunk
2967           cmd += '> %s' % outfile + '.log'
2968           # os.system(cmd)
2969           print(cmd)
2970 #+end_src
2972 #+resname:
2973 #+begin_example
2974 snptest -gen_gz -frequentist 1 -hwe -cases 58C.gen.gz 58C.sample -controls NBS.gen.gz NBS.sample -exclude_samples exclusion-study/none/exclusions -o exclusion-study/none/58C-vs-NBS-direct -chunk 10000 > exclusion-study/none/58C-vs-NBS-direct.log
2975 snptest -gen_gz -frequentist 1 -hwe -cases 58C.gen.gz 58C.sample -controls POBI.gen.gz POBI.sample -exclude_samples exclusion-study/none/exclusions -o exclusion-study/none/58C-vs-POBI-direct -chunk 10000 > exclusion-study/none/58C-vs-POBI-direct.log
2976 snptest -gen_gz -frequentist 1 -hwe -cases NBS.gen.gz NBS.sample -controls POBI.gen.gz POBI.sample -exclude_samples exclusion-study/none/exclusions -o exclusion-study/none/NBS-vs-POBI-direct -chunk 10000 > exclusion-study/none/NBS-vs-POBI-direct.log
2977 snptest -gen_gz -frequentist 1 -hwe -cases 58C.gen.gz 58C.sample -controls NBS.gen.gz NBS.sample -exclude_samples exclusion-study/noscots/exclusions -o exclusion-study/noscots/58C-vs-NBS-direct -chunk 10000 > exclusion-study/noscots/58C-vs-NBS-direct.log
2978 snptest -gen_gz -frequentist 1 -hwe -cases 58C.gen.gz 58C.sample -controls POBI.gen.gz POBI.sample -exclude_samples exclusion-study/noscots/exclusions -o exclusion-study/noscots/58C-vs-POBI-direct -chunk 10000 > exclusion-study/noscots/58C-vs-POBI-direct.log
2979 snptest -gen_gz -frequentist 1 -hwe -cases NBS.gen.gz NBS.sample -controls POBI.gen.gz POBI.sample -exclude_samples exclusion-study/noscots/exclusions -o exclusion-study/noscots/NBS-vs-POBI-direct -chunk 10000 > exclusion-study/noscots/NBS-vs-POBI-direct.log
2980 snptest -gen_gz -frequentist 1 -hwe -cases 58C.gen.gz 58C.sample -controls NBS.gen.gz NBS.sample -exclude_samples exclusion-study/lax/exclusions -o exclusion-study/lax/58C-vs-NBS-direct -chunk 10000 > exclusion-study/lax/58C-vs-NBS-direct.log
2981 snptest -gen_gz -frequentist 1 -hwe -cases 58C.gen.gz 58C.sample -controls POBI.gen.gz POBI.sample -exclude_samples exclusion-study/lax/exclusions -o exclusion-study/lax/58C-vs-POBI-direct -chunk 10000 > exclusion-study/lax/58C-vs-POBI-direct.log
2982 snptest -gen_gz -frequentist 1 -hwe -cases NBS.gen.gz NBS.sample -controls POBI.gen.gz POBI.sample -exclude_samples exclusion-study/lax/exclusions -o exclusion-study/lax/NBS-vs-POBI-direct -chunk 10000 > exclusion-study/lax/NBS-vs-POBI-direct.log
2983 snptest -gen_gz -frequentist 1 -hwe -cases 58C.gen.gz 58C.sample -controls NBS.gen.gz NBS.sample -exclude_samples exclusion-study/strict/exclusions -o exclusion-study/strict/58C-vs-NBS-direct -chunk 10000 > exclusion-study/strict/58C-vs-NBS-direct.log
2984 snptest -gen_gz -frequentist 1 -hwe -cases 58C.gen.gz 58C.sample -controls POBI.gen.gz POBI.sample -exclude_samples exclusion-study/strict/exclusions -o exclusion-study/strict/58C-vs-POBI-direct -chunk 10000 > exclusion-study/strict/58C-vs-POBI-direct.log
2985 snptest -gen_gz -frequentist 1 -hwe -cases NBS.gen.gz NBS.sample -controls POBI.gen.gz POBI.sample -exclude_samples exclusion-study/strict/exclusions -o exclusion-study/strict/NBS-vs-POBI-direct -chunk 10000 > exclusion-study/strict/NBS-vs-POBI-direct.log
2986 #+end_example
2988 ** DONE require users to explicitly turn on each language
2989 As we continue to add more languages to org-babel, many of which will
2990 require new major-modes we need to re-think how languages are added to
2991 org-babel.
2993 Currently we are requiring all available languages in the
2994 [[file:lisp/org-babel-init.el][org-babel-init.el]] file.  I think we need to change this to a user
2995 setting so that only the language which have their requirements met
2996 (in terms of system executables and emacs major modes) are loaded.  It
2997 is one more step for install, but it seems to me to be the only
2998 solution.  Thoughts?
3000 *** proposed
3002 we add something like the following to the instillation instructions  
3004 #+begin_src emacs-lisp
3005 ;; Uncomment each of the following require lines if you want org-babel
3006 ;; to support that language.  Each language has a comment explaining
3007 ;; it's dependencies.  See the related files in lisp/langs for more
3008 ;; detailed explanations of requirements.
3009 ;; 
3010 ;; (require 'org-babel-R)         ;; ess-mode
3011 ;; (require 'org-babel-asymptote) ;; asymptote be installed on your system
3012 ;; (require 'org-babel-css)       ;; none
3013 ;; (require 'org-babel-ditaa)     ;; ditaa be installed on your system
3014 ;; (require 'org-babel-dot)       ;; dot be installed on your system
3015 ;; (require 'org-babel-gnuplot)   ;; gnuplot-mode
3016 ;; (require 'org-babel-python)    ;; python-mode
3017 ;; (require 'org-babel-ruby)      ;; inf-ruby mode, ruby and irb must be installed on your system
3018 ;; (require 'org-babel-sql)       ;; none
3019 #+end_src
3021 note that =org-babel-sh=, =org-babel-emacs-lisp= are not included in
3022 the list as they can safely be assumed to work on any system.
3024 *** impetus
3025 we should come up with a way to gracefully degrade when support for a
3026 specific language is missing
3028 > To demonstrate creation of documents, open the "test-export.org" file in
3029 > the base of the org-babel directory, and export it as you would any
3030 > other org-mode file.  The "exports" header argument controls how
3031 > source-code blocks are exported, with the following options
3033 > - none :: no part of the source-code block is exported in the document
3034 > - results :: only the output of the evaluated block is exported
3035 > - code :: the code itself is exported
3036 > - both :: both the code and results are exported
3038 I have this error showing up:
3040 executing Ruby source code block
3041 apply: Searching for program: no such file or directory, irb
3043 ** DONE problem with newlines in output when :results value
3045 #+begin_src python :results value
3046 '\n'.join(map(str, range(4)))
3047 #+end_src
3049 #+resname:
3050 : 0
3051 : 1
3052 : 2
3053 : 3
3055 Whereas I was hoping for
3057 | 0 |
3058 | 1 |
3059 | 2 |
3060 | 3 |
3062 *Note*: to generate the above you can try using the new =raw= results
3063 header.
3065 #+begin_src python :results value raw
3066 '|'+'|\n|'.join(map(str, range(4)))+'|'
3067 #+end_src
3069 #+resname:
3070 | 0 |
3071 | 1 |
3072 | 2 |
3073 | 3 |
3075 This is now working, it doesn't return as a table because the value
3076 returned is technically a string.  To return the table mentioned above
3077 try something like the following.
3079 #+begin_src python
3080 [[0], [1], [2], [3]]
3081 #+end_src
3083 #+resname:
3084 | 0 |
3085 | 1 |
3086 | 2 |
3087 | 3 |
3089 This is some sort of non-printing char / quoting issue I think. Note
3090 that
3092 #+begin_src python :results value
3093 '\\n'.join(map(str, range(4)))
3094 #+end_src
3096 #+resname:
3097 : 0\n1\n2\n3
3099 Also, note that
3100 #+begin_src python :results output
3101 print('\n'.join(map(str, range(4))))
3102 #+end_src
3104 #+resname:
3105 : 0
3106 : 1
3107 : 2
3108 : 3
3110 *** collapsing consecutive newlines in string output
3111     
3112     This is an example of the same bug
3114 #+srcname: multi-line-string-output
3115 #+begin_src ruby :results output
3116 "the first line ends here
3119      and this is the second one
3121 even a third"
3122 #+end_src
3124 This doesn't produce anything at all now. I believe that's because
3125 I've changed things so that :results output really does *not* get the
3126 value of the block, only the STDOUT. So if we add a print statement
3127 this works OK.
3129 #+srcname: multi-line-string-output
3130 #+begin_src ruby :results output
3131 print "the first line ends here
3134      and this is the second one
3136 even a third"
3137 #+end_src
3139 #+resname:
3140 : the first line ends here
3143 :      and this is the second one
3145 : even a third
3147 However, the behaviour with :results value is wrong
3149 #+srcname: multi-line-string-value
3150 #+begin_src ruby
3151 "the first line ends here
3154      and this is the second one
3156 even a third"
3157 #+end_src
3159 #+resname:
3160 : 0
3162 ** TODO prompt characters appearing in output with R
3163 #+begin_src R :session *R* :results output
3164   x <- 6
3165   y <- 8
3166   3
3167 #+end_src      
3169 #+resname:
3170 : > [1] 3
3172 ** TODO o-b-execute-subtree overwrites heading when subtree is folded
3173 *** Example
3174     Try M-x org-babel-execute-subtree with the subtree folded and
3175     point at the beginning of the heading line.
3176 #+begin_src sh
3177 size=5
3178 #+end_src
3179 ** DONE non-orgtbl formatted lists
3180 for example
3182 #+srcname: this-doesn't-match-orgtbl
3183 #+begin_src emacs-lisp :results replace
3184 '((:results . "replace"))
3185 #+end_src
3187 #+resname:
3188 | (:results . "replace") |
3190 #+srcname: this-probably-also-wont-work
3191 #+begin_src emacs-lisp :results replace
3192 '(eric schulte)
3193 #+end_src
3195 #+resname:
3196 | eric | schulte |
3198 ** PROPOSED allow un-named arguments
3200 #+srcname: f(x)
3201 #+begin_src python 
3203 #+end_src
3205 #+lob: f(5)
3207 ## produces no output
3209  It's not essential but would be nice for this to work. To do it
3210 properly, would mean that we'd have to specify rules for how a string
3211 of supplied arguments (some possibly named) interact with the
3212 arguments in the definition (some possibly with defaults) to give
3213 values to the variables in the funbction body.
3214 ** PROPOSED external shell execution can't isolate return values
3215 I have no idea how to do this as of yet.  The result is that when
3216 shell functions are run w/o a session there is no difference between
3217 the =output= and =value= result arguments.
3219 Yea, I don't know how to do this either.  I searched extensively on
3220 how to isolate the *last* output of a series of shell commands (see
3221 [[* last command for
3222  shells][last command for shells]]).  The results of the search were basically
3223 that it was not possible (or at least not accomplish-able with a
3224 reasonable amount of effort).
3226 That fact combined with the tenancy to all ways use standard out in
3227 shell scripts led me to treat these two options (=output= and =value=)
3228 as identical in shell evaluation.  Not ideal but maybe good enough for
3229 the moment.
3231 In the `results' branch I've changed this so that they're not quite
3232 identical: output results in raw stdout contents, whereas value
3233 converts it to elisp, perhaps to a table if it looks tabular. This is
3234 the same for the other languages. [Dan]
3235    
3236 ** DONE adding blank line when source-block produces no output
3238 #+srcname: show-org-babel-trim
3239 #+begin_src sh
3240 find . \( -path \*/SCCS -o -path \*/RCS -o -path \*/CVS -o -path \*/MCVS -o -path \*/.svn -o -path \*/.git -o -path \*/.hg -o -path \*/.bzr -o -path \*/_MTN -o -path \*/_darcs -o -path \*/\{arch\} \) -prune -o  -type f \( -iname \*.el \) -exec grep -i -nH -e org-babel-trim {} \;
3241 #+end_src
3243 ** DONE Allow source blocks to be recognised when #+ are not first characters on the line
3244    I think Carsten has recently altered the core so that #+ can have
3245    preceding whitespace, at least for literal/code examples. org-babel
3246    should support this.
3248 #+srcname: testing-indentation
3249    #+begin_src emacs-lisp :results silent
3250    (message "i'm indented")
3251    #+end_src
3253 #+srcname: testing-non-indentation
3254 #+begin_src emacs-lisp :results silent
3255 (message "I'm not indented")
3256 #+end_src
3258 #+srcname: i-resolve-references-to-the-indented
3259 #+begin_src emacs-lisp :var speech=testing-indentation :results silent
3260 (message "I said %s" speech)
3261 #+end_src
3263 ** DONE are the org-babel-trim s necessary?
3264    at the end of e.g. org-babel-R-evaluate, org-babel-python-evaluate, but
3265    not org-babel-ruby-evaluate
3266    
3267    I think it depends on the language, if we find that extra blank
3268    lines are being inserted in a particular language that is a good
3269    indication that the trim or chomp functions may be appropriate.
3271    org-babel-trim and the related org-babel-chomp are use throughout
3272    org-babel...
3274 #+srcname: show-org-babel-trim-usage
3275 #+begin_src sh :results output
3276 find lisp/ \( -path \*/SCCS -o -path \*/RCS -o -path \*/CVS -o -path \*/MCVS -o -path \*/.svn -o -path \*/.git -o -path \*/.hg -o -path \*/.bzr -o -path \*/_MTN -o -path \*/_darcs -o -path \*/\{arch\} \) -prune -o  -type f \( -iname \*.el \) -exec grep -i -nH org-babel-trim {} \;
3277 #+end_src
3279 #+resname:
3280 #+begin_example
3281 lisp//langs/org-babel-python.el:49:                  vars "\n") "\n" (org-babel-trim body) "\n")) ;; then the source block body
3282 lisp//langs/org-babel-python.el:143:                           (org-remove-indentation (org-babel-trim body)) "[\r\n]")))
3283 lisp//langs/org-babel-python.el:158:           #'org-babel-trim
3284 lisp//langs/org-babel-python.el:166:                                           (reverse (mapcar #'org-babel-trim raw)))))))
3285 lisp//langs/org-babel-python.el:169:      (output (org-babel-trim (mapconcat #'identity (reverse (cdr results)) "\n")))
3286 lisp//langs/org-babel-python.el:170:      (value (org-babel-python-table-or-string (org-babel-trim (car results)))))))))
3287 lisp//langs/org-babel-ruby.el:149:                                                  (mapcar #'org-babel-trim raw)))))))
3288 lisp//langs/org-babel-sh.el:148:                                                  (mapcar #'org-babel-trim raw)))))))
3289 lisp//langs/org-babel-sh.el:151:            (output (org-babel-trim (mapconcat #'org-babel-trim (reverse results) "\n")))
3290 lisp//org-babel-ref.el:161:    (mapcar #'org-babel-trim (reverse (cons buffer return)))))
3291 lisp//org-babel.el:198:    (with-temp-buffer (insert (org-babel-trim body)) (copy-region-as-kill (point-min) (point-max)))
3292 lisp//org-babel.el:465:           (org-babel-trim
3293 lisp//org-babel.el:706:(defun org-babel-trim (string &optional regexp)
3294 #+end_example
3296 #+srcname: show-org-babel-chomp-usage
3297 #+begin_src sh :results output
3298 find lisp/ \( -path \*/SCCS -o -path \*/RCS -o -path \*/CVS -o -path \*/MCVS -o -path \*/.svn -o -path \*/.git -o -path \*/.hg -o -path \*/.bzr -o -path \*/_MTN -o -path \*/_darcs -o -path \*/\{arch\} \) -prune -o  -type f \( -iname \*.el \) -exec grep -i -nH org-babel-chomp {} \;
3299 #+end_src
3301 #+resname:
3302 #+begin_example
3303 lisp//langs/org-babel-R.el:122:             (full-body (mapconcat #'org-babel-chomp
3304 lisp//langs/org-babel-R.el:143:       (delete nil (mapcar #'extractor (mapcar #'org-babel-chomp raw))) "\n"))))))))
3305 lisp//langs/org-babel-ruby.el:143:           #'org-babel-chomp
3306 lisp//langs/org-babel-sh.el:142:           (full-body (mapconcat #'org-babel-chomp
3307 lisp//org-babel-tangle.el:163:      (insert (format "\n%s\n" (org-babel-chomp body)))
3308 lisp//org-babel.el:362:                  (org-babel-chomp (match-string 2 arg)))
3309 lisp//org-babel.el:698:(defun org-babel-chomp (string &optional regexp)
3310 lisp//org-babel.el:707:  "Like `org-babel-chomp' only it runs on both the front and back of the string"
3311 lisp//org-babel.el:708:  (org-babel-chomp (org-babel-reverse-string
3312 lisp//org-babel.el:709:                    (org-babel-chomp (org-babel-reverse-string string) regexp)) regexp))
3313 #+end_example
3315 ** DONE LoB is not populated on startup
3316    org-babel-library-of-babel is nil for me on startup. I have to
3317    evaluate the [[file:lisp/org-babel-lob.el::][org-babel-lob-ingest]] line manually.
3319 #+tblname: R-plot-example-data
3320 | 1 |  2 |
3321 | 2 |  4 |
3322 | 3 |  9 |
3323 | 4 | 16 |
3324 | 5 | 25 |
3326 #+lob: R-plot(data=R-plot-example-data)
3330    I've added a section to [[file:lisp/org-babel-init.el][org-babel-init.el]] which will load the
3331    library of babel on startup.
3333    Note that this needs to be done in [[file:lisp/org-babel-init.el][org-babel-init.el]] rather than in
3334    [[file:lisp/org-babel-lob.el][org-babel-lob.el]], not entirely sure why, something about it being
3335    required directly?
3337    Also, I'm now having the file closed if it wasn't being visited by
3338    a buffer before being loaded.
3340 ** DONE use new merge function [[file:lisp/org-babel-ref.el::t%20nil%20org%20combine%20plists%20args%20nil][here]]?
3341    And at other occurrences of org-combine-plists?
3342 ** DONE creeping blank lines
3343    There's still inappropriate addition of blank lines in some circumstances. 
3345    Hmm, it's a bit confusing. It's to do with o-b-remove-result. LoB
3346    removes the entire (#+resname and result) and starts from scratch,
3347    whereas #+begin_src only removes the result. I haven't worked out
3348    what the correct fix is yet. Maybe the right thing to do is to make
3349    sure that those functions (o-b-remove-result et al.) are neutral
3350    with respect to newlines. Sounds easy, but...
3352    E.g.
3354 #+begin_src sh
3356 #+end_src
3360    Compare the results of
3361 #+lob: adder(a=5, b=17)
3363 #+resname: python-add(a=5, b=17)
3364 : 22
3365 --------------------------------
3367 #+begin_src python
3369 #+end_src
3371 #+resname:
3372 : 23
3373 ---------------------
3374 ** DONE #+srcname arg parsing bug
3375 #+srcname: test-zz(arg=adder(a=1, b=1))
3376 #+begin_src python 
3378 #+end_src
3380 #+resname: test-zz
3381 : 2
3384 #+srcname: test-zz-nasty(arg=adder(a=adder(a=19,b=adder(a=5,b=2)),b=adder(a=adder(a=1,b=9),b=adder(a=1,b=3))))
3385 #+begin_src python 
3387 #+end_src
3389 #+resname: test-zz-nasty
3390 : 40
3394 #+srcname: test-zz-hdr-arg
3395 #+begin_src python :var arg=adder(a=adder(a=19,b=adder(a=5,b=2)),b=adder(a=adder(a=1,b=9),b=adder(a=1,b=3)))
3397 #+end_src
3399 #+resname:
3400 : 40
3402 ** DONE Fix nested evaluation and default args
3403    The current parser / evaluator fails with greater levels of nested
3404    function block calls (example below).
3406 *** Initial statement [ded]
3407     If we want to overcome this I think we'd have to redesign some of
3408     the evaluation mechanism. Seeing as we are also facing issues like
3409     dealing with default argument values, and seeing as we now know
3410     how we want the library of babel to behave in addition to the
3411     source blocks, now might be a good time to think about this. It
3412     would be nice to do the full thing at some point, but otoh we may
3413     not consider it a massive priority.
3414     
3415     AIui, there are two stages: (i) construct a parse tree, and (ii)
3416     evaluate it and return the value at the root. In the parse tree
3417     each node represents an unevaluated value (either a literal value
3418     or a reference). Node v may have descendent nodes, which represent
3419     values upon which node v's evaluation depends. Once that tree is
3420     constructed, then we evaluate the nodes from the tips towards the
3421     root (a post-order traversal).
3423     [This would also provide a solution for concatenating the STDOUTs
3424     of called blocks, which is a [[*allow%20output%20mode%20to%20return%20stdout%20as%20value][task below]]; we concatenate them in
3425     whatever order the traversal is done in.]
3427     In addition to the variable references (i.e. daughter nodes), each
3428     node would contain the information needed to evaluate that node
3429     (e.g. lang body). Then we would pass a function postorder over the
3430     tree which would call o-b-execute-src-block at each node, finally
3431     returning the value at the root.
3433     Fwiw I made a very tentative small start at stubbing this out in
3434     org-babel-call.el in the 'evaluation' branch. And I've made a start
3435     at sketching a parsing algorithm below.
3436 **** Parse tree algorithm
3437     Seeing as we're just trying to parse a string like
3438     f(a=1,b=g(c=2,d=3)) it shouldn't be too hard. But of course there
3439     are 'proper' parsers written in elisp out there,
3440     e.g. [[http://cedet.sourceforge.net/semantic.shtml][Semantic]]. Perhaps we can find what we need -- our syntax is
3441     pretty much the same as python and R isn't it?
3443     Or, a complete hack, but maybe it would be we easy to transform it
3444     to XML and then parse that with some existing tool?
3445     
3446     But if we're doing it ourselves, something very vaguely like this?
3447     (I'm sure there're lots of problems with this)
3449 #+srcname: org-babel-call-parse(call)
3450 #+begin_src python 
3451   ## we are currently reading a reference name: the name of the root function
3452   whereami = "refname"
3453   node = root = Node()
3454   for c in call_string:
3455       if c == '(':
3456           varnum = 0
3457           whereami = "varname" # now we're reading a variable name
3458       if c == '=':
3459           new = Node()
3460           node.daughters = [node.daughters, new]
3461           new.parent = node
3462           node = new
3463           whereami = "refname"
3464       if c == ',':
3465           whereami = "varname"
3466           varnum += 1
3467       elif c == ')':
3468           node = node.parent
3469       elif c == ' ':
3470           pass
3471       else:
3472           if whereami = "varname":
3473               node.varnames[varnum] += c
3474           elif whereami = "refname":
3475               node.name += c
3476 #+end_src
3477     
3478 *** discussion / investigation
3479 I believe that this issue should be addressed as a bug rather than as
3480 a point for new development.   The code in [[file:lisp/org-babel-ref.el][org-babel-ref.el]] already
3481 resolves variable references in a recursive manner which *should* work
3482 in the same manner regardless of the depth of the number of nested
3483 function calls.  This recursive evaluation has the effect of
3484 implicitly constructing the parse tree that your are thinking of
3485 constructing explicitly.
3487 Through using some of the commented out debugging statements in
3488 [[file:lisp/org-babel-ref.el][org-babel-ref.el]] I have looked at what may be going wrong in the
3489 current evaluation setup, and it seems that nested variables are being
3490 set using the =:var= header argument, and these variables are being
3491 overridden by the *default* variables which are being entered through
3492 the new functional syntax (see the demonstration header below).
3494 I believe that once this bug is fixed we should be back to fully
3495 resolution of nested arguments.  We should capture this functionality
3496 in a test to ensure that we continue to test it as we move forward.  I
3497 can take a look at implementing this once I get a chance.
3499 Looks like the problem may be in [[file:lisp/org-babel.el::defun%20org%20babel%20merge%20params%20rest%20plists][org-babel-merge-params]], which seems
3500 to be trampling the provided :vars values.
3502 Nope, now it seems that we are actually looking up the results line,
3503 rather than the actual source-code block, which would make sense given
3504 that the results-line will return the same value regardless of the
3505 arguments supplied.  See the output of this [[file:lisp/org-babel-ref.el::message%20type%20S%20type%20debugging][debug-statement]].
3507 We need to be sure that we don't read from a =#+resname:= line when we
3508 have a non-nil set of arguments.
3510 **** demonstration
3511 After uncommenting the debugging statements located [[file:lisp/org-babel-ref.el::message%20format%20first%20second%20S%20S%20new%20refere%20new%20referent%20debugging][here]] and more
3512 importantly [[file:lisp/org-babel-ref.el::message%20nested%20args%20S%20args%20debugging][here]], we can see that the current reference code does
3513 evaluate the references correctly, and it uses the =:var= header
3514 argument to set =a=8=, however the default variables specified using
3515 the functional syntax in =adder(a=3, b=2)= is overriding this
3516 specification.
3518 ***** doesn't work with functional syntax
3520 #+srcname: adder-func(a=3, b=2)
3521 #+begin_src python 
3522 a + b
3523 #+end_src
3525 #+resname: adder-func
3526 : 5
3528 #+srcname: after-adder-func(arg=adder-func(a=8))
3529 #+begin_src python 
3531 #+end_src
3533 #+resname: after-adder-func
3534 : 5
3536 ***** still does work with =:var= syntax
3538 so it looks like regardless of the syntax used we're not overriding
3539 the default argument values.
3541 #+srcname: adder-header
3542 #+begin_src python :var a=3 :var b=2
3543 a + b
3544 #+end_src
3546 #+resname: adder-header
3547 : 5
3549 #+srcname: after-adder-header
3550 #+begin_src python :var arg=adder-header(a=8, b=0)
3552 #+end_src
3554 #+resname: after-adder-header
3555 : 5
3557 *** Set of test cases
3558 **** Both defaults provided in definition
3559 #+srcname: adder1(a=10,b=20)
3560 #+begin_src python
3562 #+end_src
3564 #+resname: adder1
3565 : 30
3566 ****** DONE Rely on defaults
3567 #+lob: adder1()
3569 #+resname: adder1()
3570 : 30
3572 ## should be 30
3573 ## OK, but
3574 ******* DONE empty parens () not recognised as lob call
3575         E.g. remove spaces between parens above
3577         updated [[file:lisp/org-babel-lob.el::defvar%20org%20babel%20lob%20one%20liner%20regexp%20lob%20t%20n%20n%20t%20n][org-babel-lob-one-liner-regexp]]
3579 ****** DONE One supplied, one default
3580 #+lob: adder1(a=0)
3582 #+resname: adder1(a=0)
3583 : 20
3585 ## should be 20
3587 #+lob: adder1(b=0)
3589 #+resname: adder1(b=0)
3590 ## should be 10
3591 : 10
3593 ****** DONE Both supplied
3594 #+lob: adder1(a=1,b=2)
3596 #+resname: adder1(a=1,b=2)
3598 : 3
3599 **** One arg lacks default in definition
3600 #+srcname: adder2(a=10,b)
3601 #+begin_src python
3603 #+end_src
3604 ****** DEFERRED Rely on defaults (one of which is missing)
3605 #+lob: adder2( )
3607 [no output]
3609 ## should be error: b has no default
3611 Maybe we should let the programming language handle this case.  For
3612 example python spits out an error in the =#+lob= line above.  Maybe
3613 rather than catching these errors our-selves we should raise an error
3614 when the source-block returns an error.  I'll propose a [[* PROPOSED raise elisp error when source-blocks return errors][task]] for this
3615 idea, I'm not sure how/if it would work...
3617 ****** DEFERRED Default over-ridden
3618 #+lob: adder2(a=1)
3620 See the above [[* DEFERRED Rely on defaults (one of which is missing)][deferred]] and the new proposed [[* PROPOSED raise elisp error when source-blocks return errors][task]], I think it may be
3621 more flexible to allow the source block language to handle the error.
3623 [no output ]
3624 ## should be error: b has no default
3626 ****** DONE Missing default supplied
3627 #+lob: adder2(b=1)
3629 #+resname: adder2(b=1)
3630 : 11
3633 ## should be 11
3634 ## OK
3636 ****** DONE One over-ridden, one supplied
3637 #+lob: adder2(a=1,b=2)
3639 #+resname: adder2(a=1,b=2)
3640 : 3
3642 ## should be 3
3644 *** Example that fails
3645     
3646 #+srcname: adder(a=0, b=99)
3647 #+begin_src python 
3649 #+end_src
3653 #+srcname: one()
3654 #+begin_src python
3656 #+end_src
3658 **** nesting
3659 #+srcname: level-one-nesting()
3660 #+begin_src python :var arg=adder(a=one(),b=one())
3662 #+end_src
3664 #+resname: level-one-nesting
3666 : nil
3668 #+srcname: level-one-nesting()
3669 #+begin_src python :var arg=adder(a=adder(a=one(),b=one()),b=adder(a=one(),b=one()))
3671 #+end_src
3673 #+resname:
3674 : 12
3676 *** DONE deeply nested arguments still fails
3678 #+srcname: deeply-nested-args-bug
3679 #+begin_src python :var arg=adder(a=adder(a=one(),b=one()),b=adder(a=one(),b=one()))
3681 #+end_src
3683 #+resname:
3684 : 4
3686 **** Used to result in this error
3687 : supplied params=nil
3688 : new-refere="adder", new-referent="a=adder(a=one(),b=one()),b=adder(a=one(),b=one())"
3689 : args=((:var . "a=adder(a=one()") (:var . "b=one())") (:var . "b=adder(a=one()") (:var . "b=one())"))
3690 : type=source-block
3691 : supplied params=((:var . "a=adder(a=one()") (:var . "b=one())") (:var . "b=adder(a=one()") (:var . "b=one())"))
3692 : new-refere="adder", new-referent="a=one("
3693 : args=((:var . "a=one("))
3694 : type=source-block
3695 : supplied params=((:var . "a=one("))
3696 : reference 'one(' not found in this buffer
3698 Need to change the regexp in [[file:lisp/org-babel-ref.el::assign%20any%20arguments%20to%20pass%20to%20source%20block][org-babel-ref-resolve-reference]] so that
3699 it only matches when the parenthesis are balanced.  Maybe look at
3700 [[http://www.gnu.org/software/emacs/elisp/html_node/List-Motion.html][this]].
3702 *** DONE Still some problems with deeply nested arguments and defaults
3703 **** sandbox
3704 **** DONE Parsing / defaults bug
3705      Try inserting a space between 'a=0,' and 'b=0' and comparing results
3706 #+srcname: parsing-defaults-bug()
3707 #+begin_src python :var arg=adder(a=adder(a=0,b=0))
3709 #+end_src
3711 #+resname: parsing-defaults-bug
3713 : 99
3715 #+srcname: deeply-nested-args-bug-orig()
3716 #+begin_src python :var arg=adder(a=adder(a=one(),b=one()),b=adder(a=adder(a=3, b=4),b=one()))
3718 #+end_src
3720 #+resname: deeply-nested-args-bug-orig
3722 : 10
3725 **** DONE Nesting problem II
3726      This generates parsing errors
3728      Fixed: c2bef96b7f644c05be5a38cad6ad1d28723533aa
3730 #+srcname: deeply-nested-args-bug-II-1()
3731 #+begin_src python :var arg=adder(a=adder(a=one(),b=adder(a=2,b=4)))
3733 #+end_src
3735 #+resname: deeply-nested-args-bug-II-1
3737 : 106
3739 #+srcname: deeply-nested-args-bug-II-original()
3740 #+begin_src python :var arg=adder(a=adder(a=one(),b=one()),b=adder(a=one(),b=adder(a=1,b=4)))
3742 #+end_src
3744 #+resname: deeply-nested-args-bug-II-original
3745 : 8
3749 **** DONE Why does this give 8?
3750      It was picking up the wrong definition of adder
3751 #+srcname: deeply-nested-args-bug-2()
3752 #+begin_src python :var arg=adder(a=adder(a=one(),b=one()))
3754 #+end_src
3756 #+resname: deeply-nested-args-bug-2
3758 : 101
3760 **** DONE Problem with empty argument list
3761      This gives empty list with () and 'no output' with ( )
3763      I think this is OK now.
3765 #+srcname: x
3766 #+begin_src python :var arg=adder( )
3768 #+end_src
3770 #+resname:
3771 : 99
3773 #+srcname: deeply-nested-args-bug-orig()
3774 #+begin_src python :var arg=adder(a=adder(a=one(),b=one()),b=adder(a=adder(a=3, b=4),b=one()))
3776 #+end_src
3778 #+resname: deeply-nested-args-bug-orig
3780 : 10
3783 **** DONE Nesting problem II
3784      This generates parsing errors
3786      Fixed: c2bef96b7f644c05be5a38cad6ad1d28723533aa
3788 #+srcname: deeply-nested-args-bug-II-1()
3789 #+begin_src python :var arg=adder(a=adder(a=one(),b=adder(a=2,b=4)))
3791 #+end_src
3793 #+resname: deeply-nested-args-bug-II-1
3795 : 106
3797 #+srcname: deeply-nested-args-bug-II-original()
3798 #+begin_src python :var arg=adder(a=adder(a=one(),b=one()),b=adder(a=one(),b=adder(a=1,b=4)))
3800 #+end_src
3802 #+resname: deeply-nested-args-bug-II-original
3803 : 8
3807 **** DONE Why does this give 8?
3808      It was picking up the wrong definition of adder
3809 #+srcname: deeply-nested-args-bug-2()
3810 #+begin_src python :var arg=adder(a=adder(a=one(),b=one()))
3812 #+end_src
3814 #+resname: deeply-nested-args-bug-2
3816 : 101
3818 **** DONE Problem with empty argument list
3819      This gives empty list with () and 'no output' with ( )
3821      I think this is OK now.
3823 #+srcname: x
3824 #+begin_src python :var arg=adder( )
3826 #+end_src
3828 #+resname:
3829 : 99
3857 #+srcname: test-zz(arg=adder(a=adder(a=19,b=adder(a=5,b=2)),b=adder(a=adder(a=1,b=9),b=adder(a=1,b=3))))
3858 #+begin_src python 
3860 #+end_src
3863 *** DONE Arg lacking default
3864    This would be good thing to address soon. I'm imagining that
3865    e.g. here, the 'caller' block would return the answer 30. I believe
3866    there's a few issues here: i.e. the naked 'a' without a reference
3867    is not understood; the default arg b=6 is not understood.
3869 #+srcname: adder-with-arg-lacking-default(a, b=6)
3870 #+begin_src python 
3872 #+end_src
3876 #+srcname: caller(var=adder-with-arg-lacking-default(a=24))
3877 #+begin_src python :results silent
3879 #+end_src
3881 ** DONE allow srcname to omit function call parentheses
3882    Someone needs to revisit those regexps. Is there an argument for
3883    moving some of the regexps used to match function calls into
3884    defvars? (i.e. in o-b.el and o-b-ref.el)
3886    This seems to work now. It still might be a good idea to separate
3887    out some of the key regexps into defvars at some point.
3889 #+srcname: omit-parens-test
3890 #+begin_src ruby :results output
3891 3.times {puts 'x'}
3892 #+end_src
3894 #+resname:
3895 : x
3896 : x
3897 : x
3899 ** DONE avoid stripping whitespace from output when :results output
3900    This may be partly solved by using o-b-chomp rather than o-b-trim
3901    in the o-b-LANG-evaluate functions.
3902 ** DEFERRED weird escaped characters in shell prompt break shell evaluation
3903    E.g. this doesn't work. Should the shell sessions set a sane prompt
3904    when they start up? Or is it a question of altering
3905    comint-prompt-regexp? Or altering org-babel regexps?
3906    
3907 #+begin_src sh   
3908    black=30 ; red=31 ; green=32 ; yellow=33 ; blue=34 ; magenta=35 ; cyan=36 ; white=37
3909    prompt_col=$red
3910    prompt_char='>'
3911    export PS1="\[\033[${prompt_col}m\]\w${prompt_char} \[\033[0m\]"
3912 #+end_src
3914    I just pushed a good amount of changes, could you see if your shell
3915    problems still exist?
3917    The problem's still there. Specifically, aIui, at [[file:lisp/langs/org-babel-sh.el::raw%20org%20babel%20comint%20with%20output%20buffer%20org%20babel%20sh%20eoe%20output%20nil%20insert%20full%20body%20comint%20send%20input%20nil%20t][this line]] of
3918    org-babel-sh.el, raw gets the value
3920 ("" "\e[0m Sun Jun 14 19:26:24 EDT 2009\n" "\e[0m org_babel_sh_eoe\n" "\e[0m ")
3922    and therefore (member org-babel-sh-eoe-output ...) fails
3924    I think that `comint-prompt-regexp' needs to be altered to match
3925    the shell prompt.  This shouldn't be too difficult to do by hand,
3926    using the `regexp-builder' command and should probably be part of
3927    the user's regular emacs init.  I can't think of a way for us to
3928    set this automatically, and we are SOL without a regexp to match
3929    the prompt.
3930 ** DONE function calls in #+srcname: refs
3931    
3932    My srcname references don't seem to be working for function
3933    calls. This needs fixing.
3934    
3935 #+srcname: called()
3936 #+begin_src python 
3938 #+end_src
3940 srcname function call doesn't work for calling a source block
3941 #+srcname: caller(var1=called())
3942 #+begin_src python
3943 var1
3944 #+end_src
3946 #+resname: caller
3947 : 59
3954 They do work for a simple reference
3955 #+srcname: caller2(var1=56)
3956 #+begin_src python 
3957 var1
3958 #+end_src
3960 #+resname: caller2
3961 : 59
3964 and they do work for :var header arg
3965 #+srcname: caller3
3966 #+begin_src python :var var1=called() 
3967 var1
3968 #+end_src
3970 #+resname:
3971 : 58
3972 ** DONE LoB: with output to buffer, not working in buffers other than library-of-babel.org
3973 *** Initial report
3974    I haven't fixed this yet. org-babel-ref-resolve-reference moves
3975    point around, inside a save-excursion. Somehow when it comes to
3976    inserting the results (after possible further recursive calls to
3977    org-babel-ref-resolve-reference), point hasn't gone back to the
3978    lob line.
3980 #+tblname: test-data
3981 | 1 |    1 |
3982 | 2 |   .5 |
3983 | 3 | .333 |
3985 #+lob: R-plot(data=test-data)
3987 #+lob: python-add(a=2, b=9)
3989 #+resname: python-add(a=2, b=9)
3990 : 11
3992 *** Now
3993     I think this got fixed in the bugfixes before merging results into master.
3995 ** DONE cursor movement when evaluating source blocks
3996    E.g. the pie chart example. Despite the save-window-excursion in
3997    org-babel-execute:R. (I never learned how to do this properly: org-R
3998    jumps all over the place...)
4000    I don't see this now [ded]
4002 ** DONE LoB: calls fail if reference has single character name
4003    commit 21d058869df1ff23f4f8cc26f63045ac9c0190e2
4004 **** This doesn't work
4005 #+lob: R-plot(data=X)
4007 #+tblname: X
4008 | 1 |     1 |
4009 | 2 |    .5 |
4010 | 3 | .3333 |
4011 | 4 |   .25 |
4012 | 5 |    .2 |
4013 | 6 | .1666 |
4015 **** But this is OK
4016 #+tblname: XX
4017 | 1 |     1 |
4018 | 2 |    .5 |
4019 | 3 | .3333 |
4020 | 4 |   .25 |
4021 | 5 |    .2 |
4022 | 6 | .1666 |
4024 #+lob: R-plot(data=XX)
4026 ** DONE make :results replace the default?
4027    I'm tending to think that appending results to pre-existing results
4028    creates mess, and that the cleaner `replace' option should be the
4029    default. E.g. when a source block creates an image, we would want
4030    that to be updated, rather than have a new one be added.
4031    
4032    I agree.
4034 ** DONE ruby evaluation not working under ubuntu emacs 23
4035    With emacs 23.0.91.1 on ubuntu, for C-h f run-ruby I have the
4036    following, which seems to conflict with [[file:lisp/langs/org-babel-ruby.el::let%20session%20buffer%20save%20window%20excursion%20run%20ruby%20nil%20session%20current%20buffer][this line]] in org-babel-ruby.el.
4038 #+begin_example
4039 run-ruby is an interactive compiled Lisp function.
4041 (run-ruby cmd)
4043 Run an inferior Ruby process, input and output via buffer *ruby*.
4044 If there is a process already running in `*ruby*', switch to that buffer.
4045 With argument, allows you to edit the command line (default is value
4046 of `ruby-program-name').  Runs the hooks `inferior-ruby-mode-hook'
4047 (after the `comint-mode-hook' is run).
4048 (Type C-h m in the process buffer for a list of commands.)
4049 #+end_example
4051    So, I may have a non-standard inf-ruby.el.  Here's my version of
4052    run-ruby.
4054 #+begin_example 
4055 run-ruby is an interactive Lisp function in `inf-ruby.el'.
4057 (run-ruby &optional COMMAND NAME)
4059 Run an inferior Ruby process, input and output via buffer *ruby*.
4060 If there is a process already running in `*ruby*', switch to that buffer.
4061 With argument, allows you to edit the command line (default is value
4062 of `ruby-program-name').  Runs the hooks `inferior-ruby-mode-hook'
4063 (after the `comint-mode-hook' is run).
4064 (Type C-h m in the process buffer for a list of commands.)
4065 #+end_example
4067    It seems we could either bundle my version of inf-ruby.el (as it's
4068    the newest).  Or we could change the use of `run-ruby' so that it
4069    is robust across multiple distributions.  I think I'd prefer the
4070    former, unless the older version of inf-ruby is actually bundled
4071    with emacs, in which case maybe we should go out of our way to
4072    support it.  Thoughts?
4074    I think for now I'll just include the latest [[file:util/inf-ruby.el][inf-ruby.el]] in the
4075    newly created utility directory.  I doubt anyone would have a
4076    problem using the latest version of this file.
4077 ** DONE test failing forcing vector results with =test-forced-vector-results= ruby code block
4078 Note that this only seems to happen the *second* time the test table
4079 is evaluated
4081 #+srcname: bug-trivial-vector
4082 #+begin_src emacs-lisp :results vector silent
4084 #+end_src
4086 #+srcname: bug-forced-vector-results
4087 #+begin_src ruby :var triv=test-trivial-vector :results silent
4088 triv.class.name
4089 #+end_src
4091 mysteriously this seems to be fixed...
4092 ** DONE defunct R sessions
4093 Sometimes an old R session will turn defunct, and newly inserted code
4094 will not be evaluated (leading to a hang).
4096 This seems to be fixed by using `inferior-ess-send-input' rather than `comint-send-input'.
4097 ** DONE ruby fails on first call to non-default session
4099 #+srcname: bug-new-session
4100 #+begin_src ruby :session is-new
4101 :patton
4102 #+end_src
4104 ** DONE when reading results from =#+resname= line
4106 Errors when trying to read from resname lines.
4108 #+resname: bug-in-resname
4109 : 8
4111 #+srcname: bug-in-resname-reader
4112 #+begin_src emacs-lisp :var buggy=bug-in-resname() :results silent
4113 buggy
4114 #+end_src
4116 ** DONE R-code broke on "org-babel" rename
4118 #+srcname: bug-R-babels
4119 #+begin_src R 
4120 8 * 2
4121 #+end_src
4123 ** DONE error on trivial R results
4125 So I know it's generally not a good idea to squash error without
4126 handling them, but in this case the error almost always means that
4127 there was no file contents to be read by =org-table-import=, so I
4128 think it's ok.
4130 #+srcname: bug-trivial-r1
4131 #+begin_src R :results replace
4132 pie(c(1, 2, 3), labels = c(1, 2, 3))
4133 #+end_src
4135 #+srcname: bug-trivial-r2
4136 #+begin_src R :results replace
4138 #+end_src
4140 #+resname: bug-trivial-r2
4141 : 8
4143 #+srcname: bug-trivial-r3
4144 #+begin_src R :results replace
4145 c(1,2,3)
4146 #+end_src
4148 #+resname: bug-trivial-r3
4149 | 1 |
4150 | 2 |
4151 | 3 |
4153 ** DONE ruby new variable creation (multi-line ruby blocks)
4154 Actually it looks like we were dropping all but the last line.
4156 #+srcname: multi-line-ruby-test
4157 #+begin_src ruby :var table=bug-numerical-table :results replace
4158 total = 0
4159 table.each{|n| total += n}
4160 total/table.size
4161 #+end_src
4163 #+resname:
4164 : 2
4166 ** DONE R code execution seems to choke on certain inputs
4167 Currently the R code seems to work on vertical (but not landscape)
4168 tables
4170 #+srcname: little-fake
4171 #+begin_src emacs-lisp 
4172 "schulte"
4173 #+end_src
4176 #+begin_src R :var num=little-fake
4178 #+end_src
4180 #+resname:
4181 : schulte
4183 #+srcname: set-debug-on-error
4184 #+begin_src emacs-lisp :results silent
4185 (setq debug-on-error t)
4186 #+end_src
4188 #+srcname: bug-numerical-table
4189 #+begin_src emacs-lisp :results silent
4190 '(1 2 3)
4191 #+end_src
4196 #+srcname: bug-R-number-evaluation
4197 #+begin_src R :var table=bug-numerical-table
4198 mean(mean(table))
4199 #+end_src
4201 #+resname:
4202 : 2
4206 #+tblname: bug-vert-table
4207 | 1 |
4208 | 2 |
4209 | 3 |
4211 #+srcname: bug-R-vertical-table
4212 #+begin_src R :var table=bug-vert-table :results silent
4213 mean(table)
4214 #+end_src
4216 ** DONE org bug/request: prevent certain org behaviour within code blocks
4217    E.g. [[]] gets recognised as a link (when there's text inside the
4218    brackets). This is bad for R code at least, and more generally
4219    could be argued to be inappropriate. Is it difficult to get org to
4220    ignore text in code blocks? [DED]
4221    
4222    I believe Carsten addressed this recently on the mailing list with
4223    the comment that it was indeed a difficult issue.  I believe this
4224    may be one area where we could wait for an upstream (org-mode) fix.
4226    [Dan] Carsten has fixed this now in the core.
4228 ** DONE with :results replace, non-table output doesn't replace table output
4229    And vice versa. E.g. Try this first with table and then with len(table) [DED]
4230 #+begin_src python :var table=sandbox :results replace
4231 table
4232 #+end_src
4234 | 1 |         2 | 3 |
4235 | 4 | "schulte" | 6 |
4236 : 2
4238 Yes, this is certainly a problem.  I fear that if we begin replacing
4239 anything immediately following a source block (regardless of whether
4240 it matches the type of our current results) we may accidentally delete
4241 hand written portions of the user's org-mode buffer.
4243 I think that the best solution here would be to actually start
4244 labeling results with a line that looks something like...
4246 #+results: name
4248 This would have a couple of benefits...
4249 1) we wouldn't have to worry about possibly deleting non-results
4250    (which is currently an issue)
4251 2) we could reliably replace results even if there are different types
4252 3) we could reference the results of a source-code block in variable
4253    definitions, which would be useful if for example we don't wish to
4254    re-run a source-block every time because it is long-running.
4256 Thoughts?  If no-one objects, I believe I will implement the labeling
4257 of results.
4259 ** DONE extra quotes for nested string
4260 Well R appears to be reading the tables without issue...
4262 these *should* be quoted
4263 #+srcname: ls
4264 #+begin_src sh :results replace
4266 #+end_src
4268 | "COPYING"          |
4269 | "README.markdown"  |
4270 | "block"            |
4271 | "examples.org"     |
4272 | "existing_tools"   |
4273 | "intro.org"        |
4274 | "org-babel"          |
4275 | "rorg.org"         |
4276 | "test-export.html" |
4277 | "test-export.org"  |
4279 #+srcname: test-quotes
4280 #+begin_src ruby :var tab=ls
4281 tab[1][0]
4282 #+end_src
4284 : README.markdown
4286 #+srcname: test-quotes
4287 #+begin_src R :var tab=ls
4288 as.matrix(tab[2,])
4289 #+end_src
4291 : README.markdown
4293 ** DONE simple ruby arrays not working
4295 As an example eval the following.  Adding a line to test
4297 #+tblname: simple-ruby-array
4298 | 3 | 4 | 5 |
4300 #+srcname: ruby-array-test
4301 #+begin_src ruby :var ar = simple-ruby-array :results silent
4302 ar.first.first
4303 #+end_src
4305 ** DONE space trailing language name
4306 fix regexp so it works when there's a space trailing the language name
4308 #+srcname: test-trailing-space
4309 #+begin_src ruby 
4310 :schulte
4311 #+end_src
4313 ** DONE Args out of range error
4314    
4315 The following block resulted in the error below [DED]. It ran without
4316 error directly in the shell.
4317 #+begin_src sh
4318 cd ~/work/genopca
4319 for platf in ill aff ; do
4320     for pop in CEU YRI ASI ; do
4321         rm -f $platf/hapmap-genos-$pop-all $platf/hapmap-rs-all
4322         cat $platf/hapmap-genos-$pop-* > $platf/hapmap-genos-$pop-all
4323         cat $platf/hapmap-rs-* > $platf/hapmap-rs-all
4324     done
4325 done
4326 #+end_src
4327   
4328  executing source block with sh...
4329 finished executing source block
4330 string-equal: Args out of range: "", -1, 0
4332 the error =string-equal: Args out of range: "", -1, 0= looks like what
4333 used to be output when the block returned an empty results string.
4334 This should be fixed in the current version, you should now see the
4335 following message =no result returned by source block=.
4337 ** DONE ruby arrays not recognized as such
4339 Something is wrong in [[file:lisp/org-babel-script.el]] related to the
4340 recognition of ruby arrays as such.
4342 #+begin_src ruby :results replace
4343 [1, 2, 3, 4]
4344 #+end_src
4346 | 1 | 2 | 3 | 4 |
4348 #+begin_src python :results replace
4349 [1, 2, 3, 4]
4350 #+end_src
4352 | 1 | 2 | 3 | 4 |
4353 ** REJECTED elisp reference fails for literal number
4354    That's a bug in Dan's elisp, not in org-babel.
4355 #+srcname: elisp-test(a=4)
4356 #+begin_src emacs-lisp 
4357 (message a)
4358 #+end_src
4364 : 30
4367 * Tests
4368 Evaluate all the cells in this table for a comprehensive test of the
4369 org-babel functionality.
4371 *Note*: if you have customized =org-babel-default-header-args= then some
4372 of these tests may fail.
4374 #+TBLNAME: org-babel-tests
4375 | functionality           | block                      | arg |    expected |     results | pass |
4376 |-------------------------+----------------------------+-----+-------------+-------------+------|
4377 | basic evaluation        |                            |     |             |             | pass |
4378 |-------------------------+----------------------------+-----+-------------+-------------+------|
4379 | emacs lisp              | basic-elisp                |     |           5 |           5 | pass |
4380 | shell                   | basic-shell                |     |           6 |           6 | pass |
4381 | ruby                    | basic-ruby                 |     |   org-babel |   org-babel | pass |
4382 | python                  | basic-python               |     | hello world | hello world | pass |
4383 | R                       | basic-R                    |     |          13 |          13 | pass |
4384 |-------------------------+----------------------------+-----+-------------+-------------+------|
4385 | tables                  |                            |     |             |             | pass |
4386 |-------------------------+----------------------------+-----+-------------+-------------+------|
4387 | emacs lisp              | table-elisp                |     |           3 |           3 | pass |
4388 | ruby                    | table-ruby                 |     |       1-2-3 |       1-2-3 | pass |
4389 | python                  | table-python               |     |           5 |           5 | pass |
4390 | R                       | table-R                    |     |         3.5 |         3.5 | pass |
4391 | R: col names in R       | table-R-colnames           |     |          -3 |          -3 | pass |
4392 | R: col names in org     | table-R-colnames-org       |     |         169 |         169 | pass |
4393 |-------------------------+----------------------------+-----+-------------+-------------+------|
4394 | source block references |                            |     |             |             | pass |
4395 |-------------------------+----------------------------+-----+-------------+-------------+------|
4396 | all languages           | chained-ref-last           |     |       Array |       Array | pass |
4397 |-------------------------+----------------------------+-----+-------------+-------------+------|
4398 | source block functions  |                            |     |             |             | pass |
4399 |-------------------------+----------------------------+-----+-------------+-------------+------|
4400 | emacs lisp              | defun-fibb                 |     |       fibbd |       fibbd | pass |
4401 | run over                | Fibonacci                  |   0 |           1 |           1 | pass |
4402 | a                       | Fibonacci                  |   1 |           1 |           1 | pass |
4403 | variety                 | Fibonacci                  |   2 |           2 |           2 | pass |
4404 | of                      | Fibonacci                  |   3 |           3 |           3 | pass |
4405 | different               | Fibonacci                  |   4 |           5 |           5 | pass |
4406 | arguments               | Fibonacci                  |   5 |           8 |           8 | pass |
4407 |-------------------------+----------------------------+-----+-------------+-------------+------|
4408 | bugs and tasks          |                            |     |             |             | pass |
4409 |-------------------------+----------------------------+-----+-------------+-------------+------|
4410 | simple ruby arrays      | ruby-array-test            |     |           3 |           3 | pass |
4411 | R number evaluation     | bug-R-number-evaluation    |     |           2 |           2 | pass |
4412 | multi-line ruby blocks  | multi-line-ruby-test       |     |           2 |           2 | pass |
4413 | forcing vector results  | test-forced-vector-results |     |       Array |       Array | pass |
4414 | deeply nested arguments | deeply-nested-args-bug     |     |           4 |           4 | pass |
4415 |-------------------------+----------------------------+-----+-------------+-------------+------|
4416 | sessions                |                            |     |             |             | pass |
4417 |-------------------------+----------------------------+-----+-------------+-------------+------|
4418 | set ruby session        | set-ruby-session-var       |     |        :set |        :set | pass |
4419 | get from ruby session   | get-ruby-session-var       |     |           3 |           3 | pass |
4420 | set python session      | set-python-session-var     |     |         set |         set | pass |
4421 | get from python session | get-python-session-var     |     |           4 |           4 | pass |
4422 | set R session           | set-R-session-var          |     |         set |         set | pass |
4423 | get from R session      | get-R-session-var          |     |           5 |           5 | pass |
4424 #+TBLFM: $5='(if (= (length $3) 1) (progn (message (format "running %S" '(sbe $2 (n $3)))) (sbe $2 (n $3))) (sbe $2))::$6='(if (string= $4 $5) "pass" (format "expected %S but was %S" $4 $5))
4425 #+TBLFM: $5=""::$6=""
4428 The second TBLFM line (followed by replacing '[]' with '') can be used
4429 to blank out the table results, in the absence of a better method.
4431 ** basic tests
4433 #+srcname: basic-elisp
4434 #+begin_src emacs-lisp :results silent
4435 (+ 1 4)
4436 #+end_src
4439 #+srcname: basic-shell
4440 #+begin_src sh :results silent
4441 expr 1 + 5
4442 #+end_src
4445 #+srcname: date-simple
4446 #+begin_src sh :results silent
4447 date
4448 #+end_src
4450 #+srcname: basic-ruby
4451 #+begin_src ruby :results silent
4452 "org-babel"
4453 #+end_src
4456 #+srcname: basic-python
4457 #+begin_src python :results silent
4458 'hello world'
4459 #+end_src
4462 #+srcname: basic-R
4463 #+begin_src R :results silent
4464 b <- 9
4465 b + 4
4466 #+end_src
4469 ** read tables
4471 #+tblname: test-table
4472 | 1 | 2 | 3 |
4473 | 4 | 5 | 6 |
4475 #+tblname: test-table-colnames
4476 | var1 | var2 | var3 |
4477 |------+------+------|
4478 |    1 |   22 |   13 |
4479 |   41 |   55 |   67 |
4481 #+srcname: table-elisp
4482 #+begin_src emacs-lisp :results silent :var table=test-table
4483 (length (car table))
4484 #+end_src
4487 #+srcname: table-ruby
4488 #+begin_src ruby :results silent :var table=test-table
4489 table.first.join("-")
4490 #+end_src
4493 #+srcname: table-python
4494 #+begin_src python :var table=test-table
4495 table[1][1]
4496 #+end_src
4498 #+srcname: table-R(table=test-table)
4499 #+begin_src R
4500 mean(mean(table))
4501 #+end_src
4503 #+srcname: table-R-colnames(table=test-table-colnames)
4504 #+begin_src R :results silent
4505 sum(table$var2 - table$var3)
4506 #+end_src
4508 #+srcname: R-square(x=default-name-doesnt-exist)
4509 #+begin_src R :colnames t
4511 #+end_src
4513 This should return 169. The fact that R is able to use the column name
4514 to index the data frame (x$var3) proves that a table with column names
4515 (a header row) has been recognised as input for the R-square function
4516 block, and that the R-square block has output an elisp table with
4517 column names, and that the colnames have again been recognised when
4518 creating the R variables in this block.
4519 #+srcname: table-R-colnames-org(x = R-square(x=test-table-colnames))
4520 #+begin_src R
4521 x$var3[1]
4522 #+end_src
4527 ** references
4529 Lets pass a references through all of our languages...
4531 Lets start by reversing the table from the previous examples
4533 #+srcname: chained-ref-first
4534 #+begin_src python :var table = test-table
4535 table.reverse()
4536 table
4537 #+end_src
4539 #+resname: chained-ref-first
4540 | 4 | 5 | 6 |
4541 | 1 | 2 | 3 |
4543 Take the first part of the list
4545 #+srcname: chained-ref-second
4546 #+begin_src R :var table = chained-ref-first
4547 table[1]
4548 #+end_src
4550 #+resname: chained-ref-second
4551 | 4 |
4552 | 1 |
4554 Turn the numbers into string
4556 #+srcname: chained-ref-third
4557 #+begin_src emacs-lisp :var table = chained-ref-second
4558 (mapcar (lambda (el) (format "%S" el)) table)
4559 #+end_src
4561 #+resname: chained-ref-third
4562 | "(4)" | "(1)" |
4564 and Check that it is still a list
4566 #+srcname: chained-ref-last
4567 #+begin_src ruby :var table=chained-ref-third
4568 table.class.name
4569 #+end_src
4572 ** source blocks as functions
4574 #+srcname: defun-fibb
4575 #+begin_src emacs-lisp :results silent
4576 (defun fibbd (n) (if (< n 2) 1 (+ (fibbd (- n 1)) (fibbd (- n 2)))))
4577 #+end_src
4580 #+srcname: fibonacci
4581 #+begin_src emacs-lisp :results silent :var n=7
4582 (fibbd n)
4583 #+end_src
4591 ** sbe tests (these don't seem to be working...)
4592 Testing the insertion of results into org-mode tables.
4594 #+srcname: multi-line-output
4595 #+begin_src ruby :results replace
4596 "the first line ends here
4599      and this is the second one
4601 even a third"
4602 #+end_src
4604 #+resname:
4605 : the first line ends here\n\n\n     and this is the second one\n\neven a third
4607 #+srcname: multi-line-error
4608 #+begin_src ruby :results replace
4609 raise "oh nooooooooooo"
4610 #+end_src
4612 #+resname:
4613 : oh nooooooooooo
4615 | the first line ends here... | -:5: warning: parenthesize argument(s) for future version... |
4616 #+TBLFM: $1='(sbe "multi-line-output")::$2='(sbe "multi-line-error")
4618 ** forcing results types tests
4620 #+srcname: test-trivial-vector
4621 #+begin_src emacs-lisp :results vector silent
4623 #+end_src
4625 #+srcname: test-forced-vector-results
4626 #+begin_src ruby :var triv=test-trivial-vector :results silent
4627 triv.class.name
4628 #+end_src
4630 ** sessions
4632 #+srcname: set-ruby-session-var
4633 #+begin_src ruby :session :results silent
4634 var = [1, 2, 3]
4635 :set
4636 #+end_src
4638 #+srcname: get-ruby-session-var
4639 #+begin_src ruby :session :results silent
4640 var.size
4641 #+end_src
4643 #+srcname: set-python-session-var
4644 #+begin_src python :session
4645 var=4
4646 'set'
4647 #+end_src
4649 #+srcname: get-python-session-var
4650 #+begin_src python :session
4652 #+end_src
4654 #+srcname: set-R-session-var
4655 #+begin_src R :session
4656 a <- 5
4657 'set'
4658 #+end_src
4660 #+srcname: get-R-session-var
4661 #+begin_src R :session
4663 #+end_src
4666 * Sandbox
4667   :PROPERTIES:
4668   :CUSTOM_ID: sandbox
4669   :END:
4670 To run these examples evaluate [[file:lisp/org-babel-init.el][org-babel-init.el]]
4672 ** org-babel.el beginning functionality
4674 #+begin_src sh  :results replace
4675 date
4676 #+end_src
4678 #+resname:
4679 : Sun Jul  5 18:54:39 EDT 2009
4681 #+begin_src ruby
4682 Time.now
4683 #+end_src
4685 #+resname:
4686 : Sun Jul 05 18:54:35 -0400 2009
4688 #+begin_src python
4689 "Hello World"
4690 #+end_src
4692 #+resname:
4693 : Hello World
4696 ** org-babel-R
4698 #+begin_src R :results replace
4699 a <- 9
4700 b <- 16
4701 a + b
4702 #+end_src
4704 #+resname:
4705 : 25
4707 #+begin_src R
4708 hist(rgamma(20,3,3))
4709 #+end_src
4713 ** org-babel plays with tables
4714 Alright, this should demonstrate both the ability of org-babel to read
4715 tables into a lisp source code block, and to then convert the results
4716 of the source code block into an org table.  It's using the classic
4717 "lisp is elegant" demonstration transpose function.  To try this
4718 out...
4720 1. evaluate [[file:lisp/org-babel-init.el]] to load org-babel and friends
4721 2. evaluate the transpose definition =\C-c\\C-c= on the beginning of
4722    the source block
4723 3. evaluate the next source code block, this should read in the table
4724    because of the =:var table=previous=, then transpose the table, and
4725    finally it should insert the transposed table into the buffer
4726    immediately following the block
4728 *** Emacs lisp
4730 #+begin_src emacs-lisp :results silent
4731 (defun transpose (table)
4732   (apply #'mapcar* #'list table))
4733 #+end_src
4736 #+TBLNAME: sandbox
4737 | 1 |       2 | 3 |
4738 | 4 | schulte | 6 |
4740 #+begin_src emacs-lisp :var table=sandbox :results replace
4741 (transpose table)
4742 #+end_src
4745 #+begin_src emacs-lisp
4746 '(1 2 3 4 5)
4747 #+end_src
4749 #+resname:
4750 | 1 | 2 | 3 | 4 | 5 |
4752 *** Ruby and Python
4754 #+begin_src ruby :var table=sandbox :results replace
4755 table.first.join(" - ")
4756 #+end_src
4758 #+resname:
4759 : 1 - 2 - 3
4761 #+begin_src python :var table=sandbox
4762 table[0]
4763 #+end_src
4766 #+begin_src ruby :var table=sandbox :results replace
4767 table
4768 #+end_src
4770 #+resname:
4771 : [[1, 2, 3], [4, "schulte", 6]]
4774 | 1 |         2 | 3 |
4775 | 4 | "schulte" | 6 |
4777 #+begin_src python :var table=sandbox :results replace
4778 len(table)
4779 #+end_src
4781 : 2
4783 | "__add__" | "__class__" | "__contains__" | "__delattr__" | "__delitem__" | "__delslice__" | "__doc__" | "__eq__" | "__format__" | "__ge__" | "__getattribute__" | "__getitem__" | "__getslice__" | "__gt__" | "__hash__" | "__iadd__" | "__imul__" | "__init__" | "__iter__" | "__le__" | "__len__" | "__lt__" | "__mul__" | "__ne__" | "__new__" | "__reduce__" | "__reduce_ex__" | "__repr__" | "__reversed__" | "__rmul__" | "__setattr__" | "__setitem__" | "__setslice__" | "__sizeof__" | "__str__" | "__subclasshook__" | "append" | "count" | "extend" | "index" | "insert" | "pop" | "remove" | "reverse" | "sort" |
4785 *** (sandbox table) R
4787 #+TBLNAME: sandbox_r
4788 | 1 |       2 | 3 |
4789 | 4 | schulte | 6 |
4791 #+begin_src R :results replace
4792 x <- c(rnorm(10, mean=-3, sd=1), rnorm(10, mean=3, sd=1))
4794 #+end_src
4796 | -3.35473133869346 |
4797 |    -2.45714878661 |
4798 | -3.32819924928633 |
4799 | -2.97310212756194 |
4800 | -2.09640758369576 |
4801 | -5.06054014378736 |
4802 | -2.20713700711221 |
4803 | -1.37618039712037 |
4804 | -1.95839385821742 |
4805 | -3.90407396475502 |
4806 |  2.51168071590226 |
4807 |  3.96753011570494 |
4808 |  3.31793212627865 |
4809 |  1.99829753972341 |
4810 |  4.00403686419829 |
4811 |  4.63723764452927 |
4812 |  3.94636744261313 |
4813 |  3.58355906547775 |
4814 |  3.01563442274226 |
4815 |   1.7634976849927 |
4817 #+begin_src R var tabel=sandbox_r :results replace
4818 tabel
4819 #+end_src
4821 | 1 |         2 | 3 |
4822 | 4 | "schulte" | 6 |
4824 *** shell
4825 Now shell commands are converted to tables using =org-table-import=
4826 and if these tables are non-trivial (i.e. have multiple elements) then
4827 they are imported as org-mode tables...
4829 #+begin_src sh :results replace
4830 ls -l
4831 #+end_src
4833 | "total"      | 208 | ""    | ""    |    "" |   "" | "" | ""                |
4834 | "-rw-r--r--" |   1 | "dan" | "dan" |    57 | 2009 | 15 | "block"           |
4835 | "-rw-r--r--" |   1 | "dan" | "dan" | 35147 | 2009 | 15 | "COPYING"         |
4836 | "-rw-r--r--" |   1 | "dan" | "dan" |   722 | 2009 | 18 | "examples.org"    |
4837 | "drwxr-xr-x" |   4 | "dan" | "dan" |  4096 | 2009 | 19 | "existing_tools"  |
4838 | "-rw-r--r--" |   1 | "dan" | "dan" |  2207 | 2009 | 14 | "intro.org"       |
4839 | "drwxr-xr-x" |   2 | "dan" | "dan" |  4096 | 2009 | 18 | "org-babel"         |
4840 | "-rw-r--r--" |   1 | "dan" | "dan" |   277 | 2009 | 20 | "README.markdown" |
4841 | "-rw-r--r--" |   1 | "dan" | "dan" | 11837 | 2009 | 18 | "rorg.html"       |
4842 | "-rw-r--r--" |   1 | "dan" | "dan" | 61829 | 2009 | 19 | "#rorg.org#"      |
4843 | "-rw-r--r--" |   1 | "dan" | "dan" | 60190 | 2009 | 19 | "rorg.org"        |
4844 | "-rw-r--r--" |   1 | "dan" | "dan" |   972 | 2009 | 11 | "test-export.org" |
4847 ** silent evaluation
4849 #+begin_src ruby
4850 :im_the_results
4851 #+end_src
4853 : :im_the_results
4855 #+begin_src ruby :results silent
4856 :im_the_results
4857 #+end_src
4859 #+begin_src ruby :results replace
4860 :im_the_results_
4861 #+end_src
4863 : :im_the_results_
4866 ** (sandbox) referencing other source blocks
4867 Doing this in emacs-lisp first because it's trivial to convert
4868 emacs-lisp results to and from emacs-lisp.
4870 *** emacs lisp source reference
4871 This first example performs a calculation in the first source block
4872 named =top=, the results of this calculation are then saved into the
4873 variable =first= by the header argument =:var first=top=, and it is
4874 used in the calculations of the second source block.
4876 #+SRCNAME: top
4877 #+begin_src emacs-lisp
4878 (+ 4 2)
4879 #+end_src
4881 #+begin_src emacs-lisp :var first=top :results replace
4882 (* first 3)
4883 #+end_src
4885 : 18
4887 This example is the same as the previous only the variable being
4888 passed through is a table rather than a number.
4890 #+begin_src emacs-lisp :results silent
4891 (defun transpose (table)
4892   (apply #'mapcar* #'list table))
4893 #+end_src
4895 #+TBLNAME: top_table
4896 | 1 |       2 | 3 |
4897 | 4 | schulte | 6 |
4899 #+SRCNAME: second_src_example
4900 #+begin_src emacs-lisp :var table=top_table
4901 (transpose table)
4902 #+end_src
4904 #+begin_src emacs-lisp :var table=second_src_example :results replace
4905 (transpose table)
4906 #+end_src
4908 | 1 |         2 | 3 |
4909 | 4 | "schulte" | 6 |
4910 *** ruby python
4911 Now working for ruby
4913 #+srcname: start
4914 #+begin_src ruby
4916 #+end_src
4918 #+begin_src ruby :var other=start :results replace
4919 2 * other
4920 #+end_src
4922 and for python
4924 #+SRCNAME: start_two
4925 #+begin_src python
4927 #+end_src
4929 #+begin_src python :var another=start_two :results replace
4930 another*3
4931 #+end_src
4933 *** mixed languages
4934 Since all variables are converted into Emacs Lisp it is no problem to
4935 reference variables specified in another language.
4937 #+SRCNAME: ruby-block
4938 #+begin_src ruby
4940 #+end_src
4942 #+SRCNAME: lisp_block
4943 #+begin_src emacs-lisp :var ruby-variable=ruby-block
4944 (* ruby-variable 8)
4945 #+end_src
4947 #+begin_src python :var lisp_var=lisp_block
4948 lisp_var + 4
4949 #+end_src
4951 : 20
4953 *** R
4955 #+srcname: first_r
4956 #+begin_src R :results replace
4957 a <- 9
4959 #+end_src
4961 : 9
4963 #+begin_src R :var other=first_r :results replace
4964 other + 2
4965 #+end_src
4967 : 11
4970 ** (sandbox) selective export
4972 For exportation tests and examples see (including exportation of
4973 inline source code blocks) [[file:test-export.org]]
4976 ** (sandbox) source blocks as functions
4978 #+srcname: default
4979 #+begin_src emacs-lisp :results silent
4981 #+end_src
4983 #+srcname: triple
4984 #+begin_src emacs-lisp :var n=default :results replace
4985 (* 3 n)
4986 #+end_src
4988 : 15
4990 #+begin_src emacs-lisp :var result=triple(n=3, m=98) :results replace
4991 result
4992 #+end_src
4994 : 294
4996 The following just demonstrates the ability to assign variables to
4997 literal values, which was not implemented until recently.
4999 #+begin_src ruby :var num="eric" :results replace
5000 num+" schulte "
5001 #+end_src
5003 : "eric schulte "
5006 ** (sandbox) inline source blocks
5008 This is an inline source code block src_ruby{1 + 6}.  And another
5009 source block with text output src_emacs-lisp{"eric"}.
5011 This is an inline source code block with header
5012 arguments.  src_ruby[:var n=fibbd( n = 0 )]{n}
5015 ** (sandbox) integration w/org tables
5017 #+begin_src emacs-lisp :results silent
5018 (defun fibbd (n) (if (< n 2) 1 (+ (fibbd (- n 1)) (fibbd (- n 2)))))
5019 #+end_src
5021 #+srcname: fibbd
5022 #+begin_src emacs-lisp :var n=4 :results silent
5023 (fibbd n)
5024 #+end_src
5026 #+begin_src emacs-lisp :results silent
5027 (mapcar #'fibbd '(0 1 2 3 4 5 6 7 8))
5028 #+end_src
5030 Something is not working here.  The function `sbe ' works fine when
5031 called from outside of the table (see the source block below), but
5032 produces an error when called from inside the table.  I think there
5033 must be some narrowing going on during intra-table emacs-lisp
5034 evaluation.
5036 | original | fibbd |
5037 |----------+-------|
5038 |        0 |     1 |
5039 |        1 |     1 |
5040 |        2 |     2 |
5041 |        3 |     3 |
5042 |        4 |     5 |
5043 |        5 |     8 |
5044 |        6 |    13 |
5045 |        7 |    21 |
5046 |        8 |    34 |
5047 |        9 |    55 |
5048 #+TBLFM: $2='(sbe "fibbd" (n $1))
5050 silent-result
5052 #+begin_src emacs-lisp :results silent
5053 (sbe 'fibbd (n "8"))
5054 #+end_src
5057 * Buffer Dictionary
5058  LocalWords:  DBlocks dblocks org-babel el eric fontification