Is it possible to call Org Babel code blocks from other code blocks?
Asked Answered
V

2

7

I have a number of Org Babel code blocks in my Library of Babel that I call sequentially quite often.

Is it possible to make an Org Babel code block that calls these other code blocks in order?

Villanovan answered 29/3, 2013 at 20:57 Comment(1)
orgmode.org/manual/Noweb-Reference-Syntax.htmlWowser
D
6

Yes, you can. Simply use :var where the parameter is the result of another block execution.

#+name: clean
#+begin_src ...
...
#+end_src

#+name: plot
#+begin_src :var data=clean
...
#+end_src
Drews answered 30/3, 2013 at 21:55 Comment(3)
This is the answer - I want to make a new code block that takes all code blocks I want to evaluate as :var arguments. Then when I call that new code block, all the arguments get evaluated too. Thanks!Villanovan
Is it possible to define a code block such that the contents are put in var, not the results of executing it?Blodget
To answer my own question: It is – just use #+name: ex\n#+begin_example xml instead of begin_src and then later you can #+begin_src sh :var f=ex\necho "$f" | xmllint --format -\n#end_srcBlodget
U
5

Yes, I have several org-babel files where I do that. Here is one way to do it:

#+srcname: foo
#+begin_src python :exports code :tangle yes
  def foo():
      print "I'm foo()"
#+end_src

#+name: bar
#+begin_src python :exports code :tangle yes
  def bar():
      foo()
      print "I'm bar()'"
#+end_src

#+srcname: main
#+begin_src python :exports code :tangle yes
  foo()
  bar()
#+end_src

The output of this is a file that looks like this:

def foo():
    print "I'm foo()"

def bar():
    foo()
    print "I'm bar()'"

foo()
bar()

If the code in the org file is in a different order than what you want to generate, you can use the noweb tags to generate the code file in the order you want, like so:

#+name: bar
#+begin_src python :noweb-ref bar :tangle no
  def bar():
      foo()
      print "I'm bar()'"

#+end_src

#+srcname: foo
#+begin_src python :noweb-ref foo :tangle no
  def foo():
      print "I'm foo()"

#+end_src


#+begin_src python :noweb tangle :tangle yes

  <<foo>>
  <<bar>>

  foo()
  bar()
#+end_src

The output of tangling this is:

def foo():
    print "I'm foo()"

def bar():
    foo()
    print "I'm bar()'"

foo()
bar()
Unearthly answered 30/3, 2013 at 14:53 Comment(1)
In the non-noweb way, if foo is a function need argument, how can I call foo with argument and export the result?Maggie

© 2022 - 2024 — McMap. All rights reserved.