Rodrigo Leite
Rodrigo Leite

Reputation: 596

How do I generate source code from an org mode table?

I'm trying to figure out a way to move my i3wm configuration file to an org-mode file. I have a table with keybindings and what command they should execute, and I would like to generate the appropriate source code from it.

Example:

| Keybinding            | Command              | Action                   |
|-----------------------+----------------------+--------------------------|
| {{{mod}}} + Return    | i3-sensible-terminal | Opens a new terminal     |
| {{{mod}}} + Shift + q | kill                 | Kills the focused window |

should generate

bindsym {{{mod}}}+Return exec --no-startup-id i3-sensible-terminal ;; Opens a new Terminal
bindsym {{{mod}}}+Shift+q exec --no-startup-id kill ;; Kills the focused window

is such thing possible?

Upvotes: 1

Views: 184

Answers (1)

NickD
NickD

Reputation: 6422

You can name the table and pass it as an argument to a source block and have the source block iterate over rows. Here's an implementation in python:

#+NAME: commands
| Keybinding            | Command              | Action                   |
|-----------------------+----------------------+--------------------------|
| {{{mod}}} + Return    | i3-sensible-terminal | Opens a new terminal     |
| {{{mod}}} + Shift + q | kill                 | Kills the focused window |

#+begin_src python :var cmds=commands :results output raw
for row in cmds:
    print("bindsym {} exec --no-startup-id {}  ;; {}".format(row[0].replace(' ', ''), row[1], row[2]))
#+end_src

Here I assumed that the spaces in the first column should be eliminated, rather than quoting the string, but you can easily modify that.

And here are the results of running the above source block:

#+RESULTS:
bindsym {{{mod}}}+Return exec --no-startup-id i3-sensible-terminal  ;; Opens a new terminal
bindsym {{{mod}}}+Shift+q exec --no-startup-id kill  ;; Kills the focused window

Upvotes: 6

Related Questions