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);
38 //private static final Pattern wikiTokenEvent = Pattern.compile("($)", Pattern.MULTILINE);
39 private static final Pattern wikiTokenEvent = Pattern.compile("(" +
42 "\\||" + // Need the | because we might have to find unescaped pipes
43 "=|" + // Need the = because we might have to find unescaped =
46 "$)", Pattern.MULTILINE);
47 private static final String listChars = "*#:;";
50 final String wikiText;
51 final Matcher matcher;
53 boolean justReturnedNewline = true;
54 int lastLineStart = 0;
58 final List<String> errors = new ArrayList<String>();
59 final List<String> tokenStack = new ArrayList<String>();
62 private String headingWikiText;
63 private int headingDepth;
64 private int listPrefixEnd;
65 private boolean isPlainText;
66 private boolean isMarkup;
67 private boolean isComment;
68 private boolean isFunction;
69 private boolean isWikiLink;
70 private int firstUnescapedPipePos;
72 private int lastUnescapedPipePos;
73 private int lastUnescapedEqualsPos;
74 private final List<String> positionArgs = new ArrayList<String>();
75 private final Map<String,String> namedArgs = new LinkedHashMap<String,String>();
78 public WikiTokenizer(final String wikiText) {
82 public WikiTokenizer(final String wikiText, final boolean isNewline) {
83 this.wikiText = wikiText;
84 this.matcher = wikiTokenEvent.matcher(wikiText);
85 justReturnedNewline = isNewline;
88 private void clear() {
92 headingWikiText = null;
101 firstUnescapedPipePos = -1;
102 lastUnescapedPipePos = -1;
103 lastUnescapedEqualsPos = -1;
104 positionArgs.clear();
108 private static final Pattern POSSIBLE_WIKI_TEXT = Pattern.compile(
116 public static void dispatch(final String wikiText, final boolean isNewline, final Callback callback) {
118 if (!POSSIBLE_WIKI_TEXT.matcher(wikiText).find()) {
119 callback.onPlainText(wikiText);
121 final WikiTokenizer tokenizer = new WikiTokenizer(wikiText, isNewline);
122 while (tokenizer.nextToken() != null) {
123 if (tokenizer.isPlainText()) {
124 callback.onPlainText(tokenizer.token());
125 } else if (tokenizer.isMarkup()) {
126 callback.onMarkup(tokenizer);
127 } else if (tokenizer.isWikiLink) {
128 callback.onWikiLink(tokenizer);
129 } else if (tokenizer.isNewline()) {
130 callback.onNewline(tokenizer);
131 } else if (tokenizer.isFunction()) {
132 callback.onFunction(tokenizer, tokenizer.functionName(), tokenizer.functionPositionArgs(), tokenizer.functionNamedArgs());
133 } else if (tokenizer.isHeading()) {
134 callback.onHeading(tokenizer);
135 } else if (tokenizer.isListItem()) {
136 callback.onListItem(tokenizer);
137 } else if (tokenizer.isComment()) {
138 callback.onComment(tokenizer);
140 throw new IllegalStateException("Unknown wiki state.");
146 public boolean isNewline() {
147 return justReturnedNewline;
150 public void returnToLineStart() {
151 end = start = lastLineStart;
152 justReturnedNewline = true;
155 public boolean isHeading() {
156 return headingWikiText != null;
159 public String headingWikiText() {
161 return headingWikiText;
164 public int headingDepth() {
169 public boolean isMarkup() {
173 public boolean isComment() {
177 public boolean isListItem() {
178 return listPrefixEnd != -1;
181 public String listItemPrefix() {
183 return wikiText.substring(start, listPrefixEnd);
186 public String listItemWikiText() {
188 return wikiText.substring(listPrefixEnd, end);
191 public boolean isFunction() {
195 public String functionName() {
198 if (firstUnescapedPipePos != -1) {
199 return wikiText.substring(start + 2, firstUnescapedPipePos);
201 return wikiText.substring(start + 2, end - 2);
204 public List<String> functionPositionArgs() {
208 public Map<String, String> functionNamedArgs() {
212 public boolean isPlainText() {
216 public boolean isWikiLink() {
220 public String wikiLinkText() {
223 if (lastUnescapedPipePos != -1) {
224 return wikiText.substring(lastUnescapedPipePos + 1, end - 2);
226 assert start + 2 < wikiText.length() && end >= 2: wikiText;
227 return wikiText.substring(start + 2, end - 2);
230 public String wikiLinkDest() {
233 if (firstUnescapedPipePos != -1) {
234 return wikiText.substring(start + 2, firstUnescapedPipePos);
239 public boolean remainderStartsWith(final String prefix) {
240 return wikiText.startsWith(prefix, start);
243 public void nextLine() {
244 final int oldStart = start;
245 while(nextToken() != null && !isNewline()) {}
253 public WikiTokenizer nextToken() {
258 if (justReturnedNewline) {
259 lastLineStart = start;
264 final int len = wikiText.length();
269 // Eat a newline if we're looking at one:
270 final boolean atNewline = wikiText.charAt(end) == '\n' || wikiText.charAt(end) == '\u2028';
272 justReturnedNewline = true;
277 if (justReturnedNewline) {
278 justReturnedNewline = false;
280 final char firstChar = wikiText.charAt(end);
281 if (firstChar == '=') {
282 final int headerStart = end;
284 while (++end < len && wikiText.charAt(end) == '=') {}
285 final int headerTitleStart = end;
286 headingDepth = headerTitleStart - headerStart;
289 final int nextNewline = safeIndexOf(wikiText, end, "\n", "\n");
290 final int closingEquals = escapedFindEnd(end, "=");
291 if (wikiText.charAt(closingEquals - 1) == '=') {
292 end = closingEquals - 1;
297 final int headerTitleEnd = end;
298 headingWikiText = wikiText.substring(headerTitleStart, headerTitleEnd);
300 while (end < len && ++end < len && wikiText.charAt(end) == '=') {}
301 final int headerEnd = end;
302 if (headerEnd - headerTitleEnd != headingDepth) {
303 errors.add("Mismatched header depth: " + token());
307 if (listChars.indexOf(firstChar) != -1) {
308 while (++end < len && listChars.indexOf(wikiText.charAt(end)) != -1) {}
310 end = escapedFindEnd(start, "\n");
315 if (wikiText.startsWith("'''", start)) {
321 if (wikiText.startsWith("''", start)) {
327 if (wikiText.startsWith("[[", start)) {
328 end = escapedFindEnd(start + 2, "]]");
329 isWikiLink = errors.isEmpty();
333 if (wikiText.startsWith("{{", start)) {
334 end = escapedFindEnd(start + 2, "}}");
335 isFunction = errors.isEmpty();
339 if (wikiText.startsWith("<pre>", start)) {
340 end = safeIndexOf(wikiText, start, "</pre>", "\n");
344 if (wikiText.startsWith("<math>", start)) {
345 end = safeIndexOf(wikiText, start, "</math>", "\n");
349 if (wikiText.startsWith("<!--", start)) {
351 end = safeIndexOf(wikiText, start, "-->", "\n");
355 if (wikiText.startsWith("}}", start) || wikiText.startsWith("]]", start)) {
356 errors.add("Close without open!");
361 if (wikiText.charAt(start) == '|' || wikiText.charAt(start) == '=') {
368 if (this.matcher.find(start)) {
369 end = this.matcher.start(1);
372 errors.add("Empty group: " + this.matcher.group());
378 end = wikiText.length();
382 if (!errors.isEmpty()) {
383 System.err.println("Errors: " + errors + ", token=" + token());
389 public String token() {
390 final String token = wikiText.substring(start, end);
391 assert token.equals("\n") || !token.endsWith("\n") : "token='" + token + "'";
395 private int escapedFindEnd(final int start, final String toFind) {
396 assert tokenStack.isEmpty();
398 final boolean insideFunction = toFind.equals("}}");
401 int firstNewline = -1;
402 while (end < wikiText.length()) {
403 if (matcher.find(end)) {
404 final String matchText = matcher.group();
405 final int matchStart = matcher.start();
407 assert matcher.end() > end || matchText.length() == 0: "Group=" + matcher.group();
408 if (matchText.length() == 0) {
409 assert matchStart == wikiText.length() || wikiText.charAt(matchStart) == '\n';
410 if (firstNewline == -1) {
411 firstNewline = matcher.end();
413 if (tokenStack.isEmpty() && toFind.equals("\n")) {
417 } else if (tokenStack.isEmpty() && matchText.equals(toFind)) {
418 // The normal return....
419 if (insideFunction) {
420 addFunctionArg(insideFunction, matchStart);
422 return matcher.end();
423 } else if (matchText.equals("[[") || matchText.equals("{{")) {
424 tokenStack.add(matchText);
425 } else if (matchText.equals("]]") || matchText.equals("}}")) {
426 if (tokenStack.size() > 0) {
427 final String removed = tokenStack.remove(tokenStack.size() - 1);
428 if (removed.equals("{{") && !matcher.group().equals("}}")) {
429 errors.add("Unmatched {{ error: " + wikiText.substring(start));
430 return safeIndexOf(wikiText, start, "\n", "\n");
431 } else if (removed.equals("[[") && !matcher.group().equals("]]")) {
432 errors.add("Unmatched [[ error: " + wikiText.substring(start));
433 return safeIndexOf(wikiText, start, "\n", "\n");
436 errors.add("Pop too many error: " + wikiText.substring(start).replaceAll("\n", "\\\\n"));
437 // If we were looking for a newline
438 return safeIndexOf(wikiText, start, "\n", "\n");
440 } else if (matchText.equals("|")) {
441 if (tokenStack.isEmpty()) {
442 addFunctionArg(insideFunction, matchStart);
444 } else if (matchText.equals("=")) {
445 if (tokenStack.isEmpty()) {
446 lastUnescapedEqualsPos = matchStart;
448 // Do nothing. These can match spuriously, and if it's not the thing
449 // we're looking for, keep on going.
450 } else if (matchText.equals("<!--")) {
451 end = wikiText.indexOf("-->");
453 errors.add("Unmatched <!-- error: " + wikiText.substring(start));
454 return safeIndexOf(wikiText, start, "\n", "\n");
456 } else if (matchText.equals("''")) {
459 assert false : "Match text='" + matchText + "'";
460 throw new IllegalStateException();
463 // Hmmm, we didn't find the closing symbol we were looking for...
464 errors.add("Couldn't find: " + toFind + ", "+ wikiText.substring(start));
465 return safeIndexOf(wikiText, start, "\n", "\n");
468 // Inside the while loop. Just go forward.
469 end = Math.max(end, matcher.end());
471 if (toFind.equals("\n") && tokenStack.isEmpty()) {
472 // We were looking for the end, we got it.
475 if (firstNewline != -1) {
476 errors.add("Couldn't find: " + toFind + ", "+ wikiText.substring(start));
482 private void addFunctionArg(final boolean insideFunction, final int matchStart) {
483 if (firstUnescapedPipePos == -1) {
484 firstUnescapedPipePos = lastUnescapedPipePos = matchStart;
485 } else if (insideFunction) {
486 if (lastUnescapedEqualsPos > lastUnescapedPipePos) {
487 final String key = wikiText.substring(lastUnescapedPipePos + 1, lastUnescapedEqualsPos);
488 final String value = wikiText.substring(lastUnescapedEqualsPos + 1, matchStart);
489 namedArgs.put(key, value);
491 final String value = wikiText.substring(lastUnescapedPipePos + 1, matchStart);
492 positionArgs.add(value);
495 lastUnescapedPipePos = matchStart;
498 static int safeIndexOf(final String s, final int start, final String target, final String backup) {
499 int close = s.indexOf(target, start);
501 // Don't step over a \n.
502 return close + (target.equals("\n") ? 0 : target.length());
504 close = s.indexOf(backup, start);
506 return close + (backup.equals("\n") ? 0 : backup.length());
511 public static String toPlainText(final String wikiText) {
512 final WikiTokenizer wikiTokenizer = new WikiTokenizer(wikiText);
513 final StringBuilder builder = new StringBuilder();
514 while (wikiTokenizer.nextToken() != null) {
515 if (wikiTokenizer.isPlainText()) {
516 builder.append(wikiTokenizer.token());
517 } else if (wikiTokenizer.isWikiLink()) {
518 builder.append(wikiTokenizer.wikiLinkText());
519 } else if (wikiTokenizer.isNewline()) {
520 builder.append("\n");
521 } else if (wikiTokenizer.isFunction()) {
522 builder.append(wikiTokenizer.token());
525 return builder.toString();
528 public static StringBuilder appendFunction(final StringBuilder builder, final String name, List<String> args,
529 final Map<String, String> namedArgs) {
530 builder.append(name);
531 for (final String arg : args) {
532 builder.append("|").append(arg);
534 for (final Map.Entry<String, String> entry : namedArgs.entrySet()) {
535 builder.append("|").append(entry.getKey()).append("=").append(entry.getValue());