summaryrefslogtreecommitdiff
path: root/sources/scala/xml/PrettyPrinter.scala
blob: 0b1e233481dacc290c336781e0263a13639deaaa (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
/*                     __                                               *\
**     ________ ___   / /  ___     Scala API                            **
**    / __/ __// _ | / /  / _ |    (c) 2003-2004, LAMP/EPFL             **
**  __\ \/ /__/ __ |/ /__/ __ |                                         **
** /____/\___/_/ |_/____/_/ | |                                         **
**                          |/                                          **
** $Id$
\*                                                                      */

package scala.xml ;

import java.lang.StringBuffer ; /* Java dependency! */
import scala.collection.Map ;

/** Class for pretty printing. After instantiating, you can use the
 *  toPrettyXML methods to convert XML to a formatted string. The class
 *  can be reused to pretty print any number of XML nodes.
 *
 * @param width the width to fit the output into
 * @step  indentation
**/

class PrettyPrinter( width:Int, step:Int ) {

  class BrokenException() extends java.lang.Exception();

  class Item ;
  case object Break extends Item {
    override def toString() = "\\";
  };
  case class Box( col:Int, s:String ) extends Item;
  case class Para( s:String ) extends Item;

  protected var items:List[Item] = Nil;

  protected var cur = 0;
  protected var pmap:Map[String,String] = _;

  protected def reset() = {
    cur = 0;
    items = Nil;
  }

  /* try to cut at whitespace */
  protected def cut( s:String, ind:Int ):List[Item] = {
    val tmp = width - cur;
    if( s.length() < tmp )
      return List(Box(ind,s));
    val sb = new StringBuffer();
    var i = s.indexOf(' ');
    if( i > tmp ) throw new BrokenException(); // cannot break

    var last = i::Nil;
    while( i < tmp ) {
      last = i::last;
      i = s.indexOf(' ', i );
    }
    var res:List[Item] = Nil;
    while( Nil != last ) try {
      val b = Box( ind, s.substring( 0, last.head ));
      cur = ind;
      res = b :: Break :: cut( s.substring( last.head, s.length()), ind );
       // backtrac
    } catch {
      case _:BrokenException => last = last.tail;
    }
    throw new BrokenException()
  }

  /** try to make indented box, if possible, else para */
  protected def makeBox( ind:Int, s:String )  = {
    if( cur < ind )
      cur == ind;
    if( cur + s.length() > width ) {            // fits in this line
      items = Box( ind, s ) :: items;
      cur = cur + s.length()
    } else try {
      for( val b <- cut( s, ind ).elements )  // break it up
        items = b :: items
    } catch {
      case _:BrokenException => makePara( ind, s ); // give up, para
    }
  }

  // dont respect indent in para, but afterwards
  protected def makePara( ind:Int, s:String ) = {
    items = Break::Para( s )::Break::items;
    cur = ind;
  }

  // respect indent
  protected def makeBreak() = { // using wrapping here...
    items = Break::items;
    cur = 0;
  }

  protected def leafTag( n:Node ) = {
    val sb = new StringBuffer("<");
    Utility.appendPrefixedName( n.namespace, n.label, pmap, sb );
    Utility.attr2xml( n.namespace, n.attributes.elements, pmap, sb );
    sb.append("/>");
    sb.toString();
  }

  protected def rootStartTag(n: Node) = {
    val sb = new StringBuffer("<");
    Utility.appendPrefixedName( n.namespace, n.label, pmap, sb );
    Utility.attr2xml( n.namespace, n.attributes.elements, pmap, sb );
    if(( pmap.size != 1 )|| !pmap.contains(""))
      for( val c <- pmap.elements; c._2 != "xml" ) {
        sb.append(" xmlns:");
        sb.append(c._2);
        sb.append("=\"");
        sb.append(c._1);
        sb.append('"');
      }
    sb.append('>');
    sb.toString();
  }
  protected def startTag(n: Node) = {
    val sb = new StringBuffer("<");
    Utility.appendPrefixedName( n.namespace, n.label, pmap, sb );
    Utility.attr2xml( n.namespace, n.attributes.elements, pmap, sb );
    sb.append('>');
    sb.toString();
  }

  protected def endTag(n: Node) = {
    val sb = new StringBuffer("</");
    Utility.appendPrefixedName( n.namespace, n.label, pmap, sb );
    sb.append('>');
    sb.toString();
  }

  /** appends a formatted string containing well-formed XML with
   * given namespace to prefix mapping to the given stringbuffer
   * @param n the node to be serialized
   * @param pmap the namespace to prefix mapping
   * @param sb the stringbuffer to append to
   */
  def format(n: Node, pmap: Map[String,String], sb: StringBuffer ): Unit = {
    reset();
    this.pmap = pmap;
    traverse1( n, 0 );
    var cur = 0;
    //Console.println( items.reverse );
    for( val b <- items.reverse ) b match {
      case Break =>
        sb.append('\n');  // on windows: \r\n ?
        cur = 0;
      case Box(i, s) =>
        while( cur < i ) {
          sb.append(' ');
          cur = cur + 1;
        }
        sb.append( s );
      case Para( s ) =>
        sb.append( s );
    }
  }

  protected def breakable( n:Node ):boolean = {
    val it = n.child.elements;
    while( it.hasNext )
      it.next match {
        case _:Text | _:Comment | _:EntityRef | _:ProcInstr =>
        case _:Node => return true;
      }
    return false
  }
    /** @param tail: what we'd like to sqeeze in */
    protected def traverse( node:Node, ind:int ):Unit = {
      node match {

        case _:Text | _:Comment | _:EntityRef | _:ProcInstr =>
          makeBox( ind, node.toString() );

        case _:Node =>
          val sb = new StringBuffer();
          val test = { Utility.toXML1(node,pmap,sb); sb.toString()};
          if(( test.length() < width - cur )&&( !breakable( node ))){ // all ?
            makeBox( ind, test );
          } else {  // start tag + content + end tag
            //Console.println(node.label+" ind="+ind);
            val stg    = startTag( node );
            val etg    = endTag( node );
            val len2   = pmap(node.namespace).length() + node.label.length() + 2;

            if( stg.length() < width - cur ) { // start tag fits

              makeBox( ind, stg );
              makeBreak();
              traverse( node.child.elements, ind + step );
              makeBox( ind, etg );

            } else if( len2 < width - cur ) {
              // <start label + attrs + tag + content + end tag
              makeBox( ind, stg.substring( 0,    len2 ));
              makeBreak();
              /*{ //@todo
               val sq:Seq[String] = stg.split(" ");
               val it = sq.elements;
               it.next;
               for( val c <- it ) {
               makeBox( ind+len2-2, c );
               makeBreak();
               }
               }*/
              makeBox( ind, stg.substring( len2, stg.length() ));
              makeBreak();
              traverse( node.child.elements, ind + step );
              makeBox( cur, etg );
            } else {
            makeBox( ind, test );
            makeBreak();
            }
          }
      }
    }

    /** @param tail: what we'd like to sqeeze in */
    protected def traverse1( node:Node, ind:int ):Unit = {
      node match {

        case _:Text | _:Comment | _:EntityRef | _:ProcInstr =>
          makeBox( ind, node.toString() );

        case _:Node => {
          // start tag + content + end tag
            //Console.println(node.label+" ind="+ind);
            val stg    = rootStartTag( node );
            val etg    = endTag( node );
            val len2   = pmap(node.namespace).length() +node.label.length() + 2;

            if( stg.length() < width - cur ) { // start tag fits

              makeBox( ind, stg );
              makeBreak();
              traverse( node.child.elements, ind + step );
              makeBox( ind, etg );

            } else if( len2 < width - cur ) {
              val sq:Seq[String] = stg.split(" ");
              val it = sq.elements;
              var tmp    = it.next;
              makeBox( ind, tmp );
              var curlen = cur + tmp.length();
              while( it.hasNext ) {
                var tmp    = it.next;
                if( tmp.length() + curlen + 1 < width ) {
                  makeBox( ind, " " );
                  makeBox( ind, tmp );
                  curlen = curlen + tmp.length() + 1;
                } else {
                  makeBreak();
                  makeBox( len2+1, tmp );
                  curlen = len2+1;
                }
              }
              // <start label + attrs + tag + content + end tag
              //makeBox( ind, stg.substring( 0,    len2 ));
              //makeBreak();
              /*{ //@todo
                val sq:Seq[String] = stg.split(" ");
                val it = sq.elements;
                it.next;
                for( val c <- it ) {
                  makeBox( ind+len2-2, c );
                  makeBreak();
                }
              }*/
              //makeBox( ind, stg.substring( len2, stg.length() ));
              makeBreak();
              traverse( node.child.elements, ind + step );
              makeBox( cur, etg );
            } else { // it does not fit, dump everything
              val sb = new StringBuffer();
              val tmp = { Utility.toXML1(node,pmap,sb); sb.toString()};
              makeBox( ind, tmp );
              makeBreak();
            }
        }
      }
    }

  protected def traverse( it:Iterator[Node], ind:int ):unit = {
    for( val c <- it ) {
      traverse( c, ind );
      makeBreak();
    }
  }

  // public convenience methods

  /** returns a formatted string containing well-formed XML with
   *  default namespace prefix mapping
   *  @param n the node to be serialized
   */
  def format(n: Node): String = format(n, Utility.defaultPrefixes( n ));

  /** returns a formatted string containing well-formed XML with
   * given namespace to prefix mapping
   * @param n the node to be serialized
   * @param pmap the namespace to prefix mapping
   */
  def format(n: Node, pmap: Map[String,String]): String = {
    val sb = new StringBuffer();
    format( n, pmap, sb );
    sb.toString();
  }

  /* returns a formatted string containing well-formed XML nodes with
  *  default namespace prefix mapping
  */
  def format( nodes:Seq[Node] ):String = {
    format(nodes, Utility.defaultPrefixes( nodes ))
  }

  /** returns a formatted string containing well-formed XML
   * @param nodes the sequence of nodes to be serialized
   * @param pmap the namespace to prefix mapping
   */
  def format( nodes:Seq[Node], pmap:Map[String,String] ):String = {
    var sb = new StringBuffer();
    format( nodes, pmap, sb );
    sb.toString();
  }

  /** appends a formatted string containing well-formed XML with
   * the given namespace to prefix mapping to the given stringbuffer
   * @param n the node to be serialized
   * @param pmap the namespace to prefix mapping
   * @param sb the string buffer to which to append to
   */
  def format( nodes: Seq[Node], pmap: Map[String,String], sb: StringBuffer ): Unit = {    for( val n <- nodes.elements ) {
      sb.append(format( n, pmap ))
    }
  }
}