Added a basic indenting XML writer.
[jsvc.git] / src / dolda / jsvc / next / IndentWriter.java
1 package dolda.jsvc.next;
2
3 import java.io.*;
4 import org.w3c.dom.*;
5
6 public class IndentWriter extends XmlWriter {
7     public int collimit = 80;
8     
9     public IndentWriter(Document doc) {
10         super(doc);
11     }
12     
13     private static boolean onlytext(Element el) {
14         for(Node n = el.getFirstChild(); n != null; n = n.getNextSibling()) {
15             if(!(n instanceof Text))
16                 return(false);
17         }
18         return(true);
19     }
20     
21     protected boolean prebreak(ColumnWriter out, Element el) {
22         if(el.getFirstChild() == null)
23             return(false);
24         if(onlytext(el))
25             return(false);
26         return(true);
27     }
28     
29     protected int indent(ColumnWriter out, Element el) {
30         if(onlytext(el))
31             return(-1);
32         return(2);
33     }
34
35     protected boolean postbreak(ColumnWriter out, Element el) {
36         if(out.col > collimit)
37             return(true);
38         return(!onlytext(el));
39     }
40
41     protected void attribute(ColumnWriter out, String nm, String val, int indent) throws IOException {
42         if(out.col > indent) {
43             if(nm.length() + val.length() + 4 > collimit)
44                 out.indent(indent);
45         }
46         super.attribute(out, nm, val, indent);
47     }
48     
49     public static void main(String[] args) throws Exception {
50         Html barda = Html.xhtml11("Barda");
51         barda.addcss("/slen.css", "Test");
52         barda.insert("body", barda.el("h1", barda.text("Mast")));
53         barda.finalise();
54         barda.validate();
55         XmlWriter w = new IndentWriter(barda.doc);
56         w.setnsname(Html.ns, null);
57         w.write(System.out);
58         System.out.flush();
59     }
60 }