1 package org.apache.maven.doxia.module.twiki.parser;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 import java.util.ArrayList;
23 import java.util.List;
24 import java.util.regex.Matcher;
25 import java.util.regex.Pattern;
26
27 import org.apache.maven.doxia.util.ByLineSource;
28 import org.apache.maven.doxia.parser.ParseException;
29
30
31
32
33
34
35
36 public class TableBlockParser
37 implements BlockParser
38 {
39
40
41
42 private static final Pattern TABLE_PATTERN = Pattern.compile( "^\\s*([|].*[|])+\\s*$" );
43
44
45
46
47 private FormatedTextParser textParser;
48
49
50 public final boolean accept( final String line )
51 {
52 return TABLE_PATTERN.matcher( line ).lookingAt();
53 }
54
55
56
57
58 public final Block visit( final String line, final ByLineSource source )
59 throws ParseException
60 {
61 if ( !accept( line ) )
62 {
63 throw new IllegalAccessError( "call accept before this ;)" );
64 }
65
66 final List<Block> rows = new ArrayList<Block>();
67 String l = line;
68
69 do
70 {
71 final Matcher m = TABLE_PATTERN.matcher( l );
72 if ( m.lookingAt() )
73 {
74 final List<Block> cells = new ArrayList<Block>();
75
76
77 for ( int lh = l.indexOf( '|' ) + 1, rh; ( rh = l.indexOf( '|', lh ) ) != -1; lh = rh + 1 )
78 {
79 final Block[] bs = textParser.parse( l.substring( lh, rh ).trim() );
80 if ( bs.length == 1 && bs[0] instanceof BoldBlock )
81 {
82 final Block[] tmp = ( (BoldBlock) bs[0] ).getBlocks();
83 cells.add( new TableCellHeaderBlock( tmp ) );
84 }
85 else
86 {
87 cells.add( new TableCellBlock( bs ) );
88 }
89 }
90 rows.add( new TableRowBlock( (Block[]) cells.toArray( new Block[] {} ) ) );
91 }
92
93 }
94 while ( ( l = source.getNextLine() ) != null && accept( l ) );
95
96 assert rows.size() >= 1;
97
98 return new TableBlock( rows.toArray( new Block[] {} ) );
99 }
100
101
102
103
104
105
106 public final void setTextParser( final FormatedTextParser textParser )
107 {
108 if ( textParser == null )
109 {
110 throw new IllegalArgumentException( "argument can't be null" );
111 }
112
113 this.textParser = textParser;
114 }
115 }