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 public static class DoNothingCallback implements Callback {
42 public void onPlainText(String text) {
46 public void onMarkup(WikiTokenizer wikiTokenizer) {
50 public void onWikiLink(WikiTokenizer wikiTokenizer) {
54 public void onNewline(WikiTokenizer wikiTokenizer) {
58 public void onFunction(WikiTokenizer tokenizer, String functionName,
59 List<String> functionPositionArgs, Map<String, String> functionNamedArgs) {
63 public void onHeading(WikiTokenizer wikiTokenizer) {
67 public void onListItem(WikiTokenizer wikiTokenizer) {
71 public void onComment(WikiTokenizer wikiTokenizer) {
75 public void onHtml(WikiTokenizer wikiTokenizer) {
79 //private static final Pattern wikiTokenEvent = Pattern.compile("($)", Pattern.MULTILINE);
80 private static final Pattern wikiTokenEvent = Pattern.compile("(" +
83 "\\||" + // Need the | because we might have to find unescaped pipes
84 "=|" + // Need the = because we might have to find unescaped =
87 "$)", Pattern.MULTILINE);
88 private static final String listChars = "*#:;";
91 final String wikiText;
92 final Matcher matcher;
94 boolean justReturnedNewline = true;
95 int lastLineStart = 0;
99 final List<String> errors = new ArrayList<String>();
100 final List<String> tokenStack = new ArrayList<String>();
103 private String headingWikiText;
104 private int headingDepth;
105 private int listPrefixEnd;
106 private boolean isPlainText;
107 private boolean isMarkup;
108 private boolean isComment;
109 private boolean isFunction;
110 private boolean isWikiLink;
111 private boolean isHtml;
112 private int firstUnescapedPipePos;
114 private int lastUnescapedPipePos;
115 private int lastUnescapedEqualsPos;
116 private final List<String> positionArgs = new ArrayList<String>();
117 private final Map<String,String> namedArgs = new LinkedHashMap<String,String>();
120 public WikiTokenizer(final String wikiText) {
121 this(wikiText, true);
124 public WikiTokenizer(String wikiText, final boolean isNewline) {
125 wikiText = wikiText.replaceAll("\u2028", "\n");
126 wikiText = wikiText.replaceAll("\u0085", "\n");
127 this.wikiText = wikiText;
128 this.matcher = wikiTokenEvent.matcher(wikiText);
129 justReturnedNewline = isNewline;
132 private void clear() {
136 headingWikiText = null;
146 firstUnescapedPipePos = -1;
147 lastUnescapedPipePos = -1;
148 lastUnescapedEqualsPos = -1;
149 positionArgs.clear();
153 private static final Pattern POSSIBLE_WIKI_TEXT = Pattern.compile(
161 public static void dispatch(final String wikiText, final boolean isNewline, final Callback callback) {
163 if (!POSSIBLE_WIKI_TEXT.matcher(wikiText).find()) {
164 callback.onPlainText(wikiText);
166 final WikiTokenizer tokenizer = new WikiTokenizer(wikiText, isNewline);
167 while (tokenizer.nextToken() != null) {
168 if (tokenizer.isPlainText()) {
169 callback.onPlainText(tokenizer.token());
170 } else if (tokenizer.isMarkup()) {
171 callback.onMarkup(tokenizer);
172 } else if (tokenizer.isWikiLink) {
173 callback.onWikiLink(tokenizer);
174 } else if (tokenizer.isNewline()) {
175 callback.onNewline(tokenizer);
176 } else if (tokenizer.isFunction()) {
177 callback.onFunction(tokenizer, tokenizer.functionName(), tokenizer.functionPositionArgs(), tokenizer.functionNamedArgs());
178 } else if (tokenizer.isHeading()) {
179 callback.onHeading(tokenizer);
180 } else if (tokenizer.isListItem()) {
181 callback.onListItem(tokenizer);
182 } else if (tokenizer.isComment()) {
183 callback.onComment(tokenizer);
184 } else if (tokenizer.isHtml()) {
185 callback.onHtml(tokenizer);
186 } else if (!tokenizer.errors.isEmpty()) {
187 // Log was already printed....
189 throw new IllegalStateException("Unknown wiki state: " + tokenizer.token());
195 public List<String> errors() {
199 public boolean isNewline() {
200 return justReturnedNewline;
203 public void returnToLineStart() {
204 end = start = lastLineStart;
205 justReturnedNewline = true;
208 public boolean isHeading() {
209 return headingWikiText != null;
212 public String headingWikiText() {
214 return headingWikiText;
217 public int headingDepth() {
222 public boolean isMarkup() {
226 public boolean isComment() {
230 public boolean isListItem() {
231 return listPrefixEnd != -1;
234 public String listItemPrefix() {
236 return wikiText.substring(start, listPrefixEnd);
239 public static String getListTag(char c) {
246 public String listItemWikiText() {
248 return wikiText.substring(listPrefixEnd, end);
251 public boolean isFunction() {
255 public String functionName() {
258 if (firstUnescapedPipePos != -1) {
259 return trimNewlines(wikiText.substring(start + 2, firstUnescapedPipePos).trim());
261 return trimNewlines(wikiText.substring(start + 2, end - 2).trim());
264 public List<String> functionPositionArgs() {
268 public Map<String, String> functionNamedArgs() {
272 public boolean isPlainText() {
276 public boolean isWikiLink() {
280 public String wikiLinkText() {
283 if (lastUnescapedPipePos != -1) {
284 return trimNewlines(wikiText.substring(lastUnescapedPipePos + 1, end - 2));
286 assert start + 2 < wikiText.length() && end >= 2: wikiText;
287 return trimNewlines(wikiText.substring(start + 2, end - 2));
290 public String wikiLinkDest() {
293 if (firstUnescapedPipePos != -1) {
294 return trimNewlines(wikiText.substring(start + 2, firstUnescapedPipePos));
299 public boolean isHtml() {
303 public boolean remainderStartsWith(final String prefix) {
304 return wikiText.startsWith(prefix, start);
307 public void nextLine() {
308 final int oldStart = start;
309 while(nextToken() != null && !isNewline()) {}
317 public WikiTokenizer nextToken() {
322 if (justReturnedNewline) {
323 lastLineStart = start;
328 final int len = wikiText.length();
333 // Eat a newline if we're looking at one:
334 final boolean atNewline = wikiText.charAt(end) == '\n' || wikiText.charAt(end) == '\u2028';
336 justReturnedNewline = true;
341 if (justReturnedNewline) {
342 justReturnedNewline = false;
344 final char firstChar = wikiText.charAt(end);
345 if (firstChar == '=') {
346 final int headerStart = end;
348 while (++end < len && wikiText.charAt(end) == '=') {}
349 final int headerTitleStart = end;
350 headingDepth = headerTitleStart - headerStart;
353 final int nextNewline = safeIndexOf(wikiText, end, "\n", "\n");
354 final int closingEquals = escapedFindEnd(end, "=");
355 if (wikiText.charAt(closingEquals - 1) == '=') {
356 end = closingEquals - 1;
361 final int headerTitleEnd = end;
362 headingWikiText = wikiText.substring(headerTitleStart, headerTitleEnd);
364 while (end < len && ++end < len && wikiText.charAt(end) == '=') {}
365 final int headerEnd = end;
366 if (headerEnd - headerTitleEnd != headingDepth) {
367 errors.add("Mismatched header depth: " + token());
371 if (listChars.indexOf(firstChar) != -1) {
372 while (++end < len && listChars.indexOf(wikiText.charAt(end)) != -1) {}
374 end = escapedFindEnd(start, "\n");
379 if (wikiText.startsWith("'''", start)) {
385 if (wikiText.startsWith("''", start)) {
391 if (wikiText.startsWith("[[", start)) {
392 end = escapedFindEnd(start + 2, "]]");
393 isWikiLink = errors.isEmpty();
397 if (wikiText.startsWith("{{", start)) {
398 end = escapedFindEnd(start + 2, "}}");
399 isFunction = errors.isEmpty();
403 if (wikiText.startsWith("<pre>", start)) {
404 end = safeIndexOf(wikiText, start, "</pre>", "\n");
409 if (wikiText.startsWith("<math>", start)) {
410 end = safeIndexOf(wikiText, start, "</math>", "\n");
415 if (wikiText.startsWith("<!--", start)) {
417 end = safeIndexOf(wikiText, start, "-->", "\n");
421 if (wikiText.startsWith("}}", start) || wikiText.startsWith("]]", start)) {
422 errors.add("Close without open!");
427 if (wikiText.charAt(start) == '|' || wikiText.charAt(start) == '=') {
434 if (this.matcher.find(start)) {
435 end = this.matcher.start(1);
438 errors.add("Empty group: " + this.matcher.group());
444 end = wikiText.length();
448 if (!errors.isEmpty()) {
449 System.err.println("Errors: " + errors + ", token=" + token());
455 public String token() {
456 final String token = wikiText.substring(start, end);
457 assert token.equals("\n") || !token.endsWith("\n") : "token='" + token + "'";
461 private int escapedFindEnd(final int start, final String toFind) {
462 assert tokenStack.isEmpty();
464 final boolean insideFunction = toFind.equals("}}");
467 int firstNewline = -1;
468 while (end < wikiText.length()) {
469 if (matcher.find(end)) {
470 final String matchText = matcher.group();
471 final int matchStart = matcher.start();
473 assert matcher.end() > end || matchText.length() == 0: "Group=" + matcher.group();
474 if (matchText.length() == 0) {
475 assert matchStart == wikiText.length() || wikiText.charAt(matchStart) == '\n' : wikiText + ", " + matchStart;
476 if (firstNewline == -1) {
477 firstNewline = matcher.end();
479 if (tokenStack.isEmpty() && toFind.equals("\n")) {
483 } else if (tokenStack.isEmpty() && matchText.equals(toFind)) {
484 // The normal return....
485 if (insideFunction) {
486 addFunctionArg(insideFunction, matchStart);
488 return matcher.end();
489 } else if (matchText.equals("[[") || matchText.equals("{{")) {
490 tokenStack.add(matchText);
491 } else if (matchText.equals("]]") || matchText.equals("}}")) {
492 if (tokenStack.size() > 0) {
493 final String removed = tokenStack.remove(tokenStack.size() - 1);
494 if (removed.equals("{{") && !matcher.group().equals("}}")) {
495 errors.add("Unmatched {{ error: " + wikiText.substring(start));
496 return safeIndexOf(wikiText, start, "\n", "\n");
497 } else if (removed.equals("[[") && !matcher.group().equals("]]")) {
498 errors.add("Unmatched [[ error: " + wikiText.substring(start));
499 return safeIndexOf(wikiText, start, "\n", "\n");
502 errors.add("Pop too many error: " + wikiText.substring(start).replaceAll("\n", "\\\\n"));
503 // If we were looking for a newline
504 return safeIndexOf(wikiText, start, "\n", "\n");
506 } else if (matchText.equals("|")) {
507 if (tokenStack.isEmpty()) {
508 addFunctionArg(insideFunction, matchStart);
510 } else if (matchText.equals("=")) {
511 if (tokenStack.isEmpty()) {
512 lastUnescapedEqualsPos = matchStart;
514 // Do nothing. These can match spuriously, and if it's not the thing
515 // we're looking for, keep on going.
516 } else if (matchText.equals("<!--")) {
517 end = wikiText.indexOf("-->");
519 errors.add("Unmatched <!-- error: " + wikiText.substring(start));
520 return safeIndexOf(wikiText, start, "\n", "\n");
522 } else if (matchText.equals("''")) {
525 assert false : "Match text='" + matchText + "'";
526 throw new IllegalStateException();
529 // Hmmm, we didn't find the closing symbol we were looking for...
530 errors.add("Couldn't find: " + toFind + ", "+ wikiText.substring(start));
531 return safeIndexOf(wikiText, start, "\n", "\n");
534 // Inside the while loop. Just go forward.
535 end = Math.max(end, matcher.end());
537 if (toFind.equals("\n") && tokenStack.isEmpty()) {
538 // We were looking for the end, we got it.
541 if (firstNewline != -1) {
542 errors.add("Couldn't find: " + toFind + ", "+ wikiText.substring(start));
548 private void addFunctionArg(final boolean insideFunction, final int matchStart) {
549 if (firstUnescapedPipePos == -1) {
550 firstUnescapedPipePos = lastUnescapedPipePos = matchStart;
551 } else if (insideFunction) {
552 if (lastUnescapedEqualsPos > lastUnescapedPipePos) {
553 final String key = wikiText.substring(lastUnescapedPipePos + 1, lastUnescapedEqualsPos);
554 final String value = wikiText.substring(lastUnescapedEqualsPos + 1, matchStart);
555 namedArgs.put(trimNewlines(key), trimNewlines(value));
557 final String value = wikiText.substring(lastUnescapedPipePos + 1, matchStart);
558 positionArgs.add(trimNewlines(value));
561 lastUnescapedPipePos = matchStart;
564 static final String trimNewlines(String s) {
565 while (s.startsWith("\n")) {
568 while (s.endsWith("\n")) {
569 s = s.substring(0, s.length() - 1);
571 return s.replaceAll("\n", " ");
574 static int safeIndexOf(final String s, final int start, final String target, final String backup) {
575 int close = s.indexOf(target, start);
577 // Don't step over a \n.
578 return close + (target.equals("\n") ? 0 : target.length());
580 close = s.indexOf(backup, start);
582 return close + (backup.equals("\n") ? 0 : backup.length());
587 public static String toPlainText(final String wikiText) {
588 final WikiTokenizer wikiTokenizer = new WikiTokenizer(wikiText);
589 final StringBuilder builder = new StringBuilder();
590 while (wikiTokenizer.nextToken() != null) {
591 if (wikiTokenizer.isPlainText()) {
592 builder.append(wikiTokenizer.token());
593 } else if (wikiTokenizer.isWikiLink()) {
594 builder.append(wikiTokenizer.wikiLinkText());
595 } else if (wikiTokenizer.isNewline()) {
596 builder.append("\n");
597 } else if (wikiTokenizer.isFunction()) {
598 builder.append(wikiTokenizer.token());
601 return builder.toString();
604 public static StringBuilder appendFunction(final StringBuilder builder, final String name, List<String> args,
605 final Map<String, String> namedArgs) {
606 builder.append(name);
607 for (final String arg : args) {
608 builder.append("|").append(arg);
610 for (final Map.Entry<String, String> entry : namedArgs.entrySet()) {
611 builder.append("|").append(entry.getKey()).append("=").append(entry.getValue());