4

I want to create an org file with two sections, that reads in that order but "tangles" first the second section. For example, if my org file is

* Generic section

#+BEGIN_SRC python :tangle yes
print(a+4)
#+END_SRC

* Preparation

#+BEGIN_SRC python :tangle yes
a = 4
#+END_SRC

the tangled output should be

a = 4
print(a+4)

One option would be using noweb syntax to input the first code block into the second, and avoid tangling the first block, but in the generated pdf I would have a codeblock with the full code and another one with only the second line. The pdf should be something like

Generic section

print(a+4)

Preparation

a = 4

How can I achieve this result?

2 Answers 2

7

The key was to use the :noweb options. One of them, strip-export, let's you add a snippet to the code when tangling but hiding it in the document. Other option is tangle, which is similar but exports to the pdf a reference like <<imports>>.

This is the org file that creates the desired behaivour:

* Generic section

#+BEGIN_SRC python :noweb strip-export :tangle yes
<<stuff_that_goes_on_top>>
print(a+4)
#+END_SRC

* Preparation

#+NAME: stuff_that_goes_on_top
#+BEGIN_SRC python :tangle no
a = 4
#+END_SRC
1

I would try to craft the source code blocks to be separate entities on themselves. You could tangle them to different files and import the blocks from python

* Generic section

#+BEGIN_SRC python :results output :tangle generic.py
from preparation import a
print(a+4)
#+END_SRC

#+RESULTS:
: 8

* Preparation

#+BEGIN_SRC python :tangle preparation.py
a = 4
#+END_SRC

If you run M-x org-babel-tangle, the two blocks will be tangled into their .py files. Then you can enter the first block and hit C-c C-c to execute it. The first block will import the code from the tangled file of the second block and run it properly.

Then, when you export the file to PDF the blocks will appear in the order you have written them without duplicating the code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.