views:

84

answers:

2

I am generating a graphviz DOT file in a Java program (here is a example of what one looks like: http://www.graphviz.org/Gallery/directed/cluster.html). I want to automatically indent this file based on the braces. Is there an easy way to do this in Java? Thanks!

A: 

I suppose there are various solutions for this question. Deponding on the requirement, you may want an elegent solution which may allow you to easily cumstimaze a template for the final output. Then you need to understand the graphviz file format and possibly identify code by blocks as nodes. Then the job is easy: output nodes(I mean the code reprenting the node) of depth i with indents = i*4 spaces.

Since I have no knowledge about the graphviz file, I probaly will simply treat it as a plain text file. So all you need to do is

  1. open the graph file, 
  2. create a temp file for the final output
  3. set indent = 0.
  4. read one line, if not null, search the line for braces, for every opening brace, ++indent
     and --indent for every closing brace.
  NOTE:you need to escape the escaped braces if there is any. say "{" or \{


  5. write the line to the temp file with preceding spaces = 4*indent (assuming you want 4 spaces for every indent)
  6. close both files. if needed, replace the old file with the temp file.

As I probably do not understand your equestion correctly, the pseudocode could be useless functionwise. But you got the idea ;-)

Jason Wang
+1  A: 

Nested contexts like this are really best expressed by stacks, but you can do a cheap version of this kind of parsing just by counting - it's not really "correct" in that it's not a full parser (for one thing, this doesn't take comments into account, and there's probably a few other ways it could break, like a name that includes a bracket), but good enough for a one-off:

psuedocode

int indent=0;
for (line):
    print ('\t' for each indent) + line
    if (line.contains('{'))indent++
    if (line.contains('}')} indent --;

If the lines are not already broken at the brackets as your sample output displays, iterate the lines by breaking the input on newlines, '{', or '}'.

Steve B.