]> gitweb.fperrin.net Git - DictionaryPC.git/blob - src/com/hughes/android/dictionary/parser/EnWiktionaryXmlParser.java
Redo splitter language codes.
[DictionaryPC.git] / src / com / hughes / android / dictionary / parser / EnWiktionaryXmlParser.java
1 // Copyright 2011 Google Inc. All Rights Reserved.
2 //
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
6 //
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
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.
14
15 package com.hughes.android.dictionary.parser;
16
17 import java.io.BufferedInputStream;
18 import java.io.DataInputStream;
19 import java.io.EOFException;
20 import java.io.File;
21 import java.io.FileInputStream;
22 import java.io.IOException;
23 import java.util.ArrayList;
24 import java.util.Arrays;
25 import java.util.Collection;
26 import java.util.LinkedHashSet;
27 import java.util.List;
28 import java.util.Map;
29 import java.util.Set;
30 import java.util.logging.Logger;
31 import java.util.regex.Pattern;
32
33 import com.hughes.android.dictionary.engine.EntryTypeName;
34 import com.hughes.android.dictionary.engine.IndexBuilder;
35 import com.hughes.android.dictionary.engine.IndexedEntry;
36 import com.hughes.android.dictionary.engine.PairEntry;
37 import com.hughes.android.dictionary.engine.PairEntry.Pair;
38
39 public class EnWiktionaryXmlParser {
40   
41   static final Logger LOG = Logger.getLogger(EnWiktionaryXmlParser.class.getName());
42   
43   // TODO: process {{ttbc}} lines
44   
45   static final Pattern partOfSpeechHeader = Pattern.compile(
46       "Noun|Verb|Adjective|Adverb|Pronoun|Conjunction|Interjection|" +
47       "Preposition|Proper noun|Article|Prepositional phrase|Acronym|" +
48       "Abbreviation|Initialism|Contraction|Prefix|Suffix|Symbol|Letter|" +
49       "Ligature|Idiom|Phrase|" +
50       // These are @deprecated:
51       "Noun form|Verb form|Adjective form|Nominal phrase|Noun phrase|" +
52       "Verb phrase|Transitive verb|Intransitive verb|Reflexive verb|" +
53       // These are extras I found:
54       "Determiner|Numeral|Number|Cardinal number|Ordinal number|Proverb|" +
55       "Particle|Interjection|Pronominal adverb" +
56       "Han character|Hanzi|Hanja|Kanji|Katakana character|Syllable");
57   
58   final IndexBuilder enIndexBuilder;
59   final IndexBuilder otherIndexBuilder;
60   final Pattern langPattern;
61   final Pattern langCodePattern;
62   final boolean swap;
63
64   public EnWiktionaryXmlParser(final IndexBuilder enIndexBuilder, final IndexBuilder otherIndexBuilder, final Pattern langPattern, final Pattern langCodePattern, final boolean swap) {
65     this.enIndexBuilder = enIndexBuilder;
66     this.otherIndexBuilder = otherIndexBuilder;
67     this.langPattern = langPattern;
68     this.langCodePattern = langCodePattern;
69     this.swap = swap;
70   }
71
72   
73   public void parse(final File file, final int pageLimit) throws IOException {
74     int pageCount = 0;
75     final DataInputStream dis = new DataInputStream(new BufferedInputStream(new FileInputStream(file)));
76     while (true) {
77       if (pageLimit >= 0 && pageCount >= pageLimit) {
78         return;
79       }
80       
81       final String title;
82       try {
83         title = dis.readUTF();
84       } catch (EOFException e) {
85         dis.close();
86         return;
87       }
88       final String heading = dis.readUTF();
89       final int bytesLength = dis.readInt();
90       final byte[] bytes = new byte[bytesLength];
91       dis.readFully(bytes);
92       final String text = new String(bytes, "UTF8");
93       
94       parseSection(title, heading, text);
95
96       ++pageCount;
97       if (pageCount % 1000 == 0) {
98         LOG.info("pageCount=" + pageCount);
99       }
100     }
101   }
102   
103   private void parseSection(final String title, String heading, final String text) {
104     if (title.startsWith("Wiktionary:") ||
105         title.startsWith("Template:") ||
106         title.startsWith("Appendix:") ||
107         title.startsWith("Category:") ||
108         title.startsWith("Index:") ||
109         title.startsWith("MediaWiki:") ||
110         title.startsWith("TransWiki:") ||
111         title.startsWith("Citations:") ||
112         title.startsWith("Concordance:") ||
113         title.startsWith("Help:")) {
114       return;
115     }
116     
117     heading = heading.replaceAll("=", "").trim(); 
118     if (heading.equals("English")) {
119       doEnglishWord(title, text);
120     } else if (langPattern.matcher(heading).matches()){
121       doForeignWord(title, text);
122     }
123         
124   }  // endPage()
125   
126   // -------------------------------------------------------------------------
127   
128   private void doEnglishWord(String title, String text) {
129     
130     String pos = null;
131     int posDepth = -1;
132
133     final WikiTokenizer wikiTokenizer = new WikiTokenizer(text);
134     while (wikiTokenizer.nextToken() != null) {
135       
136       if (wikiTokenizer.isHeading()) {
137         final String headerName = wikiTokenizer.headingWikiText();
138         
139         if (wikiTokenizer.headingDepth() <= posDepth) {
140           pos = null;
141           posDepth = -1;
142         }
143         
144         if (partOfSpeechHeader.matcher(headerName).matches()) {
145           posDepth = wikiTokenizer.headingDepth();
146           pos = wikiTokenizer.headingWikiText();
147         } else if (headerName.equals("Translations")) {
148           if (pos == null) {
149             LOG.warning("Translations without POS: " + title);
150           }
151           doTranslations(title, wikiTokenizer, pos);
152         } else if (headerName.equals("Pronunciation")) {
153           //doPronunciation(wikiLineReader);
154         }
155       }
156     }
157   }
158
159
160   private static Set<String> encodings = new LinkedHashSet<String>(Arrays.asList("zh-ts",
161       "sd-Arab", "ku-Arab", "Arab", "unicode", "Laoo", "ur-Arab", "Thai", 
162       "fa-Arab", "Khmr", "zh-tsp", "Cyrl", "IPAchar", "ug-Arab", "ko-inline", 
163       "Jpan", "Kore", "Hebr", "rfscript", "Beng", "Mong", "Knda", "Cyrs",
164       "yue-tsj", "Mlym", "Tfng", "Grek", "yue-yue-j"));
165   
166   private void doTranslations(final String title, final WikiTokenizer wikiTokenizer, final String pos) {
167     if (title.equals("absolutely")) {
168       System.out.println();
169     }
170     
171     String sense = null;
172     boolean done = false;
173     while (wikiTokenizer.nextToken() != null) {
174       if (wikiTokenizer.isHeading()) {
175         wikiTokenizer.returnToLineStart();
176         return;
177       }
178       if (done) {
179         continue;
180       }
181       
182       // Check whether we care about this line:
183       
184       //line = WikiLineReader.removeSquareBrackets(line);
185       
186       if (wikiTokenizer.isFunction()) {
187         final String functionName = wikiTokenizer.functionName();
188         final List<String> positionArgs = wikiTokenizer.functionPositionArgs();
189         
190         if (functionName.equals("trans-top")) {
191           sense = null;
192           if (wikiTokenizer.functionPositionArgs().size() >= 1) {
193             sense = positionArgs.get(0);
194             // TODO: could emphasize words in [[brackets]] inside sense.
195             sense = WikiTokenizer.toPlainText(sense);
196             //LOG.info("Sense: " + sense);
197           }
198         } else if (functionName.equals("trans-bottom")) {
199           sense = null;
200         } else if (functionName.equals("trans-mid")) {
201         } else if (functionName.equals("trans-see")) {
202           // TODO: would also be nice...
203         } else if (functionName.startsWith("picdic")) {
204         } else if (functionName.startsWith("checktrans")) {
205         } else if (functionName.startsWith("ttbc")) {
206           wikiTokenizer.nextLine();
207           // TODO: would be great to handle ttbc
208           // TODO: Check this: done = true;
209         } else {
210           LOG.warning("Unexpected translation wikifunction: " + wikiTokenizer.token() + ", title=" + title);
211         }
212       } else if (wikiTokenizer.isListItem()) {
213         final String line = wikiTokenizer.listItemWikiText();
214         // This line could produce an output...
215         
216         // First strip the language and check whether it matches.
217         // And hold onto it for sub-lines.
218         final int colonIndex = line.indexOf(":");
219         if (colonIndex == -1) {
220           continue;
221         }
222         
223         final String lang = line.substring(0, colonIndex);
224         if (!this.langPattern.matcher(lang).find()) {
225           continue;
226         }
227         
228         String rest = line.substring(colonIndex + 1).trim();
229         if (rest.length() > 0) {
230           doTranslationLine(line, title, pos, sense, rest);
231         } else {
232           // TODO: do lines that are like "Greek:"
233         }
234         
235       } else if (wikiTokenizer.remainderStartsWith("''See''")) {
236         wikiTokenizer.nextLine();
237         LOG.fine("Skipping line: " + wikiTokenizer.token());
238       } else if (wikiTokenizer.isWikiLink()) {
239         final String wikiLink = wikiTokenizer.wikiLinkText();
240         if (wikiLink.contains(":") && wikiLink.contains(title)) {
241         } else if (wikiLink.contains("Category:")) {
242         } else  {
243           LOG.warning("Unexpected wikiLink: " + wikiTokenizer.token() + ", title=" + title);
244         }
245       } else if (wikiTokenizer.isNewline() || wikiTokenizer.isMarkup() || wikiTokenizer.isComment()) {
246       } else {
247         final String token = wikiTokenizer.token();
248         if (token.equals("----")) { 
249         } else {
250           LOG.warning("Unexpected translation token: " + wikiTokenizer.token() + ", title=" + title);
251         }
252       }
253       
254     }
255   }
256   
257   private static <T> T get(final List<T> list, final int index) {
258     return index < list.size() ? list.get(index) : null;
259   }
260   
261   private void doTranslationLine(final String line, final String title, final String pos, final String sense, final String rest) {
262     // Good chance we'll actually file this one...
263     final PairEntry pairEntry = new PairEntry();
264     final IndexedEntry indexedEntry = new IndexedEntry(pairEntry);
265     
266     final StringBuilder otherText = new StringBuilder();
267     final WikiTokenizer wikiTokenizer = new WikiTokenizer(rest, false);
268     while (wikiTokenizer.nextToken() != null) {
269       
270       if (wikiTokenizer.isPlainText()) {
271         final String plainText = wikiTokenizer.token(); 
272         otherText.append("").append(plainText);
273         otherIndexBuilder.addEntryWithString(indexedEntry, plainText, EntryTypeName.WIKTIONARY_TRANSLATION_OTHER_TEXT);
274         
275       } else if (wikiTokenizer.isWikiLink()) {
276         final String plainText = wikiTokenizer.wikiLinkText(); 
277         otherText.append("").append(plainText);
278         otherIndexBuilder.addEntryWithString(indexedEntry, plainText, EntryTypeName.WIKTIONARY_TRANSLATION_WIKI_TEXT);
279         
280       } else if (wikiTokenizer.isFunction()) {
281         final String functionName = wikiTokenizer.functionName();
282         final List<String> args = wikiTokenizer.functionPositionArgs();
283         final Map<String,String> namedArgs = wikiTokenizer.functionNamedArgs();
284         
285         if (functionName.equals("t") || functionName.equals("t+") || functionName.equals("t-") || functionName.equals("tø") || functionName.equals("apdx-t")) {
286           if (args.size() < 2) {
287             LOG.warning("{{t}} with too few args: " + line + ", title=" + title);
288             continue;
289           }
290           final String langCode = get(args, 0);
291           //if (this.langCodePattern.matcher(langCode).matches()) {
292             final String word = get(args, 1);
293             final String gender = get(args, 2);
294             final String transliteration = namedArgs.get("tr");
295             if (otherText.length() > 0) {
296               otherText.append("");
297             }
298             otherText.append(word);
299             otherIndexBuilder.addEntryWithString(indexedEntry, word, EntryTypeName.WIKTIONARY_TITLE_SINGLE, EntryTypeName.WIKTIONARY_TITLE_MULTI);
300             if (gender != null) {
301               otherText.append(String.format(" {%s}", gender));
302             }
303             if (transliteration != null) {
304               otherText.append(String.format(" (tr. %s)", transliteration));
305               otherIndexBuilder.addEntryWithString(indexedEntry, transliteration, EntryTypeName.WIKTIONARY_TRANSLITERATION);
306             }
307           //}
308         } else if (functionName.equals("qualifier")) {
309           String qualifier = args.get(0);
310           if (!namedArgs.isEmpty() || args.size() > 1) {
311             LOG.warning("weird qualifier: " + line);
312           }
313           // Unindexed!
314           otherText.append("(").append(qualifier).append(")");
315         } else if (encodings.contains(functionName)) {
316           otherText.append("").append(args.get(0));
317           otherIndexBuilder.addEntryWithString(indexedEntry, args.get(0), EntryTypeName.WIKTIONARY_TRANSLATION_OTHER_TEXT);
318         } else if (isGender(functionName)) {
319           appendGender(otherText, functionName, args);
320         } else if (functionName.equals("g")) {
321           otherText.append("{g}");
322         } else if (functionName.equals("l")) {
323           // encodes text in various langs.
324           // lang is arg 0.
325           otherText.append("").append(args.get(1));
326           otherIndexBuilder.addEntryWithString(indexedEntry, args.get(1), EntryTypeName.WIKTIONARY_TRANSLATION_OTHER_TEXT);
327           // TODO: transliteration
328         } else if (functionName.equals("term")) {
329           // cross-reference to another dictionary
330           otherText.append("").append(args.get(0));
331           otherIndexBuilder.addEntryWithString(indexedEntry, args.get(0), EntryTypeName.WIKTIONARY_TRANSLATION_OTHER_TEXT);
332           // TODO: transliteration
333         } else if (functionName.equals("italbrac") || functionName.equals("gloss")) {
334           // TODO: put this text aside to use it.
335           otherText.append("[").append(args.get(0)).append("]");
336           otherIndexBuilder.addEntryWithString(indexedEntry, args.get(0), EntryTypeName.WIKTIONARY_TRANSLATION_OTHER_TEXT);
337         } else if (functionName.equals("ttbc")) {
338           LOG.warning("Unexpected {{ttbc}}");
339         } else if (functionName.equals("trreq")) {
340         } else if (functionName.equals("not used")) {
341           otherText.append("(not used)");
342         } else if (functionName.equals("t-image")) {
343           // American sign language
344         } else {
345           // Unindexed!
346           otherText.append(wikiTokenizer.token());
347         }
348         
349       } else if (wikiTokenizer.isNewline()) {
350         assert false;
351       } else if (wikiTokenizer.isComment()) {
352       } else if (wikiTokenizer.isMarkup()) {
353       } else {
354         LOG.warning("Bad translation token: " + wikiTokenizer.token());
355       }
356     }
357     if (otherText.length() == 0) {
358       LOG.warning("Empty otherText: " + line);
359       return;
360     }
361     
362     StringBuilder englishText = new StringBuilder();
363     
364     englishText.append(title);
365     if (sense != null) {
366       englishText.append(" (").append(sense).append(")");
367       enIndexBuilder.addEntryWithString(indexedEntry, sense, EntryTypeName.WIKTIONARY_TRANSLATION_SENSE, EntryTypeName.WIKTIONARY_TRANSLATION_SENSE);
368     }
369     if (pos != null) {
370       englishText.append(" (").append(pos.toLowerCase()).append(")");
371     }
372     enIndexBuilder.addEntryWithString(indexedEntry, title, EntryTypeName.WIKTIONARY_TITLE_SINGLE, EntryTypeName.WIKTIONARY_TITLE_MULTI);
373     
374     final Pair pair = new Pair(trim(englishText.toString()), trim(otherText.toString()), swap);
375     pairEntry.pairs.add(pair);
376     if (!pairsAdded.add(pair.toString())) {
377       LOG.warning("Duplicate pair: " + pair.toString());
378     }
379     if (pair.toString().equals("libero {m} :: free (adjective)")) {
380       System.out.println();
381     }
382
383   }
384
385
386   private void appendGender(final StringBuilder otherText,
387       final String functionName, final List<String> args) {
388     otherText.append("{");
389     otherText.append(functionName);
390     for (int i = 0; i < args.size(); ++i) {
391       otherText.append("|").append(args.get(i));
392     }
393     otherText.append("}");
394   }
395
396
397   private boolean isGender(final String functionName) {
398     return functionName.equals("m") || functionName.equals("f") || functionName.equals("n") || functionName.equals("p");
399   }
400   
401   Set<String> pairsAdded = new LinkedHashSet<String>();
402   
403   // -------------------------------------------------------------------------
404   
405   private void doForeignWord(final String title, final String text) {
406     final WikiTokenizer wikiTokenizer = new WikiTokenizer(text);
407     while (wikiTokenizer.nextToken() != null) {
408       if (wikiTokenizer.isHeading()) {
409         final String headingName = wikiTokenizer.headingWikiText();
410         if (headingName.equals("Translations")) {
411           LOG.warning("Translations not in English section: " + title);
412         } else if (headingName.equals("Pronunciation")) {
413           //doPronunciation(wikiLineReader);
414         } else if (partOfSpeechHeader.matcher(headingName).matches()) {
415           doForeignPartOfSpeech(title, headingName, wikiTokenizer.headingDepth(), wikiTokenizer);
416         }
417       } else {
418       }
419     }
420   }
421   
422   static final class ListSection {
423     final String firstPrefix;
424     final String firstLine;
425     final List<String> nextPrefixes = new ArrayList<String>();
426     final List<String> nextLines = new ArrayList<String>();
427     
428     public ListSection(String firstPrefix, String firstLine) {
429       this.firstPrefix = firstPrefix;
430       this.firstLine = firstLine;
431     }
432
433     @Override
434     public String toString() {
435       return firstPrefix + firstLine + "{ " + nextPrefixes + "}";
436     }
437   }
438
439
440   int foreignCount = 0;
441   private void doForeignPartOfSpeech(String title, final String posHeading, final int posDepth, WikiTokenizer wikiTokenizer) {
442     if (++foreignCount % 1000 == 0) {
443       LOG.info("***" + title + ", pos=" + posHeading + ", foreignCount=" + foreignCount);
444     }
445     if (title.equals("moro")) {
446       System.out.println();
447     }
448     
449     final StringBuilder foreignBuilder = new StringBuilder();
450     final Collection<String> wordForms = new ArrayList<String>();
451     final List<ListSection> listSections = new ArrayList<ListSection>();
452     
453     try {
454     
455     ListSection lastListSection = null;
456     
457     int currentHeadingDepth = posDepth;
458     while (wikiTokenizer.nextToken() != null) {
459       if (wikiTokenizer.isHeading()) {
460         currentHeadingDepth = wikiTokenizer.headingDepth();
461         
462         if (currentHeadingDepth <= posDepth) {
463           wikiTokenizer.returnToLineStart();
464           return;
465         }
466       }
467       
468       if (currentHeadingDepth > posDepth) {
469         // TODO: deal with other neat info sections
470         continue;
471       }
472       
473       if (wikiTokenizer.isFunction()) {
474         final String name = wikiTokenizer.functionName();
475         final List<String> args = wikiTokenizer.functionPositionArgs();
476         final Map<String,String> namedArgs = wikiTokenizer.functionNamedArgs();
477         // First line is generally a repeat of the title with some extra information.
478         // We need to build up the left side (foreign text, tokens) separately from the
479         // right side (English).  The left-side may get paired with multiple right sides.
480         // The left side should get filed under every form of the word in question (singular, plural).
481         
482         // For verbs, the conjugation comes later on in a deeper section.
483         // Ideally, we'd want to file every English entry with the verb
484         // under every verb form coming from the conjugation.
485         // Ie. under "fa": see: "make :: fare" and "do :: fare"
486         // But then where should we put the conjugation table?
487         // I think just under fare.  But then we need a way to link to the entry (actually the row, since entries doesn't show up!)
488         // for the conjugation table from "fa".
489         // Would like to be able to link to a lang#token.
490       if (isGender(name)) {
491         appendGender(foreignBuilder, name, args);
492       } else if (name.equals("wikipedia")) {
493         namedArgs.remove("lang");
494         if (args.size() > 1 || !namedArgs.isEmpty()) {
495           // Unindexed!
496           foreignBuilder.append(wikiTokenizer.token());
497         } else if (args.size() == 1) {
498           foreignBuilder.append(wikiTokenizer.token());
499         } else {
500           //foreignBuilder.append(title);
501         }
502       } else if (name.equals("it-noun")) {
503           final String base = get(args, 0);
504           final String gender = get(args, 1);
505           final String singular = base + get(args, 2);
506           final String plural = base + get(args, 3);
507           foreignBuilder.append(String.format(" %s {%s}, %s {pl}", singular, gender, plural, plural));
508           wordForms.add(singular);
509           wordForms.add(plural);
510         } else if (name.equals("it-proper noun")) {
511           foreignBuilder.append(wikiTokenizer.token());
512         } else if (name.equals("it-adj")) {
513           foreignBuilder.append(wikiTokenizer.token());
514         } else if (name.startsWith("it-conj")) {
515           if (name.equals("it-conj-are")) {
516             itConjAre(args, namedArgs);
517           } else if (name.equals("it-conj-ere")) {
518           } else if (name.equals("it-conj-ire")) {
519           } else {
520             LOG.warning("Unknown conjugation: " + wikiTokenizer.token());
521           }
522         } else {
523           // Unindexed!
524           foreignBuilder.append(wikiTokenizer.token());
525           // LOG.warning("Unknown function: " + wikiTokenizer.token());
526         }
527         
528       } else if (wikiTokenizer.isListItem()) {
529         final String prefix = wikiTokenizer.listItemPrefix();
530         if (lastListSection != null && 
531             prefix.startsWith(lastListSection.firstPrefix) && 
532             prefix.length() > lastListSection.firstPrefix.length()) {
533           lastListSection.nextPrefixes.add(prefix);
534           lastListSection.nextLines.add(wikiTokenizer.listItemWikiText());
535         } else {
536           lastListSection = new ListSection(prefix, wikiTokenizer.listItemWikiText());
537           listSections.add(lastListSection);
538         }
539       } else if (lastListSection != null) {
540         // Don't append anything after the lists, because there's crap.
541       } else if (wikiTokenizer.isWikiLink()) {
542         // Unindexed!
543         foreignBuilder.append(wikiTokenizer.wikiLinkText());
544         
545       } else if (wikiTokenizer.isPlainText()) {
546         // Unindexed!
547         foreignBuilder.append(wikiTokenizer.token());
548         
549       } else if (wikiTokenizer.isMarkup() || wikiTokenizer.isNewline() || wikiTokenizer.isComment()) {
550         // Do nothing.
551       } else {
552         LOG.warning("Unexpected token: " + wikiTokenizer.token());
553       }
554     }
555     
556     } finally {
557       // Here's where we exit.
558       // Should we make an entry even if there are no foreign list items?
559       String foreign = foreignBuilder.toString().trim();
560       if (!foreign.toLowerCase().startsWith(title.toLowerCase())) {
561         foreign = title + " " + foreign;
562       }
563       for (final ListSection listSection : listSections) {
564         doForeignListItem(foreign, title, wordForms, listSection);
565       }
566     }
567   }
568   
569   
570   static final Pattern UNINDEXED_WIKI_TEXT = Pattern.compile(
571       "(first|second|third)-person (singular|plural)|" +
572       "present tense|" +
573       "imperative"
574       );
575
576
577   private void doForeignListItem(final String foreignText, String title, final Collection<String> forms, final ListSection listSection) {
578     
579     final String prefix = listSection.firstPrefix;
580     if (prefix.length() > 1) {
581       LOG.warning("Prefix too long: " + listSection);
582       return;
583     }
584     
585     final PairEntry pairEntry = new PairEntry();
586     final IndexedEntry indexedEntry = new IndexedEntry(pairEntry);
587     
588     final StringBuilder englishBuilder = new StringBuilder();
589
590     final String mainLine = listSection.firstLine;
591     
592     final WikiTokenizer englishTokenizer = new WikiTokenizer(mainLine, false);
593     while (englishTokenizer.nextToken() != null) {
594       // TODO handle form of....
595       if (englishTokenizer.isPlainText()) {
596         englishBuilder.append(englishTokenizer.token());
597         enIndexBuilder.addEntryWithString(indexedEntry, englishTokenizer.token(), EntryTypeName.WIKTIONARY_ENGLISH_DEF);
598       } else if (englishTokenizer.isWikiLink()) {
599         final String text = englishTokenizer.wikiLinkText();
600         final String link = englishTokenizer.wikiLinkDest();
601         if (link != null) {
602           if (link.contains("#English")) {
603             englishBuilder.append(text);
604             enIndexBuilder.addEntryWithString(indexedEntry, text, EntryTypeName.WIKTIONARY_ENGLISH_DEF_WIKI_LINK);
605           } else if (link.contains("#") && this.langPattern.matcher(link).find()) {
606             englishBuilder.append(text);
607             otherIndexBuilder.addEntryWithString(indexedEntry, text, EntryTypeName.WIKTIONARY_ENGLISH_DEF_OTHER_LANG);
608           } else if (link.equals("plural")) {
609             englishBuilder.append(text);
610           } else {
611             //LOG.warning("Special link: " + englishTokenizer.token());
612             enIndexBuilder.addEntryWithString(indexedEntry, text, EntryTypeName.WIKTIONARY_ENGLISH_DEF_WIKI_LINK);
613             englishBuilder.append(text);
614           }
615         } else {
616           // link == null
617           englishBuilder.append(text);
618           if (!UNINDEXED_WIKI_TEXT.matcher(text).find()) {
619             enIndexBuilder.addEntryWithString(indexedEntry, text, EntryTypeName.WIKTIONARY_ENGLISH_DEF_WIKI_LINK);
620           }
621         }
622       } else if (englishTokenizer.isFunction()) {
623         final String name = englishTokenizer.functionName();
624         if (name.contains("conjugation of ") || 
625             name.contains("form of ") || 
626             name.contains("feminine of ") || 
627             name.contains("plural of ")) {
628           // Ignore these in the index, they're really annoying....
629           englishBuilder.append(englishTokenizer.token());
630         } else {
631           englishBuilder.append(englishTokenizer.token());
632 //          LOG.warning("Unexpected function: " + englishTokenizer.token());
633         }
634       } else {
635         if (englishTokenizer.isComment() || englishTokenizer.isMarkup()) {
636         } else {
637           LOG.warning("Unexpected definition text: " + englishTokenizer.token());
638         }
639       }
640     }
641         
642     final String english = trim(englishBuilder.toString());
643     if (english.length() > 0) {
644       final Pair pair = new Pair(english, trim(foreignText), this.swap);
645       pairEntry.pairs.add(pair);
646       otherIndexBuilder.addEntryWithString(indexedEntry, title, EntryTypeName.WIKTIONARY_TITLE_SINGLE, EntryTypeName.WIKTIONARY_TITLE_MULTI);
647       for (final String form : forms) {
648         otherIndexBuilder.addEntryWithString(indexedEntry, form, EntryTypeName.WIKTIONARY_FORM_SINGLE, EntryTypeName.WIKTIONARY_FORM_MULTI);
649       }
650     }
651     
652     // Do examples.
653     String lastForeign = null;
654     for (int i = 0; i < listSection.nextPrefixes.size(); ++i) {
655       final String nextPrefix = listSection.nextPrefixes.get(i);
656       final String nextLine = listSection.nextLines.get(i);
657       int dash = nextLine.indexOf("&mdash;");
658       int mdashLen = 7;
659       if (dash == -1) {
660         dash = nextLine.indexOf("—");
661         mdashLen = 1;
662       }
663       if (dash == -1) {
664         dash = nextLine.indexOf(" - ");
665         mdashLen = 3;
666       }
667       
668       if ((nextPrefix.equals("#:") || nextPrefix.equals("##:")) && dash != -1) {
669         final String foreignEx = nextLine.substring(0, dash);
670         final String englishEx = nextLine.substring(dash + mdashLen);
671         final Pair pair = new Pair(formatAndIndexExampleString(englishEx, enIndexBuilder, indexedEntry), formatAndIndexExampleString(foreignEx, otherIndexBuilder, indexedEntry), swap);
672         if (pair.lang1 != "--" && pair.lang1 != "--") {
673           pairEntry.pairs.add(pair);
674         }
675         lastForeign = null;
676       } else if (nextPrefix.equals("#:") || nextPrefix.equals("##:")){
677         final Pair pair = new Pair("--", formatAndIndexExampleString(nextLine, null, indexedEntry), swap);
678         lastForeign = nextLine;
679         if (pair.lang1 != "--" && pair.lang1 != "--") {
680           pairEntry.pairs.add(pair);
681         }
682       } else if (nextPrefix.equals("#::") || nextPrefix.equals("#**")) {
683         if (lastForeign != null) {
684           pairEntry.pairs.remove(pairEntry.pairs.size() - 1);
685           final Pair pair = new Pair(formatAndIndexExampleString(nextLine, enIndexBuilder, indexedEntry), formatAndIndexExampleString(lastForeign, otherIndexBuilder, indexedEntry), swap);
686           if (pair.lang1 != "--" && pair.lang1 != "--") {
687             pairEntry.pairs.add(pair);
688           }
689         } else {
690           LOG.warning("English example with no foreign: " + title + ", " + nextLine);
691         }
692       } else if (nextPrefix.equals("#*")) {
693         // Can't really index these.
694         final Pair pair = new Pair("--", formatAndIndexExampleString(nextLine, null, indexedEntry), swap);
695         lastForeign = nextLine;
696         if (pair.lang1 != "--" && pair.lang1 != "--") {
697           pairEntry.pairs.add(pair);
698         }
699       } else if (nextPrefix.equals("#::*") || nextPrefix.equals("##") || nextPrefix.equals("#*:") || nextPrefix.equals("#:*") || true) {
700         final Pair pair = new Pair("--", formatAndIndexExampleString(nextLine, null, indexedEntry), swap);
701         if (pair.lang1 != "--" && pair.lang1 != "--") {
702           pairEntry.pairs.add(pair);
703         }
704 //      } else {
705 //        assert false;
706       }
707     }
708   }
709   
710   private String formatAndIndexExampleString(final String example, final IndexBuilder indexBuilder, final IndexedEntry indexedEntry) {
711     final WikiTokenizer wikiTokenizer = new WikiTokenizer(example, false);
712     final StringBuilder builder = new StringBuilder();
713     boolean insideTripleQuotes = false;
714     while (wikiTokenizer.nextToken() != null) {
715       if (wikiTokenizer.isPlainText()) {
716         builder.append(wikiTokenizer.token());
717         if (indexBuilder != null) {
718           indexBuilder.addEntryWithString(indexedEntry, wikiTokenizer.token(), EntryTypeName.WIKTIONARY_EXAMPLE);
719         }
720       } else if (wikiTokenizer.isWikiLink()) {
721         final String text = wikiTokenizer.wikiLinkText().replaceAll("'", ""); 
722         builder.append(text);
723         if (indexBuilder != null) {
724           indexBuilder.addEntryWithString(indexedEntry, text, EntryTypeName.WIKTIONARY_EXAMPLE);
725         }
726       } else if (wikiTokenizer.isFunction()) {
727         builder.append(wikiTokenizer.token());
728       } else if (wikiTokenizer.isMarkup()) {
729         if (wikiTokenizer.token().equals("'''")) {
730           insideTripleQuotes = !insideTripleQuotes;
731         }
732       } else if (wikiTokenizer.isComment() || wikiTokenizer.isNewline()) {
733         // Do nothing.
734       } else {
735         LOG.warning("unexpected token: " + wikiTokenizer.token());
736       }
737     }
738     final String result = trim(builder.toString());
739     return result.length() > 0 ? result : "--";
740   }
741
742
743   private void itConjAre(List<String> args, Map<String, String> namedArgs) {
744     final String base = args.get(0);
745     final String aux = args.get(1);
746     
747     putIfMissing(namedArgs, "inf", base + "are");
748     putIfMissing(namedArgs, "aux", aux);
749     putIfMissing(namedArgs, "ger", base + "ando");
750     putIfMissing(namedArgs, "presp", base + "ante");
751     putIfMissing(namedArgs, "pastp", base + "ato");
752     // Present
753     putIfMissing(namedArgs, "pres1s", base + "o");
754     putIfMissing(namedArgs, "pres2s", base + "i");
755     putIfMissing(namedArgs, "pres3s", base + "a");
756     putIfMissing(namedArgs, "pres1p", base + "iamo");
757     putIfMissing(namedArgs, "pres2p", base + "ate");
758     putIfMissing(namedArgs, "pres3p", base + "ano");
759     // Imperfect
760     putIfMissing(namedArgs, "imperf1s", base + "avo");
761     putIfMissing(namedArgs, "imperf2s", base + "avi");
762     putIfMissing(namedArgs, "imperf3s", base + "ava");
763     putIfMissing(namedArgs, "imperf1p", base + "avamo");
764     putIfMissing(namedArgs, "imperf2p", base + "avate");
765     putIfMissing(namedArgs, "imperf3p", base + "avano");
766     // Passato remoto
767     putIfMissing(namedArgs, "prem1s", base + "ai");
768     putIfMissing(namedArgs, "prem2s", base + "asti");
769     putIfMissing(namedArgs, "prem3s", base + "ò");
770     putIfMissing(namedArgs, "prem1p", base + "ammo");
771     putIfMissing(namedArgs, "prem2p", base + "aste");
772     putIfMissing(namedArgs, "prem3p", base + "arono");
773     // Future
774     putIfMissing(namedArgs, "fut1s", base + "erò");
775     putIfMissing(namedArgs, "fut2s", base + "erai");
776     putIfMissing(namedArgs, "fut3s", base + "erà");
777     putIfMissing(namedArgs, "fut1p", base + "eremo");
778     putIfMissing(namedArgs, "fut2p", base + "erete");
779     putIfMissing(namedArgs, "fut3p", base + "eranno");
780     // Conditional
781     putIfMissing(namedArgs, "cond1s", base + "erei");
782     putIfMissing(namedArgs, "cond2s", base + "eresti");
783     putIfMissing(namedArgs, "cond3s", base + "erebbe");
784     putIfMissing(namedArgs, "cond1p", base + "eremmo");
785     putIfMissing(namedArgs, "cond2p", base + "ereste");
786     putIfMissing(namedArgs, "cond3p", base + "erebbero");
787     // Subjunctive / congiuntivo
788     putIfMissing(namedArgs, "sub123s", base + "i");
789     putIfMissing(namedArgs, "sub1p", base + "iamo");
790     putIfMissing(namedArgs, "sub2p", base + "iate");
791     putIfMissing(namedArgs, "sub3p", base + "ino");
792     // Imperfect subjunctive
793     putIfMissing(namedArgs, "impsub12s", base + "assi");
794     putIfMissing(namedArgs, "impsub3s", base + "asse");
795     putIfMissing(namedArgs, "impsub1p", base + "assimo");
796     putIfMissing(namedArgs, "impsub2p", base + "aste");
797     putIfMissing(namedArgs, "impsub3p", base + "assero");
798     // Imperative
799     putIfMissing(namedArgs, "imp2s", base + "a");
800     putIfMissing(namedArgs, "imp3s", base + "i");
801     putIfMissing(namedArgs, "imp1p", base + "iamo");
802     putIfMissing(namedArgs, "imp2p", base + "ate");
803     putIfMissing(namedArgs, "imp3p", base + "ino");
804
805
806     itConj(args, namedArgs);
807   }
808
809
810   private void itConj(List<String> args, Map<String, String> namedArgs) {
811     // TODO Auto-generated method stub
812     
813   }
814
815
816   private static void putIfMissing(final Map<String, String> namedArgs, final String key,
817       final String value) {
818     final String oldValue = namedArgs.get(key);
819     if (oldValue == null || oldValue.length() == 0) {
820       namedArgs.put(key, value);
821     }
822   }
823   
824   // TODO: check how ='' and =| are manifested....
825   // TODO: get this right in -are
826   private static void putOrNullify(final Map<String, String> namedArgs, final String key,
827       final String value) {
828     final String oldValue = namedArgs.get(key);
829     if (oldValue == null/* || oldValue.length() == 0*/) {
830       namedArgs.put(key, value);
831     } else {
832       if (oldValue.equals("''")) {
833         namedArgs.put(key, "");
834       }
835     }
836   }
837
838   static final Pattern whitespace = Pattern.compile("\\s+");
839   static String trim(final String s) {
840     return whitespace.matcher(s).replaceAll(" ").trim();
841   }
842
843   
844 }