Search code examples
graphvizdotauto-indent

Auto-indenting graphviz .dot file


I am working on a long and complex architectural graph. The document indentation mixes tabs, spaces and indentation levels, which drives me crazy.

Is there a simple way to automatically indent graphviz .dot files in Linux environment?

A pure command line tool would be best, but plugins to popular editors like vim would be a good solution too.

Update:

The vim indentation has a bug with : in node names in edges. For example, server_a:event -> log_server; causes the next line to be further indented, presumably because the : is parsed as a block declaration (see comments on Harry Pehkonen's answer). Quoting the node name (e.g. "server_a":event -> log_server;) solves this issue:

#!/usr/bin/python3

import re

dot=open('components.dot').read()
reg=re.compile("(\s)(\S+)(\:.*\-\>)")
print(reg.sub(r'\1"\2"\3', dot))

Solution

  • Vim has dot syntax knowledge out of the box, and seems to re-indent dot files for me.

    I removed all indentation, went to the top of the file, and did =G

    Your global tab-related values determine whether to use tabs/spaces, how many, etc.

    If you want, you can create a script with:

    > vim -W reIndentAndSave whatever.dot
    

    Edit your dot file by re-indenting from top with

    gg=G
    

    ...Save

    :x
    

    Then, for each file you want to re-indent via the script that you just recorded,

    > vim -s reIndentAndSave somegraph.dot