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:
12: private static final Pattern pattern = Pattern
13: .compile("([ \\t]+)([\\*\\d])([^\r\n]*)");
14:
15: private boolean ordered = false;
16:
17: private int level;
18:
19: public ListWidget(ParentWidget parent, String text)
20: throws Exception {
21: super (parent);
22: Matcher match = pattern.matcher(text);
23: if (match.find()) {
24: level = findLevel(match);
25: ordered = !("*".equals(match.group(2)));
26: }
27: buildList(text);
28: }
29:
30: private ListWidget(ParentWidget parent, Matcher match) {
31: super (parent);
32: level = findLevel(match);
33: ordered = !("*".equals(match.group(2)));
34: }
35:
36: private String buildList(String text) throws Exception {
37: if (text == null)
38: return null;
39: Matcher match = pattern.matcher(text);
40: if (match.find()) {
41: int level = findLevel(match);
42: if (level > this .level) {
43: ListWidget childList = new ListWidget(this , match);
44: String remainder = childList.buildList(text);
45: return buildList(remainder);
46: } else if (level < this .level)
47: return text;
48: else {
49: String listItemContent = match.group(3).trim();
50: // the trim is real important. It removes the starting spaces
51: // that could cause the item to be recognized
52: // as another list.
53: new ListItemWidget(this , listItemContent,
54: this .level + 1);
55: return buildList(text.substring(match.end()));
56: }
57: } else
58: return null;
59: }
60:
61: public boolean isOrdered() {
62: return ordered;
63: }
64:
65: public int getLevel() {
66: return level;
67: }
68:
69: public String render() throws Exception {
70: String tagValue = ordered ? "ol" : "ul";
71: StringBuffer html = new StringBuffer();
72: appendTabs(html);
73: html.append("<").append(tagValue).append(">").append("\n");
74: html.append(childHtml());
75: appendTabs(html);
76: html.append("</").append(tagValue).append(">").append("\n");
77:
78: return html.toString();
79: }
80:
81: private void appendTabs(StringBuffer html) {
82: for (int i = 0; i < level; i++)
83: html.append("\t");
84: }
85:
86: private int findLevel(Matcher match) {
87: return match.group(1).length() - 1;
88: }
89: }
|