1 // Copyright 2011 Google Inc. All Rights Reserved.
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
7 // http://www.apache.org/licenses/LICENSE-2.0
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
15 package com.hughes.android.dictionary.parser;
17 import java.util.ArrayList;
18 import java.util.LinkedHashMap;
19 import java.util.List;
21 import java.util.regex.Matcher;
22 import java.util.regex.Pattern;
24 public final class WikiTokenizer {
26 public static interface Callback {
27 void onPlainText(final String text);
28 void onMarkup(WikiTokenizer wikiTokenizer);
29 void onWikiLink(WikiTokenizer wikiTokenizer);
30 void onNewline(WikiTokenizer wikiTokenizer);
31 void onFunction(final WikiTokenizer tokenizer, String functionName, List<String> functionPositionArgs,
32 Map<String, String> functionNamedArgs);
33 void onHeading(WikiTokenizer wikiTokenizer);
34 void onListItem(WikiTokenizer wikiTokenizer);
35 void onComment(WikiTokenizer wikiTokenizer);
36 void onHtml(WikiTokenizer wikiTokenizer);
39 //private static final Pattern wikiTokenEvent = Pattern.compile("($)", Pattern.MULTILINE);
40 private static final Pattern wikiTokenEvent = Pattern.compile("(" +
43 "\\||" + // Need the | because we might have to find unescaped pipes
44 "=|" + // Need the = because we might have to find unescaped =
47 "$)", Pattern.MULTILINE);
48 private static final String listChars = "*#:;";
51 final String wikiText;
52 final Matcher matcher;
54 boolean justReturnedNewline = true;
55 int lastLineStart = 0;
59 final List<String> errors = new ArrayList<String>();
60 final List<String> tokenStack = new ArrayList<String>();
63 private String headingWikiText;
64 private int headingDepth;
65 private int listPrefixEnd;
66 private boolean isPlainText;
67 private boolean isMarkup;
68 private boolean isComment;
69 private boolean isFunction;
70 private boolean isWikiLink;
71 private boolean isHtml;
72 private int firstUnescapedPipePos;
74 private int lastUnescapedPipePos;
75 private int lastUnescapedEqualsPos;
76 private final List<String> positionArgs = new ArrayList<String>();
77 private final Map<String,String> namedArgs = new LinkedHashMap<String,String>();
80 public WikiTokenizer(final String wikiText) {
84 public WikiTokenizer(final String wikiText, final boolean isNewline) {
85 this.wikiText = wikiText.replaceAll("\u2028", "\n");
86 this.matcher = wikiTokenEvent.matcher(wikiText);
87 justReturnedNewline = isNewline;
90 private void clear() {
94 headingWikiText = null;
104 firstUnescapedPipePos = -1;
105 lastUnescapedPipePos = -1;
106 lastUnescapedEqualsPos = -1;
107 positionArgs.clear();
111 private static final Pattern POSSIBLE_WIKI_TEXT = Pattern.compile(
119 public static void dispatch(final String wikiText, final boolean isNewline, final Callback callback) {
121 if (!POSSIBLE_WIKI_TEXT.matcher(wikiText).find()) {
122 callback.onPlainText(wikiText);
124 final WikiTokenizer tokenizer = new WikiTokenizer(wikiText, isNewline);
125 while (tokenizer.nextToken() != null) {
126 if (tokenizer.isPlainText()) {
127 callback.onPlainText(tokenizer.token());
128 } else if (tokenizer.isMarkup()) {
129 callback.onMarkup(tokenizer);
130 } else if (tokenizer.isWikiLink) {
131 callback.onWikiLink(tokenizer);
132 } else if (tokenizer.isNewline()) {
133 callback.onNewline(tokenizer);
134 } else if (tokenizer.isFunction()) {
135 callback.onFunction(tokenizer, tokenizer.functionName(), tokenizer.functionPositionArgs(), tokenizer.functionNamedArgs());
136 } else if (tokenizer.isHeading()) {
137 callback.onHeading(tokenizer);
138 } else if (tokenizer.isListItem()) {
139 callback.onListItem(tokenizer);
140 } else if (tokenizer.isComment()) {
141 callback.onComment(tokenizer);
142 } else if (tokenizer.isHtml()) {
143 callback.onHtml(tokenizer);
144 } else if (!tokenizer.errors.isEmpty()) {
145 // Log was already printed....
147 throw new IllegalStateException("Unknown wiki state: " + tokenizer.token());
153 public List<String> errors() {
157 public boolean isNewline() {
158 return justReturnedNewline;
161 public void returnToLineStart() {
162 end = start = lastLineStart;
163 justReturnedNewline = true;
166 public boolean isHeading() {
167 return headingWikiText != null;
170 public String headingWikiText() {
172 return headingWikiText;
175 public int headingDepth() {
180 public boolean isMarkup() {
184 public boolean isComment() {
188 public boolean isListItem() {
189 return listPrefixEnd != -1;
192 public String listItemPrefix() {
194 return wikiText.substring(start, listPrefixEnd);
197 public String listItemWikiText() {
199 return wikiText.substring(listPrefixEnd, end);
202 public boolean isFunction() {
206 public String functionName() {
209 if (firstUnescapedPipePos != -1) {
210 return trimNewlines(wikiText.substring(start + 2, firstUnescapedPipePos).trim());
212 return trimNewlines(wikiText.substring(start + 2, end - 2).trim());
215 public List<String> functionPositionArgs() {
219 public Map<String, String> functionNamedArgs() {
223 public boolean isPlainText() {
227 public boolean isWikiLink() {
231 public String wikiLinkText() {
234 if (lastUnescapedPipePos != -1) {
235 return trimNewlines(wikiText.substring(lastUnescapedPipePos + 1, end - 2));
237 assert start + 2 < wikiText.length() && end >= 2: wikiText;
238 return trimNewlines(wikiText.substring(start + 2, end - 2));
241 public String wikiLinkDest() {
244 if (firstUnescapedPipePos != -1) {
245 return trimNewlines(wikiText.substring(start + 2, firstUnescapedPipePos));
250 public boolean isHtml() {
254 public boolean remainderStartsWith(final String prefix) {
255 return wikiText.startsWith(prefix, start);
258 public void nextLine() {
259 final int oldStart = start;
260 while(nextToken() != null && !isNewline()) {}
268 public WikiTokenizer nextToken() {
273 if (justReturnedNewline) {
274 lastLineStart = start;
279 final int len = wikiText.length();
284 // Eat a newline if we're looking at one:
285 final boolean atNewline = wikiText.charAt(end) == '\n' || wikiText.charAt(end) == '\u2028';
287 justReturnedNewline = true;
292 if (justReturnedNewline) {
293 justReturnedNewline = false;
295 final char firstChar = wikiText.charAt(end);
296 if (firstChar == '=') {
297 final int headerStart = end;
299 while (++end < len && wikiText.charAt(end) == '=') {}
300 final int headerTitleStart = end;
301 headingDepth = headerTitleStart - headerStart;
304 final int nextNewline = safeIndexOf(wikiText, end, "\n", "\n");
305 final int closingEquals = escapedFindEnd(end, "=");
306 if (wikiText.charAt(closingEquals - 1) == '=') {
307 end = closingEquals - 1;
312 final int headerTitleEnd = end;
313 headingWikiText = wikiText.substring(headerTitleStart, headerTitleEnd);
315 while (end < len && ++end < len && wikiText.charAt(end) == '=') {}
316 final int headerEnd = end;
317 if (headerEnd - headerTitleEnd != headingDepth) {
318 errors.add("Mismatched header depth: " + token());
322 if (listChars.indexOf(firstChar) != -1) {
323 while (++end < len && listChars.indexOf(wikiText.charAt(end)) != -1) {}
325 end = escapedFindEnd(start, "\n");
330 if (wikiText.startsWith("'''", start)) {
336 if (wikiText.startsWith("''", start)) {
342 if (wikiText.startsWith("[[", start)) {
343 end = escapedFindEnd(start + 2, "]]");
344 isWikiLink = errors.isEmpty();
348 if (wikiText.startsWith("{{", start)) {
349 end = escapedFindEnd(start + 2, "}}");
350 isFunction = errors.isEmpty();
354 if (wikiText.startsWith("<pre>", start)) {
355 end = safeIndexOf(wikiText, start, "</pre>", "\n");
360 if (wikiText.startsWith("<math>", start)) {
361 end = safeIndexOf(wikiText, start, "</math>", "\n");
366 if (wikiText.startsWith("<!--", start)) {
368 end = safeIndexOf(wikiText, start, "-->", "\n");
372 if (wikiText.startsWith("}}", start) || wikiText.startsWith("]]", start)) {
373 errors.add("Close without open!");
378 if (wikiText.charAt(start) == '|' || wikiText.charAt(start) == '=') {
385 if (this.matcher.find(start)) {
386 end = this.matcher.start(1);
389 errors.add("Empty group: " + this.matcher.group());
395 end = wikiText.length();
399 if (!errors.isEmpty()) {
400 System.err.println("Errors: " + errors + ", token=" + token());
406 public String token() {
407 final String token = wikiText.substring(start, end);
408 assert token.equals("\n") || !token.endsWith("\n") : "token='" + token + "'";
412 private int escapedFindEnd(final int start, final String toFind) {
413 assert tokenStack.isEmpty();
415 final boolean insideFunction = toFind.equals("}}");
418 int firstNewline = -1;
419 while (end < wikiText.length()) {
420 if (matcher.find(end)) {
421 final String matchText = matcher.group();
422 final int matchStart = matcher.start();
424 assert matcher.end() > end || matchText.length() == 0: "Group=" + matcher.group();
425 if (matchText.length() == 0) {
426 assert matchStart == wikiText.length() || wikiText.charAt(matchStart) == '\n' : wikiText + ", " + matchStart;
427 if (firstNewline == -1) {
428 firstNewline = matcher.end();
430 if (tokenStack.isEmpty() && toFind.equals("\n")) {
434 } else if (tokenStack.isEmpty() && matchText.equals(toFind)) {
435 // The normal return....
436 if (insideFunction) {
437 addFunctionArg(insideFunction, matchStart);
439 return matcher.end();
440 } else if (matchText.equals("[[") || matchText.equals("{{")) {
441 tokenStack.add(matchText);
442 } else if (matchText.equals("]]") || matchText.equals("}}")) {
443 if (tokenStack.size() > 0) {
444 final String removed = tokenStack.remove(tokenStack.size() - 1);
445 if (removed.equals("{{") && !matcher.group().equals("}}")) {
446 errors.add("Unmatched {{ error: " + wikiText.substring(start));
447 return safeIndexOf(wikiText, start, "\n", "\n");
448 } else if (removed.equals("[[") && !matcher.group().equals("]]")) {
449 errors.add("Unmatched [[ error: " + wikiText.substring(start));
450 return safeIndexOf(wikiText, start, "\n", "\n");
453 errors.add("Pop too many error: " + wikiText.substring(start).replaceAll("\n", "\\\\n"));
454 // If we were looking for a newline
455 return safeIndexOf(wikiText, start, "\n", "\n");
457 } else if (matchText.equals("|")) {
458 if (tokenStack.isEmpty()) {
459 addFunctionArg(insideFunction, matchStart);
461 } else if (matchText.equals("=")) {
462 if (tokenStack.isEmpty()) {
463 lastUnescapedEqualsPos = matchStart;
465 // Do nothing. These can match spuriously, and if it's not the thing
466 // we're looking for, keep on going.
467 } else if (matchText.equals("<!--")) {
468 end = wikiText.indexOf("-->");
470 errors.add("Unmatched <!-- error: " + wikiText.substring(start));
471 return safeIndexOf(wikiText, start, "\n", "\n");
473 } else if (matchText.equals("''")) {
476 assert false : "Match text='" + matchText + "'";
477 throw new IllegalStateException();
480 // Hmmm, we didn't find the closing symbol we were looking for...
481 errors.add("Couldn't find: " + toFind + ", "+ wikiText.substring(start));
482 return safeIndexOf(wikiText, start, "\n", "\n");
485 // Inside the while loop. Just go forward.
486 end = Math.max(end, matcher.end());
488 if (toFind.equals("\n") && tokenStack.isEmpty()) {
489 // We were looking for the end, we got it.
492 if (firstNewline != -1) {
493 errors.add("Couldn't find: " + toFind + ", "+ wikiText.substring(start));
499 private void addFunctionArg(final boolean insideFunction, final int matchStart) {
500 if (firstUnescapedPipePos == -1) {
501 firstUnescapedPipePos = lastUnescapedPipePos = matchStart;
502 } else if (insideFunction) {
503 if (lastUnescapedEqualsPos > lastUnescapedPipePos) {
504 final String key = wikiText.substring(lastUnescapedPipePos + 1, lastUnescapedEqualsPos);
505 final String value = wikiText.substring(lastUnescapedEqualsPos + 1, matchStart);
506 namedArgs.put(trimNewlines(key), trimNewlines(value));
508 final String value = wikiText.substring(lastUnescapedPipePos + 1, matchStart);
509 positionArgs.add(trimNewlines(value));
512 lastUnescapedPipePos = matchStart;
515 static final String trimNewlines(String s) {
516 while (s.startsWith("\n")) {
519 while (s.endsWith("\n")) {
520 s = s.substring(0, s.length() - 1);
522 return s.replaceAll("\n", " ");
525 static int safeIndexOf(final String s, final int start, final String target, final String backup) {
526 int close = s.indexOf(target, start);
528 // Don't step over a \n.
529 return close + (target.equals("\n") ? 0 : target.length());
531 close = s.indexOf(backup, start);
533 return close + (backup.equals("\n") ? 0 : backup.length());
538 public static String toPlainText(final String wikiText) {
539 final WikiTokenizer wikiTokenizer = new WikiTokenizer(wikiText);
540 final StringBuilder builder = new StringBuilder();
541 while (wikiTokenizer.nextToken() != null) {
542 if (wikiTokenizer.isPlainText()) {
543 builder.append(wikiTokenizer.token());
544 } else if (wikiTokenizer.isWikiLink()) {
545 builder.append(wikiTokenizer.wikiLinkText());
546 } else if (wikiTokenizer.isNewline()) {
547 builder.append("\n");
548 } else if (wikiTokenizer.isFunction()) {
549 builder.append(wikiTokenizer.token());
552 return builder.toString();
555 public static StringBuilder appendFunction(final StringBuilder builder, final String name, List<String> args,
556 final Map<String, String> namedArgs) {
557 builder.append(name);
558 for (final String arg : args) {
559 builder.append("|").append(arg);
561 for (final Map.Entry<String, String> entry : namedArgs.entrySet()) {
562 builder.append("|").append(entry.getKey()).append("=").append(entry.getValue());