Separating code blocks from results in org-mode

| categories: org-mode | tags: | View Comments

I often put my code blocks right where I need them in my org documents. It usually has a section explaining what I want to do, then the code block that implements the idea, following by the output. Sometimes the code blocks are long, however, and it might be desirable for that code to be in an appendix. 1

Org-mode enables this with #+CALL. For example, I have a function named circle-area in the appendix of this post that calculates the area of a circle given its radius. The function is "named" by a line like this:

#+name: function-name

I can use the function like this:

#+CALL: circle-area(1)
3.14159265359

That is pretty nice. You can separate the code out from the main document. You still have to put the #+CALL: line in though. It may be appropriate to put a call inline with your text. If you add the following sentence, and put your cursor on the callcircle-area and press C-c C-c, the output is put in verbatim markers right after it.

The area of a circle with unit radius is call_circle-area(1).

The area of a circle with unit radius is 3.14159265359.

Here is another interesting way to do it. We can specify a named results block. Let us consider another function named hello-block that prints output. We specify a named results block like this:

#+RESULTS: function-name

Now, whenever you execute that block, the results will get put where this line is like this.

hello John

These could be useful approaches to making the "top" of your document cleaner, with less code in it. The code of course is still in the document, but at the end, in an appendix for example. This kind of separation might make it a little harder to find the code, and to reevaluate it,2 but it might improve the readability for others.

1 Appendix of code

1.1 Area of a circle

import numpy as np
return np.pi * r**2

1.2 Hello function

print 'hello ' + name

Footnotes:

1

I know I can pretty conveniently collapse a code block by pressing tab on the header. Sometimes that is not enough.

2

It is not much harder, C-s will let you search for the named block. I do not know if there are nice convenient navigation commands for this.

Copyright (C) 2014 by John Kitchin. See the License for information about copying.

org-mode source

Org-mode version = 8.2.5h

blog comments powered by Disqus