01: // Copyright (C) 2003,2004,2005 by Object Mentor, Inc. All rights reserved.
02: // Released under the terms of the GNU General Public License version 2 or later.
03: package fitnesse.wikitext.widgets;
04:
05: import java.util.regex.Matcher;
06: import java.util.regex.Pattern;
07:
08: public class ListWidget extends ParentWidget {
09: public static final String REGEXP = "(?:^[ \\t]+[\\*\\d][^\r\n]*"
10: + LineBreakWidget.REGEXP + "?)+";
11: private static final Pattern pattern = Pattern
12: .compile("([ \\t]+)([\\*\\d])([^\r\n]*)");
13:
14: private boolean ordered = false;
15: private int level;
16:
17: public ListWidget(ParentWidget parent, String text)
18: throws Exception {
19: super (parent);
20: Matcher match = pattern.matcher(text);
21: if (match.find()) {
22: level = findLevel(match);
23: ordered = !("*".equals(match.group(2)));
24: }
25: buildList(text);
26: }
27:
28: private ListWidget(ParentWidget parent, Matcher match) {
29: super (parent);
30: level = findLevel(match);
31: ordered = !("*".equals(match.group(2)));
32: }
33:
34: private String buildList(String text) throws Exception {
35: if (text == null)
36: return null;
37: Matcher match = pattern.matcher(text);
38: if (match.find()) {
39: int level = findLevel(match);
40: if (level > this .level) {
41: ListWidget childList = new ListWidget(this , match);
42: String remainder = childList.buildList(text);
43: return buildList(remainder);
44: } else if (level < this .level)
45: return text;
46: else {
47: String listItemContent = match.group(3).trim();
48: // the trim is real important. It removes the starting spaces that could cause the item to be recognized
49: // as another list.
50: new ListItemWidget(this , listItemContent,
51: this .level + 1);
52: return buildList(text.substring(match.end()));
53: }
54: } else
55: return null;
56: }
57:
58: public boolean isOrdered() {
59: return ordered;
60: }
61:
62: public int getLevel() {
63: return level;
64: }
65:
66: public String render() throws Exception {
67: String tagValue = ordered ? "ol" : "ul";
68: StringBuffer html = new StringBuffer();
69: appendTabs(html);
70: html.append("<").append(tagValue).append(">").append("\n");
71: html.append(childHtml());
72: appendTabs(html);
73: html.append("</").append(tagValue).append(">").append("\n");
74:
75: return html.toString();
76: }
77:
78: private void appendTabs(StringBuffer html) {
79: for (int i = 0; i < level; i++)
80: html.append("\t");
81: }
82:
83: private int findLevel(Matcher match) {
84: return match.group(1).length() - 1;
85: }
86: }
|