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 public class TableBlockParser
36 implements BlockParser
37 {
38
39
40
41 private static final Pattern TABLE_PATTERN = Pattern.compile( "^\\s*([|].*[|])+\\s*$" );
42
43
44
45
46 private FormatedTextParser textParser;
47
48
49 public final boolean accept( final String line )
50 {
51 return TABLE_PATTERN.matcher( line ).lookingAt();
52 }
53
54
55 public final Block visit( final String line, final ByLineSource source )
56 throws ParseException
57 {
58 if ( !accept( line ) )
59 {
60 throw new IllegalAccessError( "call accept before this ;)" );
61 }
62
63 final List<Block> rows = new ArrayList<>();
64 String l = line;
65
66 do
67 {
68 final Matcher m = TABLE_PATTERN.matcher( l );
69 if ( m.lookingAt() )
70 {
71 final List<Block> cells = new ArrayList<>();
72
73
74 for ( int lh = l.indexOf( '|' ) + 1, rh; ( rh = l.indexOf( '|', lh ) ) != -1; lh = rh + 1 )
75 {
76 final Block[] bs = textParser.parse( l.substring( lh, rh ).trim() );
77 if ( bs.length == 1 && bs[0] instanceof BoldBlock )
78 {
79 final Block[] tmp = ( (BoldBlock) bs[0] ).getBlocks();
80 cells.add( new TableCellHeaderBlock( tmp ) );
81 }
82 else
83 {
84 cells.add( new TableCellBlock( bs ) );
85 }
86 }
87 rows.add( new TableRowBlock( cells.toArray( new Block[] {} ) ) );
88 }
89
90 }
91 while ( ( l = source.getNextLine() ) != null && accept( l ) );
92
93 assert rows.size() >= 1;
94
95 return new TableBlock( rows.toArray( new Block[] {} ) );
96 }
97
98
99
100
101
102
103 public final void setTextParser( final FormatedTextParser textParser )
104 {
105 if ( textParser == null )
106 {
107 throw new IllegalArgumentException( "argument can't be null" );
108 }
109
110 this.textParser = textParser;
111 }
112 }