1

Is it possible to program the export in org-mode in the following way?

Say you'd like to export some org-mode text in latex or html but you'd like to program a kind of limited text loop with an increasing index, something like (with some invented pseudo-code with a novel "for-export" bloc)

#+begin_src for-export i=1..3
hello number $i
#+end_src

would export into

hello number 1
hello number 2
hello number 3

Is there anything in org-mode that allows us to make this? In one or another form?

Many thanks.

2
  • 1
    You could write some elisp to do that. Take a look at orgmode.org/manual/Macro-Replacement.html#Macro-Replacement.
    – aadcg
    Commented Sep 27, 2021 at 13:07
  • 1
    You mean a single exported document? Or multiple ones each with a different hello number version? If the first, why can't you loop inside the block e.g with a shell source block and a shell for loop?
    – NickD
    Commented Sep 27, 2021 at 13:23

1 Answer 1

4

I don't think you can do exactly what you want. But there are a few options that come close.

If you don't want the source block included in your output, you can do this with the following block:

#+begin_src bash :exports results :results verbatim
for i in 1 2 3
do
echo hello number $i
done
#+end_src

This will generate:

#+RESULTS:
: hello number 1
: hello number 2
: hello number 3

This uses a bash script, but you can use any language you like. Setting :exports results in the header suppresses the source block from your export. Depending on your intent, you may also want to use :results output raw, or otherwise configure the presentation of the resulting text.

You can't put the loop in the header, but you can assign the variables there:

#+begin_src bash :results verbatim :var vals="1 2 3"
for i in $vals
do
echo hello number $i
done
#+end_src

Another approach is to use noweb syntax. In this case, you define the code block you want to insert, here named 'loop', and then you refer to it at the location you want it to appear. This would allow you to reuse the same structure with different values throughout your document:

#+name: loop
#+begin_src bash :exports none :results raw :var vals="1 2 3"
for i in $vals
do
echo hello number $i
done
#+end_src

#+begin_src text :noweb yes 
<<loop(vals="1 2 3")>>
#+end_src

#+begin_src text :noweb yes
<<loop(vals="a b c")>>
#+end_src

#+begin_src text :noweb yes
<<loop(vals="apple orange banana")>>
#+end_src

This generates the following pdf:

enter image description here

For more details, see the org mode manual, Working with Source Code, NoWeb Reference Syntax,

1
  • Interesting! Moreover, I didn’t know the noweb syntax. This is super handy. Commented Sep 27, 2021 at 17:36

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.