Projects About AlBasmala
build status

org-special-block-extras: Org lists, drawn as Graphviz graphs

Article image
  

Ξ  

⭐ The code lives at github.com/alhassy/org-special-block-extras —star it, or discuss it there!

Every construct of a #+begin_graph block, on one page —itself a graph. Hover a node for how it reads, and click it for its section below:

﴾What You Write﴿
#+macro: tint lightyellow

#+begin_graph =#+begin_graph=, at a glance ---hover a node for how, click it for more :direction right
#+name: syntax style="rounded,filled" fillcolor={{{tint}}}
#+name: topic penwidth=2 :syntax:
#+node: fontname=Courier
#+edge: color=gray40 fontsize=10

+ [[*An outline is already a graph][#+begin_graph TITLE :KEY V]]

  An outline is already a graph: every item is a node, and nesting is an arc. The words before the first
  :KEY title the graph; each :KEY V is a Graphviz graph attribute, and :node.KEY V or :edge.KEY V a default.
  C-c C-c renders the block beneath it; C-u C-c C-c shows the dot it compiles to.
  + arcs :: [[*Arcs that speak: description lists][+ child]] :topic:

    Indenting an item under another draws an arc from the parent to the child.
    + labelled :: [[*Arcs that speak: description lists][a labelled arc]] :syntax:
      | label | + L :: child |

      A description term labels the arc into its item.
    + up the tree :: [[*Arcs that leave the tree: targets and links][an inline link]] :syntax:
      | label | [[T][L]] |

      A link to a node's id is an arc to it, labelled L; C-c C-o jumps to that node.
    + as a child :: [[*A child that is just a link: references][a reference]] :syntax:
      | label | + [[T][L :S:]] |

      A child that is nothing but a link is a reference: an arc to T, declared elsewhere, labelled L and
      styled by template S; both are optional.
    + from every mention :: [[*Radio targets: arcs from every mention][a radio target]] :syntax:
      | label | <<<NUMBER>>>, … |

      A radio target is a node, and every item mentioning NUMBER, in any case, has an arc to it.
  + names :: [[*Ids and labels][+ <<id>> label]] :topic:

    A target gives the node an id, for links to name, apart from its drawn label.
  + styles :: [[*Styling: one key-value syntax][| key | value |]] :topic:

    A two-column table beneath an item sets the node's Graphviz attributes; values need no quotes.
    + the arc in :: [[*An arc's table: :edge.KEY][| :edge.KEY | V |]] :syntax:

      An :edge.KEY row styles the arc from the parent, rather than the node.
    + everything :: [[*When the preamble outgrows the line][#+node: shape=box]] :syntax:

      The lines #+graph:, #+node:, and #+edge: style the graph, every node, every arc; by a table below,
      or KEY=VALUE pairs on the line. Within a subtree, they reach only that subtree.
    + side by side :: [[*Side by side: ordered lists and :@X: tags][+ node :@X:]] :syntax:

      Nodes tagged :@X: share a rank, :@start: the first, :@end: the last; ordered children, 1. 2. 3.,
      share one in the order written.
  + templates :: [[*Saying it once: templates][#+name: T k=v]] :topic:

    A named bundle of rows, on its name's line or in a table below; one outside every graph serves the
    whole buffer.
    + applied by :: [[*Saying it once: templates][+ node :T:]] :syntax:

      A trailing tag applies template T; explicit rows win. This very node wears :syntax:, defined above.
    + explained by :: [[*Legends: a glossary of templates][- MEANING :T:]] :syntax:

      In a container titled Legend, an item is a sample of T, captioned MEANING; see the legend here.
    + [-] progress :: [[*Checkboxes are templates][checkboxes]] :syntax:
      | label | [X] [-] [ ] |

      A checkbox applies template checked, partial, or unchecked; C-c C-c on it toggles it.
    + single values :: [[*Macros name single values][#+macro: M V]] :syntax:

      Names a single value; M in triple braces is V, anywhere in the block, as this graph's tint is.
  + labels :: [[*Markup makes rich labels][*bold* /italic/ =code=]] :topic:

    Org's markup, entities, and sub- and superscripts make a rich label; the id stays plain text.
    + lines :: [[*\\ breaks a line, :wrap fills][a label,]] \\ broken in two :syntax:

      A \\ breaks a label, mid-line too; :wrap N fills every label to N characters.
  + asides :: [[*Footnotes are tooltips][footnotes]] [fn::A footnote leaves the label and becomes the node's tooltip, as this one does.] :topic:
    | label | [fn::NOTE] |
    + longer :: [[*Notes are longer tooltips][a later paragraph]] :syntax:

      Every paragraph after an item's first is a note: its tooltip, as this one is. :notes inline draws
      notes beneath their labels instead.
    + clickable :: [[*Web links are URLs, image links are images][a web link]] :syntax:
      | label | [[https://…]] |

      A web or section link makes the node clickable, as every node here is; an image link draws the image.
  + layout :: [[*Containers draw boxes][+ TITLE :container:]] :topic:

    A container draws a box around its children, its members; its table styles the box.
    + records :: [[*Records: a table of fields][| a | table |]] :syntax:

      A table under an item is its label, a record of fields; a <<P>> cell is a port, which =[[node::P]]= reaches.
    + mind maps :: [[*Mind maps: :layout twopi][:layout twopi]] :syntax:

      A radial layout; :theme mindmap gives an arrowless one, radiating from the first item.
  + documents :: [[*#+name: and #+caption: make a figure][#+name: N]] :topic:

    Above the block, it makes a figure that =[[N]]= reaches, and #+caption: captions it; a :graph: tag on a
    heading makes its whole section a graph.
+ Legend :container:
  - a family of constructs :topic:
  - a construct             :syntax:
#+end_graph
﴾What You Get﴿

#+begin_graph , at a glance ---hover a node for how, click it for more Legend #+begin_graph TITLE :KEY V + child arcs + <<id>> label names | key | value | styles #+name: T k=v templates bold italic code labels [fn::NOTE] asides + TITLE :container: layout #+name: N documents + L :: child labelled [[T][L]] up the tree + [[T][L :S:]] as a child <<<NUMBER>>>, … from every mention | :edge.KEY | V | the arc in #+node: shape=box everything + node :@X: side by side + node :T: applied by - MEANING :T: explained by [X] [-] [ ] progress #+macro: M V single values a label, broken in two lines a later paragraph longer [[https://…]] clickable | a | table | records :layout twopi mind maps a family of constructs a construct

1. An outline is already a graph

Say we are showing a friend how 1 * 2 + 3 - 4 parses. On paper, we would draw a tree. In Org, we would reach for Graphviz —and write that tree a second time, in a second language:

digraph { "-" -> "+"; "-" -> 4; "+" -> "*"; "+" -> 3; "*" -> 1; "*" -> 2; }

Every arc there restates what an outline's indentation already says. So we write the outline, and let the outline be the graph. Each demo in this README shows what we write, then what we get:

﴾What You Write﴿
#+begin_graph
+ -
  + +
    + *
      + 1
      + 2
    + 3
  + 4
#+end_graph
﴾What You Get﴿
- + 4 * 3 1 2

That is the whole idea. A #+begin_graph block compiles the Org we already write —nested lists, two-column tables, links, tags, footnotes— into Graphviz dot. Nesting is an arc; the rest of this README refines that one sentence, one gap at a time, and every example stays with our running theme: parsing 1 * 2 + 3 - 4, from characters to tokens to trees.

A wide graph shrinks to fit the page; a click on it shows it full size, and another shrinks it back. LaTeX export draws it too, as a vector PDF by dot, shrunk likewise to fit the line.

1.1. Setup

org-graph-block extends org-special-block-extras:

(require 'org-special-block-extras)
(require 'org-graph-block)

Graphviz must be on our PATH: dot -V should work in a terminal.

1.2. A REPL for pictures

The fun part is how quickly a picture grows. Start with the seven tokens as a flat list, one item each, and press C-c C-c anywhere in the block: seven lonely nodes.

﴾What You Write﴿
#+begin_graph
+ 1
+ *
+ 2
+ +
+ 3
+ -
+ 4
#+end_graph
﴾What You Get﴿
1 * 2 + 3 - 4

Now M-S-<right> demotes an item, children and all —Org's own list editing— and another C-c C-c shows the new arc. A minute later, the flat list is the tree above. (Plain M-<right> demotes the item alone, leaving its children behind, as anywhere in Org.)

C-c C-c renders a PNG and links it beneath the block, under #+RESULTS:. The file's name is made up, unless :file picks one, as in #+begin_graph :file parse-tree.png. When the picture surprises us, C-u C-c C-c shows the generated dot instead; see Comforts while editing.

2. Arcs that speak: description lists

A bare arc says “related”, and little else. Explaining how our expression becomes a value, we want each arc to say how: the source text is lexed into tokens, which are parsed into a tree. Org's description list, - TERM :: DEFINITION, already attaches a word to an item; in a graph, that word sits on the arc into the item. Read left to right, the line is the arc —source, then lexed into, then tokens:

﴾What You Write﴿
#+begin_graph :direction right
+ ="1 * 2 + 3 - 4"=
  + lexed into :: tokens
    + parsed into :: syntax tree
      + evaluated to :: -1
      + compiled to :: bytecode
#+end_graph
﴾What You Get﴿
"1 * 2 + 3 - 4" tokens lexed into syntax tree parsed into -1 evaluated to bytecode compiled to

Two arcs between the same nodes are just two items. A parser both consumes its tokens and peeks at the next one, unconsumed; two arcs, one stream:

﴾What You Write﴿
#+begin_graph :direction right
+ parser
  + consumes :: token stream
  + /peeks at/ :: token stream
#+end_graph
﴾What You Get﴿
parser token stream consumes peeks at
  • The term may be marked up, as /peeks at/ is; it is then an HTML-like label.
  • It is the terse spelling of | :edge.label | consumes |, met below; an explicit :edge.label row wins.
  • A top-level item has no arc into it, so a term there is an error —except for a legend entry, met later.
  • As in Org, the :: needs whitespace on both sides: std::vector is a name, not a description, and so is BNF's expr ::= term, as ::= is not ::.

4. Ids and labels

Links make us name things, and a name wants to be short where a label wants to be clear. So every node has an id, which arcs and links name, and a label, which is drawn. By default both are the item's text, so these three items, spelling it out more and more, all declare one and the same node:

﴾What You Write﴿
#+begin_graph
+ expr

+ <<expr>> expr

+ <<expr>> expr
  | label | expr |
#+end_graph
﴾What You Get﴿
expr

When the two should differ, we set either one apart: a <<target>> gives the id, and a | label | row gives the label:

﴾What You Write﴿
#+begin_graph
+ <<expr>> Expression
  + <<term>> Term
    + factor
      | label | Factor: a number, or ( expr ) |
      + [[expr]]
+ Sum
  + [[term]]
#+end_graph
﴾What You Get﴿
Expression Term Factor: a number, or ( expr ) Sum
  • The id is the <<target>>, else the text —sans markup, links, footnotes, and tags. So [[1]] reaches + 1, and C-c C-o on it jumps there, sans a <<1>>; a target earns its place only when the id should differ from the text, or the text is long.
  • The label is the label row, else the text; markup makes it an HTML-like one.
  • Two items with one id are one node, so an item may appear twice to gain more children.

5. Styling: one key-value syntax

Out of the box, every node wears the same cream box; soon we want our tokens to read apart from our rules. Graphviz's attributes are key-value pairs, and Org's key-value syntax is the two-column table. So a table beneath an item styles that item: one syntax, from a single node up to the whole graph.

5.1. A node's table, and two kinds of keys

In a parse tree, the leaves are tokens, straight from the lexer; we tint them, so they read apart from the grammar's rules:

﴾What You Write﴿
#+begin_graph
+ term
  + factor
    + NUMBER 1
      | fillcolor | lightblue |
  + STAR
    | fillcolor | lightblue |
    | label     | *         |
  + factor
    + NUMBER 2
      | fillcolor | lightblue |
#+end_graph
﴾What You Get﴿
term factor * NUMBER 1 NUMBER 2

A plain key, such as fillcolor, is a Graphviz attribute of the node, passed straight through. We quote its value for you, so NUMBER 1, #00ff00, and x -> y all need no quotes; already-quoted values, and <…> HTML labels, are left alone.

A key prefixed :edge. is an attribute of an arc rather than the node; a leading colon is never a Graphviz attribute, so the two kinds cannot clash. Each is met in due time:

Key Meaning
:edge.KEY attribute KEY of the arc from the parent
:edge[T].KEY attribute KEY of this item's arc to T

Any other key —a misspelt colour, or :edge.colour— makes the table a record, so the typo shows in the picture, rather than silently vanishing.

5.2. An arc's table: :edge.KEY

An arc is drawn from parent to child, so the child's table is where it is styled: an :edge.KEY row there is attribute KEY of the arc into the item. Every attribute is its own row, exactly like a node's. Peeking consumes nothing, so its arc should look tentative:

﴾What You Write﴿
#+begin_graph :direction right
+ parser
  + consumes :: token stream
    | :edge.penwidth | 2 |
  + /peeks at/ :: token stream
    | :edge.style | dashed |
    | :edge.color | gray   |
#+end_graph
﴾What You Get﴿
parser token stream consumes peeks at

A reference is styled just the same; this is why an inline link graduates to one. The recursion back to expr is the arc that makes our grammar interesting, so we paint it:

﴾What You Write﴿
#+begin_graph
+ <<expr>> expression
  + term
    + factor
      + number
      + in parentheses :: [[expr]]
        | :edge.color     | red |
        | :edge.fontcolor | red |
#+end_graph
﴾What You Get﴿
expression term factor in parentheses number
  • A parallel arc is simply a second child, styled on its own; a KEY given twice is an error.
  • As in Org, an item's tables and directives may also follow its sub-items; they still belong to it.

5.3. The whole graph: the #+begingraph line

Small graphs deserve no preamble at all. So the header line takes the graph's title and any graph attribute; a parse tree laid out left to right, every node a circle, every arc grey:

﴾What You Write﴿
#+begin_graph How 1 * 2 + 3 - 4 parses :direction right :node.shape circle :edge.color grey
+ -
  + +
    + *
      + 1
      + 2
    + 3
  + 4
#+end_graph
﴾What You Get﴿
How 1 * 2 + 3 - 4 parses - + 4 * 3 1 2
  • The title, the words before the first :key, is the graph's label. Every graph is directed; a #+edge: :undirected: line makes all its arcs arrowless, an undirected graph.
  • :direction says which way arcs flow: down, the default, up, right, or left. It is Graphviz's rankdir ---TB, BT, LR, RL— spelled to be read; the header has no :rankdir, while #+graph: rankdir=LR keeps Graphviz's spelling.
  • :KEY V is a graph attribute; :node.KEY V and :edge.KEY V are node and edge defaults —the same KEY, node.KEY, edge.KEY spelling as table rows.
  • As on Org's own #+attr_html: lines, values need no quotes: :bgcolor #6c7086, :fontname Helvetica,Arial. A value with spaces does: :fontname "Helvetica Neue".
  • :file, :direction, :theme, :wrap, :notes, :unflatten, :unknown-tags, and :C-c_C-c belong to the block itself, never to Graphviz; each is met below. So do the Babel habits :exports and :results, which the block ignores; and :demo, which every block of this package understands.

5.4. When the preamble outgrows the line

A real graph's settings outgrow one line. Then #+graph:, #+node:, and #+edge: lines style the graph, every node, every arc —by KEY=VALUE pairs, as Graphviz's own edge [fontsize=10 color=gray] writes them, a value with spaces in double quotes, beside any :tags:— and they override the header. A drawer of any name, :SETTINGS: or :PALETTE:, folds them away with TAB, along with #+name: lines:

﴾What You Write﴿
#+begin_graph A compiler's front end
:SETTINGS:
#+graph: rankdir=LR fontname=Helvetica
#+node: style=rounded fontname=Helvetica
#+edge: fontsize=10 color=gray
:END:
+ characters
  + lexer :: tokens
    + parser :: syntax tree
#+end_graph
﴾What You Get﴿
A compiler's front end characters tokens lexer syntax tree parser

When the pairs outgrow their line, a two-column table below the keyword holds them instead, a row a key, as a node's table does; a line's pairs and a table below it join:

#+node:
| style     | rounded,filled |
| fillcolor | white          |
| fontname  | Helvetica      |
| fontcolor | gray30         |

Anything else on such a line is an error, rather than silently ignored. In Emacs, the keyword stands out, and so does each key that means something on its line —a graph's attribute on #+graph:, a node's on #+node:, an arc's on #+edge:, any on #+name:. A key left plain is one Graphviz does not know there, so a mistake shows before we export: a typo, as colour=red, or a misplaced key, as shape=box on an #+edge: line.

5.5. Subtrees inherit #+node: and #+edge:

Sometimes a style belongs to one branch, not the whole graph. A compiler folds constants: 1 * 2 is known before the program runs, so its whole subtree collapses to 2. We want that subtree shaded. Org's properties are inherited: a :PROPERTIES: drawer on a heading reaches its subheadings. So it is with an item's #+node: and #+edge: lines: they style every node and arc beneath the item, while the item itself keeps its own | key | value | rows:

﴾What You Write﴿
#+begin_graph Constant folding
+ -
  + +
    + *
      | xlabel | folds to 2 |
      #+node: fillcolor=lightgrey
      #+edge: style=dotted
      + 1
      + 2
    + 3
  + 4
#+end_graph
﴾What You Get﴿
Constant folding - + 4 * folds to 2 3 1 2

Above, * keeps its plain look —only what lies beneath it is shaded— just as a heading's own properties drawer is not one of its subheadings'. Graphviz scopes such defaults by an anonymous subgraph, which draws no box. A deeper item's lines override a shallower one's, as nested :PROPERTIES: do; a node first declared elsewhere keeps the defaults of where it was declared.

5.6. Themes: a look for every graph

Every graph wears a theme, beneath all its own attributes: by default creamsicle, after D2's theme 101, Orange Creamsicle —cream boxes, orange containers lightening as they nest, dark brown lines, and italic arc labels. :theme NAME picks another of org-graph-themes, and :theme nil wears Graphviz's own look:

﴾What You Write﴿
#+begin_graph :theme nil
+ Org
  + exports to :: HTML
#+end_graph
﴾What You Get﴿
Org HTML exports to

A theme is data, #+graph:, #+node:, and #+edge: lines' pairs, plus a fill per depth of node and of container; so a new one is a push away, and a new default a setq:

(push '(ink :node "shape=box fontname=Helvetica" :edge "color=gray30" :container-colors "#eeeeee #ffffff")
      org-graph-themes)
(setq org-graph-theme 'ink)

6. Saying it once: templates

A parse tree repeats itself: every token the same tint, every rule the same outline. Restating those rows at each leaf is how styles drift apart. So we name them once: a #+name: line is a reusable bundle of KEY=VALUE pairs —as #+edge: lines take them— and a tag applies it. On a headline, :work:urgent: classifies the entry; on an item, tags classify the node:

﴾What You Write﴿
#+begin_graph
#+name: token fillcolor=lightblue
#+name: rule style=bold

+ expr :rule:
  + term :rule:
    + NUMBER 1 :token:
    + * :token:
    + NUMBER 2 :token:
  + PLUS :token:
    | fillcolor | pink |
  + NUMBER 3 :token:
#+end_graph
﴾What You Get﴿
expr term PLUS NUMBER 3 NUMBER 1 * NUMBER 2

Several such lines in a row are several templates. A long template holds its rows in a table below its name instead, as a #+node: line may; a line's pairs and a table below it join. In Emacs, each template of a graph —its name's line, and the table below it— wears a background of its own, from org-graph-template-backgrounds, so where one ends and the next begins shows at a glance.

Explicit rows win over a template's, so PLUS above is pink. A line may carry several tags, :token:rule:, each a template, the earlier winning on a clash —save colors: when the tags' templates color it differently, a node shows every color as stripes, tinted, or wedges if it is round, and an arc as parallel lines; a node's own fillcolor or style turns the stripes off. The same rule reaches every other line a template could apply to; in a link's description, or a description term, a tag styles the arc:

Line What its tags style
+ NUMBER 1 :token: the node
+ [[expr][:recursion:]] the arc to the reference; so too a link's mid-text
+ reduces :rule-arc: :: expr :rule: the arc, by the description term's tags; the node, by its own
#+node: :token: every node; likewise #+edge: and #+graph:
#+name: keyword :token: the template keyword, which inherits token
﴾What You Write﴿
#+begin_graph
#+name: recursion color=red style=dashed
#+name: keyword fontname=Courier
#+node: :keyword:

+ <<expr>> expression
  + term
    + factor
      + in parentheses :recursion: :: [[expr]]
#+end_graph
﴾What You Get﴿
expression term factor in parentheses

6.1. Everyday tags every graph has

Some looks are wanted so often that every graph has them, sans a #+name::

Tags What they do
:dashed: :dotted: :bold: a node's outline, or an arc, so drawn
:bidirectional: :undirected: an arc's arrowheads: at either end, or none
:red: :orange: :yellow: :green: :teal: :blue: a node's outline and text, or an arc and its label, so colored
:purple: :magenta: :pink: :brown: :gray: :black: likewise
:small: :large: :size_N: a label at 10pt, 20pt, or N points
:database: :note: :folder: :component: :tab: a node drawn as a cylinder, a dog-eared page, a folder, a UML component, a tab
:circle: :diamond: :hexagon: :star: :oval: :rectangle: :text: a node so shaped; :text: is its label alone, sans outline
:person: :actor: a stick figure, in the node's color, above its label
﴾What You Write﴿
#+begin_graph :direction right
+ Musa :person:
  + writes :: Org :large:green:
    + exports to :dashed:bidirectional: :: HTML :blue:
    + [[Musa][:dotted:pink:]]
+ LaTeX :size_9:
#+end_graph
﴾What You Get﴿
Musa Org writes HTML exports to LaTeX

A style is a set of flags, so they join rather than override: :dashed:bold: is both, and a theme's fill survives :dashed:. Every other key overrides, the earlier tag winning, as ever. A fillcolor fills by itself: Graphviz would ignore it, silently, sans style=filled, so we add that flag for it.

In Emacs, each tag wears a color of its own name's —the same on its #+name: line— boxed as org-modern draws tags. So a typo stands out: :hott: differs in color from :hot:, as does a #+name: hott. A tag every graph has wears a face of its own, org-graph-builtin-tag.

6.2. Templates build on templates

A template inherits others by the tags on its name's line, as an item does: #+name: keyword :token: is a token, set in Courier. Its own rows win over those it inherits, as an item's explicit rows win over its tags':

﴾What You Write﴿
#+begin_graph
#+name: token fillcolor=lightblue
#+name: keyword :token: fontname=Courier

+ expression
  + if :keyword:
  + NUMBER :token:
#+end_graph
﴾What You Get﴿
expression if NUMBER
  • A template that, directly or not, inherits itself contributes nothing the second time.
  • A graph's own template sets only Graphviz attributes, and :edge.KEY ones; any other key, as a misspelt color, is an error.
  • A name that no #+name: defines gets a made-up template; see Prototype first, name later.

As with Babel's named tables, a #+name: table anywhere in the buffer, outside any graph, is a template every graph in the buffer may use; so a house style is named once per file rather than once per graph. A graph's own template of the same name wins, and a template inside one graph stays that graph's own:

﴾What You Write﴿
#+name: token fillcolor=lightblue

#+begin_graph Lexing
+ 1 * 2 :token:
  + NUMBER 1 :token:
  + STAR :token:
  + NUMBER 2 :token:
#+end_graph
﴾What You Get﴿
Lexing 1 * 2 NUMBER 1 STAR NUMBER 2

6.3. Which colons are tags

Tags are trailing :word: groups, exactly as on a headline; inside graph blocks, they wear Org's org-tag face, so they do not read as part of the label. Colons anywhere else are just text. A label that needs a trailing :word: of its own —Smalltalk's at:put: selector, say— puts it in =verbatim=, or in a | label | row:

﴾What You Write﴿
#+begin_graph Colons that are just text
#+name: faint style=dotted

+ Python's xs[1:2]
+ C++'s std::vector
+ BNF's expr ::= term
+ Smalltalk's =at:put:=
+ a token, read at 12:30 :faint:
#+end_graph
﴾What You Get﴿
Colons that are just text Python's xs[1:2] C++'s std::vector BNF's expr ::= term Smalltalk's at:put: a token, read at 12:30

Unlike Org's, our tags may be kebab-case: :rule-arc:. A tag is never part of the label, even one naming no template.

6.4. Prototype first, name later

While prototyping, we want shapes before names. So a tag naming no template gets a made-up one —a color, a shape, a font— the same at every use, so the tags read at a glance. A legend entry gives each its meaning; when the design settles, #+name: tables replace the made-up templates, one tag at a time:

﴾What You Write﴿
#+begin_graph Prototype first, name later
+ Legend :container:
  - a grammar rule :rule:
  - a token        :token:
  - a literal      :literal:
+ expr :rule:
  + term :rule:
    + NUMBER :token:
      + 1 :literal:
    + STAR :token:
  + PLUS :token:
#+end_graph
﴾What You Get﴿
Prototype first, name later Legend a grammar rule a token a literal expr term PLUS NUMBER STAR 1

The Nth unknown tag takes the Nth of org-graph-random-template-colors, -shapes, and -fonts, so renders are stable, and the first eight tags differ in every way.

6.5. Legends: a glossary of templates

A reader meeting blue boxes and red dashes asks what they mean. A legend answers: a glossary of templates. Within a container titled Legend, an item - MEANING :T: is a legend entry —a sample styled by template T, captioned MEANING— rather than a node; it reads as prose, a caption tagged with what it explains:

﴾What You Write﴿
#+begin_graph
#+name: token fillcolor=lightblue
#+name: recursion color=red style=dashed

+ <<expr>> expression
  + term
    + factor
      + NUMBER :token:
      + [[expr][:recursion:]]
+ Legend :container:
  - a token, from the lexer         :token:
  - /back/ to an enclosing rule     :recursion:
#+end_graph
﴾What You Get﴿
Legend expression term factor NUMBER a token, from the lexer back to an enclosing rule

Equally, - :T: :: MEANING is a legend entry anywhere in a graph, boxed or not. Org's own glossary is the description list: its term is the thing defined, here template T, and its description says what it means. An arc's label is a term too ---+ calls :: f labels the arc from the parent— yet a top-level item has no parent to arc from; so its term, being just tags, can only name templates, and the item is a legend entry. The two legends below are one and the same:

+ Legend :container:             + Legend :container:
  - a token        :token:          - :token: :: a token
  - a literal      :literal:        - :literal: :: a literal
  • The legend can never drift from the graph: change recursion, and its sample changes too.
  • A template that styles some arc in the graph —by a link's or a term's tags, or an #+edge: line— is sampled as an arc; any other, as a node.
  • …~, sample their templates together.
  • The sample drops constraint, which shapes the layout rather than the arc; and a backward arc's sample, dir=back, points forward, its arrow the arc's arrowtail, so a legend's arrows all point one way.
  • A legend stacks as a column: in a top-down graph its entries are chained by invisible arcs, and in a left-right one they share a rank already. An ordered legend, 1. 2. 3., is a row along the graph's foot instead: its entries share one rank, as ordered children do, beneath every other node. Graphviz's rankdir is the whole graph's, so a container cannot have one of its own; the chain does that job for a legend.
  • A legend's untitled boxes, + :container:, are legends too; so a legend of several ordered boxes is several rows, each beneath the one before —say, its arcs, then its nodes.
  • A legend tagged :@start:, + Legend :container:@start:, sits atop the graph rather than at its foot.

6.6. Checkboxes are templates

A checkbox says how far along a thing is; so a graph of tasks is just a checklist. Our calculator's compiler is half built. [X], [-], and [ ] apply the templates checked, partial, and unchecked, as a :checked: tag would; and C-c C-c on a checkbox toggles it, as Org's own does, then renders the graph:

﴾What You Write﴿
#+begin_graph Our calculator, so far
#+name: unchecked style=dashed

+ [-] compiler
  + [X] lexer
  + [X] parser
  + [-] type checker
  + [ ] code generator
#+end_graph
﴾What You Get﴿
Our calculator, so far compiler lexer parser type checker code generator

checked and partial default to green and orange, by org-graph-checkbox-templates; a graph's own #+name: template wins. A checkbox whose template exists nowhere, such as unchecked by default, styles nothing.

6.7. Macros name single values

Templates name whole bundles of rows; sometimes we want to name one value. A palette repeats itself, and Org's #+macro: names a value once, so {{{name}}} uses it —in a table, an item, a container's title, anywhere in the block:

﴾What You Write﴿
#+macro: token-color #a6e3a1

#+begin_graph Tokens, in one color
+ 1 * 2
  + NUMBER
    | color | #a6e3a1 |
  + STAR
    | :edge.color | #a6e3a1 |
    | color       | #a6e3a1 |
#+end_graph
﴾What You Get﴿
Tokens, in one color 1 * 2 NUMBER STAR

An undefined macro is an error. In similar spirit, inline src_LANG{…} blocks and call_NAME() calls run at export, as anywhere in Org, their results landing in the label; C-c C-c shows them as written.

7. Richer labels

A label is more than a name: we want a rule in bold, a token in monospace, a formula, a second line. Again, Org already has the syntax.

7.1. Markup makes rich labels

*bold*, /italic/, _underline_, +strike+, =code=, and ~pre~ in an item's text make its label an HTML-like one, while its id stays the plain text:

﴾What You Write﴿
#+begin_graph :direction right
+ *expr* is =term= /op/ =term=
  + _left_ operand :: =term=
  + +ambiguous+ :: /fixed by precedence/
#+end_graph
﴾What You Get﴿
expr is term op term term left operand fixed by precedence ambiguous

We escape &, <, >, and " for you. Graphviz has no way to tell =code= from ~pre~, so both are monospace. A record's cells keep their markup too. Names such as a_b, C++, and org-graph.el are not mistaken for markup.

7.2. Entities, scripts, and snippets

Org's entities are their characters, and braced sub- and superscripts are Graphviz's own; as under Org's #+options: ^:{}, an unbraced a_b stays text, so snake_case ids are safe. For whatever Org has no markup for, a @@dot:…@@ export snippet is raw label HTML; a snippet for any other backend vanishes:

﴾What You Write﴿
#+begin_graph :direction right
+ x^{2} \to pow(x, 2)
+ parse : String \to Tree \times String
+ token_stream
+ @@dot:<FONT COLOR="red">@@syntax error@@dot:</FONT>@@ at line 3
#+end_graph
﴾What You Get﴿
x 2 → pow(x, 2) parse : String → Tree × String token_stream syntax error at line 3
  • Timestamps, statistics cookies, and citations show as written; LaTeX fragments too, since Graphviz has no math.
  • Syntax that means nothing in a graph —a headline, a #+begin_quote, an unknown #+key:— is an error, rather than silently dropped. Comments, and footnote definitions, are fine.

7.3. \\ breaks a line, :wrap fills

A long label makes a wide node, and a wide node a sprawling graph. In Org, a \\ ending a line is a hard line break; in a graph, it breaks the node's label. Since a label seldom wants a literal \\, it may sit mid-line too, so a two-line node stays one terse line:

﴾What You Write﴿
#+begin_graph
+ parser
  + reports :: Unexpected token =)= \\ at line 3, column 7
  + *Recursive descent* \\
    one function per rule
  + every grammar \\ needs a lexer :: lexer
#+end_graph
﴾What You Get﴿
parser Unexpected token ) at line 3, column 7 reports Recursive descent one function per rule lexer every grammar needs a lexer

The label becomes an HTML-like one, as with markup; the id joins the lines with a space, so a node reached by a link usually wants a terse <<target>>. It is the one line break wherever a label is written: a description term, as above; a table value, | :edge.label | consumes \\ tokens |; a record's cell.

Breaking every long label by hand is tedious, though. #+begin_graph :wrap N fills node and arc labels to lines of N characters, so long item text needs no \\ at all; a label already broken by \\ stays as written:

﴾What You Write﴿
#+begin_graph :wrap 20 :direction right
+ A parser turns a flat stream of tokens into a tree
  + by repeatedly asking which grammar rule the next token can begin :: recursive descent
#+end_graph
﴾What You Get﴿
A parser turns a flat stream of tokens into a tree recursive descent by repeatedly asking which grammar rule the next token can begin

9. Layout: ranks, boxes, and records

Graphviz lays out the graph for us, and mostly well; but sometimes the layout says something the graph does not mean. Here is how we take the wheel back.

9.1. Side by side: ordered lists and :@X: tags

Look again at our parse tree: 1 * 2 + 3 - 4 subtracts 4 from the rest, never the other way around, yet nothing in an unordered list promises Graphviz will draw 4 on the right. Org's + - * bullets say “these things”; 1. 2. 3. say “first, second, third”. So ordered children sit side by side, on one rank, in the order written —Graphviz no longer reshuffles them to save a crossing:

﴾What You Write﴿
#+begin_graph
+ -
  1. +
     1. *
        1. 1
        2. 2
     2. 3
  2. 4
#+end_graph
﴾What You Get﴿
- + 4 * 3 1 2
  • An ordered top-level list, or one inside a container, shares a rank too; a lone ordered child gets no rank at all.

Nodes with no common parent share a rank when each wears a tag naming their group, :@X:, as Org's @home tags name a context. Every token is a leaf, so we line them all up, as the lexer emitted them:

﴾What You Write﴿
#+begin_graph
+ -
  + +
    + *
      + 1 :@tokens:
      + 2 :@tokens:
    + 3 :@tokens:
  + 4 :@tokens:
#+end_graph
﴾What You Get﴿
- + 4 * 3 1 2

Two group names are reserved: :@start: sets its nodes on the first rank, Graphviz's rank=min, and :@end: on the last, rank=max —the top and bottom rows, or, under :direction right, the left and right columns. A legend's samples, say, may all sit beneath the graph, :@end:.

  • An @ tag aligns a node; it names no template, so #+name: @X is an error, as is an @ tag on an arc or a container.
  • A group's name is a label, not a position: :@2: need not sit below :@1:.
  • A group reaching into a box sets newrank=true; else Graphviz would pull its nodes out of the box.

Under splines=curved, Graphviz drops the label of an arc between two nodes on one rank; so there, such an arc's label becomes an xlabel, which it still draws.

9.2. Containers draw boxes

Some nodes belong together —a compiler's front end, say— and a box around them says so. An item tagged :container: is such a box: its children are its members, inside it, rather than the targets of its arcs. Indentation says what is in the box, as D2's braces do, and an item folds with TAB, as ever. Its table styles the box, and its #+node: and #+edge: set defaults within it:

﴾What You Write﴿
#+begin_graph :direction right
+ compiler
  + Front end :container:
    | bgcolor | lightgrey |
    #+node: fillcolor=white
    + lexer
      + parser
        + :container:
          + syntax tree
          + symbol table
  + Back end :container:
    | style | dashed |
    + code generator
#+end_graph
﴾What You Get﴿
Front end Back end compiler lexer code generator parser syntax tree symbol table
  • A container is a child of its parent: above, compiler has an arc to Front end. An arc to or from a container lands on its first member, clipped at its border.
  • A reference among its children is an arc from the box, rather than a member; by way of example, + uses :: [[T]].
  • A box holds only the nodes declared within it: a member's reference to a node elsewhere draws the arc without pulling that node inside, though Graphviz would draw a node in the first box mentioning it.
  • An item of tags alone, + :container:, is an untitled box, with no label and no name to draw arcs to.
  • A container is a Graphviz cluster; | shape | cluster | is the same thing, spelled as a row.

Containers nest, each in the one around it. Unknown tags such as :Prophet: get made-up templates, as in Prototype first, name later:

﴾What You Write﴿
#+begin_graph
+ Islam :container:
  + Christianity :container:
    + Jesus :Prophet:
      + Simon :Heir:
    + Judaism :container:
      + Moses :Prophet:
        + Aaron :Heir:
  + Mohammad :Prophet:
    + Ali :Heir:
#+end_graph
﴾What You Get﴿
Islam Christianity Judaism Jesus Simon Moses Aaron Mohammad Ali

A node may also join a container by a tag: :container_TITLE: puts it in the box TITLE, its underscores spaces, so :container_Holy_Land: is Holy Land. A + TITLE :container: item is the same box, so the tag adds a node to it from anywhere in the graph; else the tags alone make the box. Several tags of other kinds color the node in stripes, as above:

﴾What You Write﴿
#+begin_graph
+ Moses :Prophet:Judaism:Christianity:Islam:
+ Jesus :Prophet:Christianity:Islam:container_Gospels:
+ Mohammad :Prophet:Islam:
+ Mark :container_Gospels:
+ John :container_Gospels:
#+end_graph
﴾What You Get﴿
Gospels Moses Jesus Mohammad Mark John

9.3. Records: a table of fields

Some nodes have insides: an AST node has a left operand, an operator, and a right operand, and each arc should leave from its own field. A record is a node drawn as a table, and Org already has tables: an item's table is its label, laid out exactly as written —unless it is the | key | value | rows of a node's table. A cell's [[link]] is an arc from that cell, its port, named by its text; a <<target>> makes any cell a port; and an arc reaches a port by record::port —just as Org's [[file:notes.org::target]] reaches into a file:

﴾What You Write﴿
#+begin_graph Our expression, as an AST
+ minus
  | left [[plus]] | - | right [[4]] |
+ plus
  | left [[times]] | + | right [[3]] |
+ times
  | left [[1]] | * | right [[2]] |
+ 1
+ 2
+ 3
+ 4
+ evaluator
  + starts at :: [[minus::left]]
#+end_graph
﴾What You Get﴿
Our expression, as an AST left - right left + right 4 left * right 3 1 2 evaluator starts at

Org tables have no merged cells, so two markers stand in for them: ^ continues the cell above, and an empty cell continues the cell to its left —or, in the first column, the one above. Together they draw any layout that Graphviz's old { } nesting could. A grammar rule with three alternatives spans its name over three rows; a token's heading spans its two fields:

﴾What You Write﴿
#+begin_graph
+ expr
  | expr \\ ::= | term =+= expr |
  | ^           | term =-= expr |
  | ^           | term          |
+ token
  | Token  |        |
  | kind   | lexeme |
  | NUMBER | ="42"= |
#+end_graph
﴾What You Get﴿
expr ::= term + expr term - expr term Token kind lexeme NUMBER "42"

Hlines and column cookies mean what they mean to Org. An hline draws a rule between rows, and a table with any hline draws one outer border rather than a box around every cell —so a UML class is just the table we would write anyway. A row of <l>, <c>, and <r> cookies aligns its columns, and cells keep their markup:

﴾What You Write﴿
#+begin_graph
+ Parser
  | <l>                  |
  | *Parser*             |
  |----------------------|
  | tokens: =List Token= |
  | position: =Int=      |
  |----------------------|
  | parse(): =Tree=      |
  | peek(): =Token=      |
#+end_graph
﴾What You Get﴿
Parser tokens: List Token position: Int parse(): Tree peek(): Token
  • A table is | key | value | rows when each row is two cells, its key a Graphviz attribute or a :key of ours; any other table is a record. So a misspelt | colour | red | shows itself, drawn as a record, rather than vanishing; and a record whose first field names an attribute writes it =label=.
  • A record is otherwise an ordinary node: its children are nodes of their own, and its attributes, tags, and templates apply as usual; color, fillcolor, and fontcolor color the table. An item may carry both tables, a blank line between, since Org reads adjacent rows as one table.
  • A record is shape=plain, the table being its whole outline; an explicit shape row wins.
  • A port's name is its cell's text sans links, spaces as underscores: [[minus::left operand]] reaches | left operand [[plus]] |. A <<target>> names a cell sans link, or gives a long one a terse name: | <<x>> where the parse resumes | is [[rec::x]].
  • Ports belong to their record, so all three records above have a left port: minus::left, plus::left.
  • A link's tags style its arc, as in an item's text: | left [[plus][:dashed:]] | draws a dashed arc. A cell's trailing tags are an error; write =:x:= for literal text.
  • a::b names a port only when a names a record; otherwise it is an ordinary node, such as std::vector. Record and port names may contain dots: [[org.el::v1.2]].
  • Graphviz spells ports record:port; that is the spelling in the generated dot.

9.4. Mind maps: :layout twopi

Every graph so far flows top to bottom; a mind map grows outward from its centre. Graphviz's layout attribute picks its engine, so the header line turns a tree into a mind map: twopi places root in the middle and each generation on a ring around it. With :wrap, long labels stay compact:

﴾What You Write﴿
#+begin_graph Parsing, radially :layout twopi :root Parsing :wrap 12 :node.style rounded
#+edge: :undirected:
+ Parsing
  + Top-down
    + Recursive descent
    + LL(k)
    + Packrat
  + Bottom-up
    + LR(0)
    + LALR(1)
    + Shift-reduce
  + Chart
    + Earley
    + CYK
#+end_graph
﴾What You Get﴿
Parsing, radially Parsing Top-down Bottom-up Chart Recursive descent LL(k) Packrat LR(0) LALR(1) Shift-reduce Earley CYK

Sans :root, twopi picks a centre itself. neato, fdp, and circo suit graphs that are not trees.

9.5. Wide trees: :unflatten N

A node with many children lays them out in one wide row: a ribbon, too wide for the page. Our lexer knows nine kinds of token:

﴾What You Write﴿
#+begin_graph Token kinds
+ token
  + NUMBER
  + IDENT
  + PLUS
  + MINUS
  + STAR
  + SLASH
  + LPAREN
  + RPAREN
  + EOF
#+end_graph
﴾What You Get﴿
Token kinds token NUMBER IDENT PLUS MINUS STAR SLASH LPAREN RPAREN EOF

:unflatten N passes the dot through Graphviz's own unflatten -l N, which staggers those leaves over N ranks, so the graph is a block rather than a ribbon:

﴾What You Write﴿
#+begin_graph Token kinds :unflatten 3
+ token
  + NUMBER
  + IDENT
  + PLUS
  + MINUS
  + STAR
  + SLASH
  + LPAREN
  + RPAREN
  + EOF
#+end_graph
﴾What You Get﴿
Token kinds token NUMBER IDENT PLUS MINUS STAR SLASH LPAREN RPAREN EOF

10. Diagrams we draw: sequences, classes, states, entities, mindmaps

Many diagrams are graphs in disguise; they differ only in how their nodes and arcs look. So rather than a syntax per kind, every graph has a few templates already, defined by org-defgraph-tag; a tag applies one, as with any #+name: template of our own, and our own of the same name wins. In Emacs, such a tag wears a face of its own, org-graph-builtin-tag, and clicking it says what it does.

org-defgraph-tag is defvar-like, a value with its docstring, yet setq-like, since evaluating it anew redefines the tag; so our own tags, used across documents, live in our init file:

(org-defgraph-tag hot "color=red penwidth=2"
  "Marks what needs attention now: red, and bold.")

Its pairs read as a #+name: hot color=red penwidth=2 line does.

Diagram Node tags Arc tags
Class (UML) —a class is a record table with hlines :inherits: :implements: :composes: :aggregates: :depends:
State machine :state: :start: :final: :choice: —a guard is the description term
Entity-relation —an entity is any node :one-to-one: :one-to-many: :many-to-one: :many-to-many:
Mindmap #+begin_graph :theme mindmap, sans tags  

10.1. A class diagram: records and UML arcs

A class is the table we would write anyway, as in Records; its relations are references, each link tagged with its kind. The arrow points at what is inherited, implemented, or depended on; a diamond sits at the owner's end:

﴾What You Write﴿
#+begin_graph :direction up
+ Animal
  | <l>               |
  | *Animal*          |
  |-------------------|
  | name: =String=    |
  |-------------------|
  | speak(): =String= |
+ Dog
  | <l>             |
  | *Dog*           |
  |-----------------|
  | fetch(): =Bone= |
  + [[Animal][:inherits:]]
  + [[Pet][:implements:]]
  + [[Tail][:composes:]]
  + [[Owner][:aggregates:]]
  + [[Bone][:depends:]]
+ <<Pet>> «interface» Pet
+ Tail
+ Owner
+ Bone
#+end_graph
﴾What You Get﴿
Animal name: String speak(): String Dog fetch(): Bone «interface» Pet Tail Owner Bone

10.2. A state machine: pseudo-states as tags

A state machine is an outline of what follows what; the description term is the event, or the guard, that takes us along the arc. A :start:, :final:, or :choice: item of tags alone is a node of its own, apart from every other; a composite state is a container:

﴾What You Write﴿
#+begin_graph :direction right
+ :start:
  + Idle :state:
    + coin :: Paid :state:
      + push :: :choice:
        + [stock] :: Vending :state:
          + done :: [[Idle]]
        + [empty] :: Refunding :state:
          + done :: :final:
#+end_graph
﴾What You Get﴿
Idle Paid coin push Vending [stock] Refunding [empty] done done

10.3. An entity-relationship diagram: cardinalities as tags

Each relationship is a description term, its cardinality a tag on that term, read from the parent's end to the child's: a customer places many orders, each order placed by one customer. Graphviz draws the crow's foot for “many” and the bar for “one”:

﴾What You Write﴿
#+begin_graph :direction right
+ Customer
  + places :one-to-many: :: Order
    + contains :one-to-many: :: Line item
      + names :many-to-one: :: Product
  + has :one-to-one: :: Account
#+end_graph
﴾What You Get﴿
Customer Order places Account has Line item contains Product names

10.4. A mindmap: an outline, radiating

An Org outline already is a mindmap; :theme mindmap merely draws it so: arrowless, its first item at the centre, the rest radiating out by Graphviz's twopi layout, every node a rounded box filled by its depth, from the theme's :node-colors. Any layout=twopi graph sans a root radiates from its first item, themed or not. The header's own attributes still win; e.g., :ranksep 2 spreads it out:

﴾What You Write﴿
#+begin_graph :theme mindmap
+ Org mode
  + Outlines
    + Folding
    + Tags
  + Tables
    + Spreadsheet
  + Babel
    + Tangling
    + Results
  + Export
    + HTML
    + LaTeX
#+end_graph
﴾What You Get﴿
Org mode Outlines Tables Babel Export Folding Tags Spreadsheet Tangling Results HTML LaTeX

A mindmap may instead grow one way, as a tree: :layout dot :direction right overrides the radial layout, :splines curved softens its arcs, and :wrap 40 keeps long thoughts narrow. Each depth keeps its color, and a label's Org markup is shown as markup:

﴾What You Write﴿
#+begin_graph :theme mindmap :layout dot :direction right :splines curved :wrap 40
+ Projects
  + Defined as:
    + Anything that can
      + Be finished in 1 year
      + Requires more than 1 step
  + *Note:* A lot of what I list as tasks should be projects
  + Project support material
    + Best kept out of sight
    + Next Action categories
      + Next Action list
        + Non-actionable items
          + Trash
            + Keeping trash will undermine system
          + Incubate
            + Someday/Maybe list
            + Tickler file
      + Waiting For list
    + Calendar
      + For tracking
        + Time-specific actions
          + Appointments
        + Day-specific actions
          + Things I need to do but don't have a set time
        + Day-specific information
          + Information useful for a certain date but not necessarily an action
      + *Important:* /Don't keep to-do lists on the calendar!/
        + If things that don't need to get done that day get tracked on the calendar, it will clutter and prevent getting done the things that do need to get done that day.
#+end_graph
﴾What You Get﴿
Projects Defined as: Note: A lot of what I list as tasks should be projects Project support material Anything that can Be finished in 1 year Requires more than 1 step Best kept out of sight Next Action categories Calendar Next Action list Waiting For list Non-actionable items Trash Incubate Keeping trash will undermine system Someday/Maybe list Tickler file For tracking Important: Don't keep to-do lists on the calendar! Time-specific actions Day-specific actions Day-specific information Appointments Things I need to do but don't have a set time Information useful for a certain date but not necessarily an action If things that don't need to get done that day get tracked on the calendar, it will clutter and prevent getting done the things that do need to get done that day.

10.5. A sequence diagram: lifelines, ranks, and a turned arrow

No template draws a sequence diagram, yet ranks and templates do. Each actor's lifeline is a chain of moments: points, whose arcs a moment template dashes, greys, and —by a heavy weight— keeps straight. An :@X: tag puts the moments of one instant side by side, and a message is a reference from one moment to another. Graphviz orders a rank's nodes by its arcs' direction, so every message hangs off the left lifeline, and a reply template turns its arrow back:

﴾What You Write﴿
#+begin_graph Ordering a latte :labelloc t
#+name: actor style=rounded

#+name: moment
| shape           | point  |
| width           | 0.04   |
| :edge.style     | dashed |
| :edge.arrowhead | none   |
| :edge.color     | gray   |
| :edge.weight    | 100    |

#+name: reply dir=back style=dashed

+ Customer :actor:@actors:
  + :moment:@t1:
    + order a latte :: [[b1]]
    + :moment:@t2:
      + “that’s $5” :reply: :: [[b2]]
      + :moment:@t3:
        + pay :: [[b3]]
        + :moment:@t4:
          + here you go :reply: :: [[b4]]
+ Barista :actor:@actors:
  + <<b1>> :moment:@t1:
    + <<b2>> :moment:@t2:
      + <<b3>> :moment:@t3:
        + <<b4>> :moment:@t4:
#+end_graph
﴾What You Get﴿
Ordering a latte Customer order a latte “that’s $5” pay here you go Barista

The moment template styles the arc into each point, by its :edge.KEY rows, being a node's template; reply styles an arc itself, being a description term's, so its keys are plain. For a long conversation, #+begin_image mermaid or plantuml says it more tersely; see Images.

11. Graphs in their document

A graph rarely stands alone: prose refers to it, and an outline may already be one. Org's own document machinery reaches graphs too.

11.1. #+name: and #+caption: make a figure

We want to write “as Figure 1 shows”, and have the number stay right. In Org, #+name: is what [[links]] reach, and #+caption: captions a table or an image. A graph is an image, so both mean what they always do. Its point is an image file beside our document, so we show it as source alone:

As parse-tree shows, =*= binds tighter than =+=.

#+name: parse-tree
#+caption: How 1 * 2 + 3 parses
#+begin_graph
+ +
  + *
    + 1
    + 2
  + 3
#+end_graph
  • The graph renders to parse-tree.png —both on C-c C-c and on export— and exports as that image, numbered and captioned: [[parse-tree]] reads “Figure 1” in HTML, and \ref in LaTeX.
  • An explicit :file still wins: #+begin_graph :file elsewhere.png renders there, and the #+name: still labels it; its extension picks the format, so :file parse-tree.svg makes the figure an SVG.
  • An unnamed graph exports as before: inlined into HTML, or as dot source elsewhere.

11.2. Sections are graphs: the :graph: tag

Sometimes a whole section is nothing but the outline we want drawn; wrapping it in a block is ceremony. A #+begin_graph block is a function on a region; a :graph: tag is the same function on a section, its subsections included. Its subheadings are the items; their :PROPERTIES: drawers —Org's own home for key-value settings— are the items' tables; and the root's own drawer is the #+begin_graph line.

11.2.1. The equivalence, by example

Here is a block:

#+begin_graph Our grammar :direction right
+ expr
  | shape | box |
  + term

    A product of factors.

    + factor
      1. NUMBER
      2. ( … ) :: [[expr]]
#+end_graph

And here is the very same graph, as a section; both draw the same dot, and so the same picture:

﴾What You Write﴿
* Our grammar :graph:
:PROPERTIES:
:DIRECTION: right
:END:
** expr
:PROPERTIES:
:SHAPE: box
:END:
*** term
A product of factors.
**** factor
:PROPERTIES:
:ORDERED: t
:END:
***** NUMBER
***** ( … ) :: [[expr]]
﴾What You Get﴿

Our grammar

Our grammar expr term factor ( … ) NUMBER

Every left cell is a block's spelling; the right, what a section says instead.

Block Section
#+begin_graph TITLE :direction right * TITLE :graph:, its drawer holding :DIRECTION: right
+ child nested under + parent ** child under * parent
item text: markup, <<id>>, [[T]], [fn::…] the heading's title: the very same text
trailing :t₁:t₂: tags the heading's own tags —the very same spelling
+ LABEL :: CHILD, labelling the arc into CHILD ** LABEL :: CHILD
an item's shape / box row :SHAPE: box in its drawer; the table still works too
an item's :edge.color / red row :EDGE.COLOR: red
an item's :edge[T].color / red row :EDGE[T].COLOR: red, T keeping its case
#+node: under an item, for its subtree :NODE.SHAPE: box; likewise :GRAPH.KEY:; #+edge: stays as it is
an item's later paragraphs, its notes the heading's body paragraphs
1. 2. children, one rank in the order written the parent's :ORDERED: t —Org's own property, meaning just this
[X] / [ ] checkbox a DONE / TODO keyword; a keyword K applies template k, if any
#+graph:, #+name:, a legend, before the items the root's own text, before its first subheading
  • The heading titles the graph, as it does every tagged block; :graph_The_Grammar: retitles it The Grammar, and a :TITLE: property does too.
  • The heading stays a heading; its text and subsections become the graph, on export, and the next section is untouched. A node's own tags, such as :details:, style it; they never fold its section.
  • A drawer's keys are Graphviz attributes, regardless of case: :url: is URL. Org's own properties, such as :CUSTOM_ID: and :CATEGORY:, stay Org's —bar :STYLE:, which Graphviz names too— and any other key is an error, so a typo never vanishes silently.
  • COMMENT headings, and those tagged :noexport: or :ARCHIVE:, are no nodes, their subtrees neither.
  • A :graph: heading cannot hold another; a :container: tag draws a box.
  • C-c C-c anywhere in the section's body renders it, its image right beneath the root's drawer; on a heading, C-c C-c stays Org's, setting tags.

11.2.2. Go only as deep as is comfortable

A section's body may hold a list, read exactly as a block's body is. So the sections need only go as deep as is comfortable, and leaves stay terse:

﴾What You Write﴿
* Lineage :graph:
** λ-calculus
*** inspired :: Lisp
+ subset of :: Emacs Lisp
+ dialect :: Scheme
﴾What You Get﴿

Lineage

Lineage λ-calculus Lisp inspired Emacs Lisp subset of Scheme dialect

Hence a section holding a lone list, and no subheadings, is a graph too: as is this one, further below.

11.2.3. Org is the graph editor

A block's editor is C-c ' and our own commands; a section's is Org itself.

  • M-← and M-→ re-parent a node, its subtree in tow; M-↑ and M-↓ reorder siblings; C-c C-w refiles a node into another graph.
  • Folding: a 200-node graph is a page of headings, not a page of nested bullets and tables.
  • Column view, C-c C-x C-c, is a spreadsheet of every node's attributes, editable in place; say, by #+columns: %ITEM %SHAPE %COLOR %EDGE.LABEL.
  • C-M-i in a drawer completes Graphviz's attributes, then their values, and eldoc explains them; C-c C-x p completes a value, and S-→ cycles through them, as for any of Org's allowed values.
  • TODO nodes reach the agenda; C-c ; comments a node out; C-c / m sparse-trees the graph by tag.

12. Beyond Graphviz: smartdiagram

Graphviz lays out a graph; but a slide or a README's opening often wants something more posed than a layout. LaTeX's smartdiagram package typesets a handful of fixed pictures —a planet amid its satellites, a flow of boxes, a column of terms and their descriptions— that suit it better than any graph. #+begin_smartdiagram TITLE :type TYPE hands the very same list to smartdiagram instead: it is a thin facade over #+begin_image latex, so LaTeX export typesets it in place, any other backend shows its image, and C-c C-c renders it atop the block. Our compiler's pipeline is a flow:

﴾What You Write﴿
#+begin_smartdiagram From text to value :type flow:horizontal
+ characters
+ tokens
+ syntax tree
+ value
#+end_smartdiagram
﴾What You Get﴿
From text to value
  • TYPE is one of constellation, connected-constellation, bubble, flow, flow:horizontal, circular, circular:clockwise, descriptive, priority-descriptive, or sequence.
  • A constellation or bubble has one top item, its centre; that item's children orbit it. A descriptive diagram's items are + TERM :: DESCRIPTION. Every other type reads the top items, in order.
  • The #+graph: rows are \smartdiagramset's, in smartdiagram's own words: | planet color | black!75 |.
  • An item's | color |, | fontcolor |, and | fontsize | rows —Graphviz's names for them— color its shape and its text, and size its text; its :tags: splice #+name: templates of those rows, as in any graph. An item's later paragraphs sit beneath its text.
  • The title sits above the diagram; prose before the list, between the two; prose after it, beneath.
  • :file, :resolution, and :as-image are #+begin_image's: they name its images, sharpen its PNG, and make it an image along LaTeX too.
  • C-M-i and eldoc know which block they are in: in a #+begin_smartdiagram, they offer smartdiagram's keys, with their defaults, rather than Graphviz's.
  • Graphviz's own syntax ---#+node:, #+edge:, links between items, records— draws nothing here, so it is an error rather than silently dropped.

12.1. Org's markup in place of LaTeX's

Why bother, when LaTeX could draw it directly? Here is a richer diagram, one that began life as a #+begin_src latex-as-png block, via ob-latex-as-png: a constellation of how one syntax, (key map), replaces many. Its #+graph: rows, macro, and color links are where the LaTeX went:

﴾What You Write﴿
#+macro: replaces \\ [[color:gray][replaces]] \\ [[color:gray][=$1=]]

#+begin_smartdiagram One syntax =(key map)= \\ where =key= is =number=, =:keyword=, ='symbol=, or ="string"=! :type constellation
#+graph:
| planet color              | black!75        |
| planet size               | 3.5cm           |
| planet text width         | 3.3cm           |
| satellite size            | 3.6cm           |
| satellite text width      | 3.5cm           |
| distance planet-satellite | 5.7cm           |
| connection color          | gray!60         |
| font                      | \small\sffamily |

+ *easy-access.el* \\ one syntax
  | fontcolor | white |
  + =(:k plist)= \\ [[color:gray][replaces]] \\ [[color:gray][=(plist-get plist :k)=]]
  + =(:k alist)= \\ [[color:gray][replaces]] \\ [[color:gray][=(cdr (assoc :k alist))=]]
  + =(:k hash)= \\ [[color:gray][replaces]] \\ [[color:gray][=(gethash :k hash)=]]
  + =(:field instance)= \\ [[color:gray][replaces]] \\ [[color:gray][=(record-field instance)=]]
  + =(n sequence)= \\ [[color:gray][replaces]] \\ [[color:gray][=(seq-elt sequence n)=]]
  + =(setf (:k p) v)= \\ [[color:gray][replaces]] \\ [[color:gray][=(map-put p :k v)=]]

-----

=(:school 'math "jasim" :names 2 my-nested-life)=

[[color:gray][replaces]]

#+begin_src emacs-lisp
(seq-elt (-> my-nested-life
             (map-elt :school)
             (map-elt 'math)
             (map-elt "jasim")
             person-names)
         2)
#+end_src
#+end_smartdiagram
﴾What You Get﴿
One syntax =(key map)= \\ where =key= is =number=, =:keyword=, ='symbol=, or =

Every LaTeX incantation it needed has an Org counterpart that we already write daily:

LaTeX Org
\smartdiagram[constellation diagram]{…} :type constellation, over a nested list
\smartdiagramset{planet color=black!75, …} a #+graph: table, one row a key
\newcommand{\old}[1]{\textcolor{black!70}{\texttt{#1}}} #+macro: old [[color:gray][=$1=]]
\texttt{(:k plist)}, \textbf{…} =(:k plist)=, *…*
\mbox{\texttt{…}}, lest code break mid-circle nothing: code never breaks
\textcolor{black!70}{replaces} [[color:gray][replaces]]
{\color{white}…} on the planet a fontcolor row of white
\centering{One syntax … \\ …} above the diagram the block's title
\vspace{1em}{\textcolor{black!44}\hrule}\vspace{1em} -----
\hspace{7em} (map-elt :school), line by line a #+begin_src block, indented as we read it
% \new{(N xs)} \replaces … # + =(N xs)= …
\resizebox, \vspace, {\color{white} Bye!} padding nothing: the image is cropped to a small border

The LaTeX column is a second language inside our Org file: its macros, its color syntax, and hand-tuned \hspace's that drift the moment a line changes. The Org column is the language the rest of the file is already in; it folds, links, exports, and completes like everything around it. The only backslashes that survive the move are \\ —which Org itself reads as a line break— and the font names, such as \small, that smartdiagram's own settings take as values.

13. Beyond text: drawing by hand

Some pictures resist an outline: a whiteboard sketch, a doodle with arrows wherever we please, a layout we would rather place than describe. For those, we put the keyboard down and pick up a pen.

  • Excalidraw is a lovely online tool for drawing diagrams easily: boxes, arrows, and text, in a hand-drawn style, with nothing to install. It exports to PNG or SVG, which [[file:sketch.svg]] then shows in our Org file like any other image.
  • Screenbrush, a macOS app, draws on top of whatever is on screen. When presenting —say, while screen sharing— we use it to highlight things, or to draw arrows and boxes around stuff.

14. Comforts while editing

Graphviz has 177 attributes, and nobody remembers them. So the block helps as we type, wherever we type.

  1. C-M-i (completion-at-point) and eldoc know about graph keys —in any Org buffer's graph blocks, and in the org-graph-edit-mode buffer that C-c ' opens on one, as for a source block:
    • In a key cell, completion offers the attributes valid there, plus the reserved keys; after :edge. or :edge[T]., it offers only edge attributes, prefix and all. In a value cell, it offers the values of that row's attribute, such as vee for :edge.arrowhead. Each candidate is annotated with its description.
    • On the #+begin_graph line, :r C-M-i offers :ratio and the other graph attributes, every :node.KEY and :edge.KEY, and the block's own :file, :direction, and :C-c_C-c; :direction r C-M-i then offers right.
    • Eldoc shows the description of the key on the current row, or at point on the #+begin_graph line, ending with Graphviz's default; e.g., | :edge.arrowhead | vee | shows “Style of arrowhead on the head node of an edge. Default: normal.”
  2. A directive's line validates itself as we type: #+graph:, #+node:, #+edge:, and #+name: stand out, and so does each KEY of a KEY=VALUE pair that Graphviz knows on that line. A key left plain is a typo, or a misplaced key; see When the preamble outgrows the line. Each #+name: template wears a background of its own.
  3. When we would rather pick than type, C-u RET on any table row inside a graph inserts a new | key | value | row interactively: a completion menu for the key, then one for the value —or a free-text prompt, when the attribute accepts arbitrary strings. Plain RET is unaffected. The menu shows only the attributes valid where the table sits:

    • Table under #+graph: ⟶ graph-level attributes (rankdir, splines, bgcolor, …)
    • Table under #+node: ⟶ default node attributes (shape, style, color, …)
    • Table under #+edge: ⟶ default edge attributes (arrowhead, dir, penwidth, …)
    • Table on a list item ⟶ node attributes, as above

    For a color ---bgcolor, fillcolor, fontcolor, or color— the value is picked from Helm's color list, when Helm is installed; RET inserts the color's hex code, and its name as a comment. (This replaces our old ritual of M-x helm-colors, then C-z, then C-c r.) C-u RET works in the C-c ' buffer too.

  4. Where do the descriptions come from? org-graph-attributes, which lives on its own in org-graph-attributes.el: every Graphviz attribute, scraped from Graphviz's attribute table. To add or adjust one, edit its entry there, or M-x customize-variable RET org-graph-attributes; each entry has the form:

    (:name "shape" :valid-on (nodes) :default "ellipse"
     :values ("box" "polygon" "ellipse" …)  ;; nil → free-text prompt
     :description "Sets the shape of a node.")
    

    Reserved keys are described by org-graph--reserved-key-docs, and the header's own keys by org-graph--header-key-docs.

  5. When the picture is wrong, we want to see what we built. C-u C-c C-c shows the generated dot in a *org-graph dot* buffer instead of rendering a PNG, and inserts —or replaces— a #+RESULTS: holding it as a #+begin_src dot block, so the source is preserved. For a block where we always want dot, :C-c_C-c dot in its header makes plain C-c C-c show dot, and C-u C-c C-c toggles back to PNG: the prefix always flips whatever the block's default is.
  6. The image C-c C-c renders is clickable. Hovering over a node or cluster shows its tooltip —its footnotes and notes— and a click follows it: to its link's target, when its item has a web, file, or [[*Heading]] link; else to the item itself, in the #+begin_graph block. Graphviz writes an image map (-Tcmapx) beside the PNG, from the same layout, and its areas become the image's :map; it is scaled as the image is, say by org-image-actual-width. The map lives only as long as the image does: an image Org redisplays itself, say on reopening the file, is clickable again after another C-c C-c.
  7. Big graphs make big PNGs; (setq org-image-actual-width 700) keeps them on screen. In an HTML export, a graph shrinks to the page's width by itself, and a click toggles its full size.
  8. In a :demo live graph, as throughout this README, C-c C-c still renders the graph: a live demo keeps no snapshot to take.
  9. A tag is a link to its template: clicking it, or C-c C-o on it, jumps to its #+name: line —the graph's own, else one outside every graph— as a template's lookup goes. A tag every graph has, from org-defgraph-tag, says what it does instead, as eldoc does with point on it; and an undefined tag says that a template is made up for it, and that :unknown-tags error forbids that.

15. Reference

Once the demo is over, this is the page we keep open.

15.1. Syntax at a glance

Construct Dot equivalent
#+begin_graph TITLE graph [ label=TITLE ]
#+begin_graph :KEY V graph [ KEY=V ]; also :node.KEY V and :edge.KEY V; V needs no quotes
#+edge: :undirected: edge [ dir=none ]: arrowless arcs, an undirected graph
#+begin_graph :direction right graph [ rankdir=LR ]; likewise down TB, up BT, left RL
:dashed: :pink: :large: :size_N:, … everyday templates every graph has; see Everyday tags
#+begin_graph :theme NAME the theme NAME of org-graph-themes, beneath all else; nil for Graphviz's look
#+begin_graph :theme mindmap an arrowless twopi layout, radiating from the first item, nodes filled by depth
#+name: N above #+begin_graph renders to N.png: a figure that [[N]] reaches, and #+caption: captions
* HEADING :graph:, with :PROPERTIES: subheadings are nodes, drawers their attributes; the root's drawer, the header line
:NAME: … :END: drawer the directives inside, folded away
#+graph: table graph [ … ]
#+node: table node [ … ]
#+edge: table edge [ … ]
#+edge: fontsize=10 color=gray :T: edge [ fontsize=10 color=gray … ], with template T; likewise #+graph:, #+node:
#+name: T + table style template T, used via :T: tags; in or out of graphs
#+name: T :S: template T, inheriting template S
#+name: T color=red shape=box template T on one line, of KEY=VALUE pairs; with or without a table below
top-level - :T: :: MEANING a legend entry: a sample of template T, captioned MEANING
- MEANING :T: in a Legend container the same legend entry, in prose
+ TITLE :container:, then children subgraph cluster_TITLE { label=TITLE … }, the children inside; its table styles it
+ NAME :container_TITLE: node NAME, inside the box TITLE
+ NAME list item node NAME declaration
indent + CHILD under + PARENT edge PARENT → CHILD
+ L :: CHILD under + PARENT edge PARENT → CHILD, labelled L
1. A, 2. B under + PARENT edges PARENT → A, B; { rank=same; A; B }, in that order
+ <<ID>> NAME node ID, labelled NAME
+ <<<NAME>>> node NAME; every item mentioning NAME arcs to it
+ NAME [[T]], + NAME [[T][L]] edge NAME → T, labelled L
+ NAME [[T][L :S:]] edge NAME → T, labelled L, with template S; L is optional
+ NAME :T₁:T₂: node NAME, with templates T₁ and T₂ spliced in
+ NAME :@X: node NAME, in group X: { rank=same; NAME; … }
+ NAME :@start:, + NAME :@end: { rank=min; NAME; … }, { rank=max; NAME; … }
+ NAME [fn::NOTE] node NAME, with tooltip=NOTE
a later paragraph of + NAME a note: NAME's tooltip, or beneath its label under :notes inline
+ NAME \\ MORE node NAME MORE, its label broken over two lines; likewise in table cells
+ NAME [[https://…]], [[file:x.png]] node NAME, with URL="https://…", or image="x.png"
+ [X] NAME, [-], [ ] node NAME, with template checked, partial, or unchecked, if defined
:inherits:, :state:, :one-to-many:, … templates every graph has; see org-defgraph-tag
{{{M}}}, after #+macro: M V V, anywhere in the block
*b* /i/ _u_ +s+ =c= ~p~ an HTML-like label: <B>, <I>, <U>, <S>, monospace
∣ key ∣ value ∣ node attribute; values are quoted for you
∣ :edge.KEY ∣ value ∣ attribute of the arc from the parent; each KEY at most once
+ [[T][L :S:]] under + PARENT edge PARENT → T, a node declared elsewhere; record::port targets a port
∣ :edge[T].KEY ∣ value ∣ attribute of this item's arc to T, from a [[T]] link; see Strictly tables
∣ shape ∣ cluster ∣ subgraph cluster_ID { … } around the children; see Strictly tables
any other table under + NAME node NAME, labelled by that table, a record; <<P>> in a cell is port P

15.2. Strictly tables: :edge[T].KEY and | shape | cluster |

Some of us prefer every attribute in a key-value table, never in the list's shape. Two spellings serve that taste; the examples above avoid them, but they are fully supported.

An inline link's arc is styled by :edge[T].KEY, naming the arc by where it goes; its tags, [[T][L :S:]], apply a template to it. A row with no [[T]] link in the item's text is an error:

﴾What You Write﴿
#+begin_graph
+ <<expr>> expression
  + term
    + factor [[expr][( … )]]
      | :edge[expr].style | dotted |
      | :edge[expr].color | red    |
#+end_graph
﴾What You Get﴿
expression term factor ( … )

A | shape | cluster | row makes an item a container, as the :container: tag does. Its children are then its members rather than arc targets, so arcs out of them are inline links, styled as above:

﴾What You Write﴿
#+begin_graph :direction right
+ compiler
  + Front end
    | shape | cluster |
    + lexer [[parser]]
    + parser
#+end_graph
﴾What You Get﴿
Front end compiler lexer parser

Generated by Emacs and Org-mode (•̀ᴗ•́)و
Creative Commons License
Life & Computing Science by Musa Al-hassy is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License