]> gitweb.fperrin.net Git - DictionaryPC.git/blob - src/com/hughes/android/dictionary/parser/enwiktionary/EnWiktionaryXmlParser.java
zipSize, overrideStoplist-> special isMainEntry, tagalog, trying to
[DictionaryPC.git] / src / com / hughes / android / dictionary / parser / enwiktionary / 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.enwiktionary;
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.Level;
31 import java.util.logging.Logger;
32 import java.util.regex.Pattern;
33
34 import com.hughes.android.dictionary.engine.EntrySource;
35 import com.hughes.android.dictionary.engine.EntryTypeName;
36 import com.hughes.android.dictionary.engine.IndexBuilder;
37 import com.hughes.android.dictionary.engine.IndexedEntry;
38 import com.hughes.android.dictionary.engine.PairEntry;
39 import com.hughes.android.dictionary.engine.PairEntry.Pair;
40 import com.hughes.android.dictionary.parser.WikiTokenizer;
41
42 public class EnWiktionaryXmlParser {
43   
44   static final Logger LOG = Logger.getLogger(EnWiktionaryXmlParser.class.getName());
45   
46   // TODO: process {{ttbc}} lines
47   
48   static final Pattern partOfSpeechHeader = Pattern.compile(
49       "Noun|Verb|Adjective|Adverb|Pronoun|Conjunction|Interjection|" +
50       "Preposition|Proper noun|Article|Prepositional phrase|Acronym|" +
51       "Abbreviation|Initialism|Contraction|Prefix|Suffix|Symbol|Letter|" +
52       "Ligature|Idiom|Phrase|\\{\\{acronym\\}\\}|\\{\\{initialism\\}\\}|" +
53       "\\{\\{abbreviation\\}\\}|" +
54       // These are @deprecated:
55       "Noun form|Verb form|Adjective form|Nominal phrase|Noun phrase|" +
56       "Verb phrase|Transitive verb|Intransitive verb|Reflexive verb|" +
57       // These are extras I found:
58       "Determiner|Numeral|Number|Cardinal number|Ordinal number|Proverb|" +
59       "Particle|Interjection|Pronominal adverb" +
60       "Han character|Hanzi|Hanja|Kanji|Katakana character|Syllable");
61   
62   EntrySource entrySource;
63   final IndexBuilder enIndexBuilder;
64   final IndexBuilder foreignIndexBuilder;
65   final Pattern langPattern;
66   final Pattern langCodePattern;
67   final boolean swap;
68   
69   // State used while parsing.
70   enum State {
71     TRANSLATION_LINE,
72     ENGLISH_DEF_OF_FOREIGN,
73     ENGLISH_EXAMPLE,
74     FOREIGN_EXAMPLE,
75   }
76   State state = null;
77   String title;
78
79   public EnWiktionaryXmlParser(final IndexBuilder enIndexBuilder, final IndexBuilder otherIndexBuilder, final Pattern langPattern, final Pattern langCodePattern, final boolean swap) {
80     this.enIndexBuilder = enIndexBuilder;
81     this.foreignIndexBuilder = otherIndexBuilder;
82     this.langPattern = langPattern;
83     this.langCodePattern = langCodePattern;
84     this.swap = swap;
85   }
86
87   
88   public void parse(final File file, final EntrySource entrySource, final int pageLimit) throws IOException {
89     this.entrySource = entrySource;
90     int pageCount = 0;
91     final DataInputStream dis = new DataInputStream(new BufferedInputStream(new FileInputStream(file)));
92     try {
93     while (true) {
94       if (pageLimit >= 0 && pageCount >= pageLimit) {
95         return;
96       }
97       
98       try {
99         title = dis.readUTF();
100       } catch (EOFException e) {
101         LOG.log(Level.INFO, "EOF reading split.");
102         dis.close();
103         return;
104       }
105       final String heading = dis.readUTF();
106       final int bytesLength = dis.readInt();
107       final byte[] bytes = new byte[bytesLength];
108       dis.readFully(bytes);
109       final String text = new String(bytes, "UTF8");
110       
111       parseSection(heading, text);
112
113       ++pageCount;
114       if (pageCount % 1000 == 0) {
115         LOG.info("pageCount=" + pageCount);
116       }
117     }
118     } finally {
119       System.out.println("lang Counts: " + appendAndIndexWikiCallback.langCodeToTCount);
120       appendAndIndexWikiCallback.langCodeToTCount.keySet().removeAll(EnWiktionaryLangs.isoCodeToWikiName.keySet());
121       System.out.println("unused Counts: " + appendAndIndexWikiCallback.langCodeToTCount);
122     }
123   }
124   
125   private void parseSection(String heading, final String text) {
126     if (title.startsWith("Wiktionary:") ||
127         title.startsWith("Template:") ||
128         title.startsWith("Appendix:") ||
129         title.startsWith("Category:") ||
130         title.startsWith("Index:") ||
131         title.startsWith("MediaWiki:") ||
132         title.startsWith("TransWiki:") ||
133         title.startsWith("Citations:") ||
134         title.startsWith("Concordance:") ||
135         title.startsWith("Help:")) {
136       return;
137     }
138     
139     heading = heading.replaceAll("=", "").trim(); 
140     if (heading.equals("English")) {
141       doEnglishWord(text);
142     } else if (langPattern.matcher(heading).find()){
143       doForeignWord(heading, text);
144     }
145         
146   }  // endPage()
147   
148   // -------------------------------------------------------------------------
149   
150   private void doEnglishWord(String text) {
151     
152     String pos = null;
153     int posDepth = -1;
154
155     final WikiTokenizer wikiTokenizer = new WikiTokenizer(text);
156     while (wikiTokenizer.nextToken() != null) {
157       
158       if (wikiTokenizer.isHeading()) {
159         final String headerName = wikiTokenizer.headingWikiText();
160         
161         if (wikiTokenizer.headingDepth() <= posDepth) {
162           pos = null;
163           posDepth = -1;
164         }
165         
166         if (partOfSpeechHeader.matcher(headerName).matches()) {
167           posDepth = wikiTokenizer.headingDepth();
168           pos = wikiTokenizer.headingWikiText();
169           // TODO: if we're inside the POS section, we should handle the first title line...
170           
171         } else if (headerName.equals("Translations")) {
172           if (pos == null) {
173             LOG.info("Translations without POS (but using anyway): " + title);
174           }
175           doTranslations(wikiTokenizer, pos);
176         } else if (headerName.equals("Pronunciation")) {
177           //doPronunciation(wikiLineReader);
178         }
179       } else if (wikiTokenizer.isFunction()) {
180         final String name = wikiTokenizer.functionName();
181         if (name.equals("head") && pos == null) {
182           LOG.warning("{{head}} without POS: " + title);
183         }
184       }
185     }
186   }
187   
188   final AppendAndIndexWikiCallback appendAndIndexWikiCallback = new AppendAndIndexWikiCallback(this);
189   {
190     appendAndIndexWikiCallback.functionCallbacks.putAll(FunctionCallbacksDefault.DEFAULT);
191   }
192   
193   private void doTranslations(final WikiTokenizer wikiTokenizer, final String pos) {
194     if (title.equals("absolutely")) {
195       //System.out.println();
196     }
197     
198     String topLevelLang = null;
199     String sense = null;
200     boolean done = false;
201     while (wikiTokenizer.nextToken() != null) {
202       if (wikiTokenizer.isHeading()) {
203         wikiTokenizer.returnToLineStart();
204         return;
205       }
206       if (done) {
207         continue;
208       }
209       
210       // Check whether we care about this line:
211       
212       if (wikiTokenizer.isFunction()) {
213         final String functionName = wikiTokenizer.functionName();
214         final List<String> positionArgs = wikiTokenizer.functionPositionArgs();
215         
216         if (functionName.equals("trans-top")) {
217           sense = null;
218           if (wikiTokenizer.functionPositionArgs().size() >= 1) {
219             sense = positionArgs.get(0);
220             // TODO: could emphasize words in [[brackets]] inside sense.
221             sense = WikiTokenizer.toPlainText(sense);
222             //LOG.info("Sense: " + sense);
223           }
224         } else if (functionName.equals("trans-bottom")) {
225           sense = null;
226         } else if (functionName.equals("trans-mid")) {
227         } else if (functionName.equals("trans-see")) {
228           // TODO: would also be nice...
229         } else if (functionName.startsWith("picdic")) {
230         } else if (functionName.startsWith("checktrans")) {
231           done = true;
232         } else if (functionName.startsWith("ttbc")) {
233           wikiTokenizer.nextLine();
234           // TODO: would be great to handle ttbc
235           // TODO: Check this: done = true;
236         } else {
237           LOG.warning("Unexpected translation wikifunction: " + wikiTokenizer.token() + ", title=" + title);
238         }
239       } else if (wikiTokenizer.isListItem()) {
240         final String line = wikiTokenizer.listItemWikiText();
241         // This line could produce an output...
242         
243         if (line.contains("ich hoan dich gear")) {
244           //System.out.println();
245         }
246         
247         // First strip the language and check whether it matches.
248         // And hold onto it for sub-lines.
249         final int colonIndex = line.indexOf(":");
250         if (colonIndex == -1) {
251           continue;
252         }
253         
254         final String lang = trim(WikiTokenizer.toPlainText(line.substring(0, colonIndex)));
255         final boolean appendLang;
256         if (wikiTokenizer.listItemPrefix().length() == 1) {
257           topLevelLang = lang;
258           final boolean thisFind = langPattern.matcher(lang).find();
259           if (!thisFind) {
260             continue;
261           }
262           appendLang = !langPattern.matcher(lang).matches();
263         } else if (topLevelLang == null) {
264           continue;
265         } else {
266           // Two-level -- the only way we won't append is if this second level matches exactly.
267           if (!langPattern.matcher(lang).matches() && !langPattern.matcher(topLevelLang).find()) {
268             continue;
269           }
270           appendLang = !langPattern.matcher(lang).matches();
271         }
272         
273         String rest = line.substring(colonIndex + 1).trim();
274         if (rest.length() > 0) {
275           doTranslationLine(line, appendLang ? lang : null, pos, sense, rest);
276         }
277         
278       } else if (wikiTokenizer.remainderStartsWith("''See''")) {
279         wikiTokenizer.nextLine();
280         LOG.fine("Skipping See line: " + wikiTokenizer.token());
281       } else if (wikiTokenizer.isWikiLink()) {
282         final String wikiLink = wikiTokenizer.wikiLinkText();
283         if (wikiLink.contains(":") && wikiLink.contains(title)) {
284         } else if (wikiLink.contains("Category:")) {
285         } else  {
286           LOG.warning("Unexpected wikiLink: " + wikiTokenizer.token() + ", title=" + title);
287         }
288       } else if (wikiTokenizer.isNewline() || wikiTokenizer.isMarkup() || wikiTokenizer.isComment()) {
289       } else {
290         final String token = wikiTokenizer.token();
291         if (token.equals("----")) { 
292         } else {
293           LOG.warning("Unexpected translation token: " + wikiTokenizer.token() + ", title=" + title);
294         }
295       }
296       
297     }
298   }
299   
300   private void doTranslationLine(final String line, final String lang, final String pos, final String sense, final String rest) {
301     state = State.TRANSLATION_LINE;
302     // Good chance we'll actually file this one...
303     final PairEntry pairEntry = new PairEntry(entrySource);
304     final IndexedEntry indexedEntry = new IndexedEntry(pairEntry);
305     
306     final StringBuilder foreignText = new StringBuilder();
307     appendAndIndexWikiCallback.reset(foreignText, indexedEntry);
308     appendAndIndexWikiCallback.dispatch(rest, foreignIndexBuilder, EntryTypeName.WIKTIONARY_TRANSLATION_OTHER_TEXT);
309     
310     if (foreignText.length() == 0) {
311       LOG.warning("Empty foreignText: " + line);
312       return;
313     }
314     
315     if (lang != null) {
316       foreignText.insert(0, String.format("(%s) ", lang));
317     }
318     
319     StringBuilder englishText = new StringBuilder();
320     
321     englishText.append(title);
322     if (sense != null) {
323       englishText.append(" (").append(sense).append(")");
324       enIndexBuilder.addEntryWithString(indexedEntry, sense, EntryTypeName.WIKTIONARY_TRANSLATION_SENSE);
325     }
326     if (pos != null) {
327       englishText.append(" (").append(pos.toLowerCase()).append(")");
328     }
329     enIndexBuilder.addEntryWithString(indexedEntry, title, EntryTypeName.WIKTIONARY_TITLE_MULTI);
330     
331     final Pair pair = new Pair(trim(englishText.toString()), trim(foreignText.toString()), swap);
332     pairEntry.pairs.add(pair);
333     if (!pairsAdded.add(pair.toString())) {
334       LOG.warning("Duplicate pair: " + pair.toString());
335     }
336   }
337
338
339   Set<String> pairsAdded = new LinkedHashSet<String>();
340   
341   // -------------------------------------------------------------------------
342   
343   private void doForeignWord(final String lang, final String text) {
344     final WikiTokenizer wikiTokenizer = new WikiTokenizer(text);
345     while (wikiTokenizer.nextToken() != null) {
346       if (wikiTokenizer.isHeading()) {
347         final String headingName = wikiTokenizer.headingWikiText();
348         if (headingName.equals("Translations")) {
349           LOG.warning("Translations not in English section: " + title);
350         } else if (headingName.equals("Pronunciation")) {
351           //doPronunciation(wikiLineReader);
352         } else if (partOfSpeechHeader.matcher(headingName).matches()) {
353           doForeignPartOfSpeech(lang, headingName, wikiTokenizer.headingDepth(), wikiTokenizer);
354         }
355       } else {
356       }
357     }
358   }
359   
360   static final class ListSection {
361     final String firstPrefix;
362     final String firstLine;
363     final List<String> nextPrefixes = new ArrayList<String>();
364     final List<String> nextLines = new ArrayList<String>();
365     
366     public ListSection(String firstPrefix, String firstLine) {
367       this.firstPrefix = firstPrefix;
368       this.firstLine = firstLine;
369     }
370
371     @Override
372     public String toString() {
373       return firstPrefix + firstLine + "{ " + nextPrefixes + "}";
374     }
375   }
376
377
378   int foreignCount = 0;
379   final Collection<String> wordForms = new ArrayList<String>();
380   boolean titleAppended = false;
381
382   private void doForeignPartOfSpeech(final String lang, String posHeading, final int posDepth, WikiTokenizer wikiTokenizer) {
383     if (++foreignCount % 1000 == 0) {
384       LOG.info("***" + lang + ", " + title + ", pos=" + posHeading + ", foreignCount=" + foreignCount);
385     }
386     if (title.equals("6")) {
387       System.out.println();
388     }
389     
390     final StringBuilder foreignBuilder = new StringBuilder();
391     final List<ListSection> listSections = new ArrayList<ListSection>();
392     
393     appendAndIndexWikiCallback.reset(foreignBuilder, null);
394     this.state = State.ENGLISH_DEF_OF_FOREIGN;  // TODO: this is wrong, need new category....
395     titleAppended = false;
396     wordForms.clear();
397     
398     try {
399     
400     ListSection lastListSection = null;
401     
402     int currentHeadingDepth = posDepth;
403     while (wikiTokenizer.nextToken() != null) {
404       if (wikiTokenizer.isHeading()) {
405         currentHeadingDepth = wikiTokenizer.headingDepth();
406         
407         if (currentHeadingDepth <= posDepth) {
408           wikiTokenizer.returnToLineStart();
409           return;
410         }
411       }
412       
413       if (currentHeadingDepth > posDepth) {
414         // TODO: deal with other neat info sections
415         continue;
416       }
417       
418       if (wikiTokenizer.isFunction()) {
419         final String name = wikiTokenizer.functionName();
420         final List<String> args = wikiTokenizer.functionPositionArgs();
421         final Map<String,String> namedArgs = wikiTokenizer.functionNamedArgs();
422         // First line is generally a repeat of the title with some extra information.
423         // We need to build up the left side (foreign text, tokens) separately from the
424         // right side (English).  The left-side may get paired with multiple right sides.
425         // The left side should get filed under every form of the word in question (singular, plural).
426         
427         // For verbs, the conjugation comes later on in a deeper section.
428         // Ideally, we'd want to file every English entry with the verb
429         // under every verb form coming from the conjugation.
430         // Ie. under "fa": see: "make :: fare" and "do :: fare"
431         // But then where should we put the conjugation table?
432         // 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!)
433         // for the conjugation table from "fa".
434         // Would like to be able to link to a lang#token.
435         
436         appendAndIndexWikiCallback.onFunction(wikiTokenizer, name, args, namedArgs);
437         
438       } else if (wikiTokenizer.isListItem()) {
439         final String prefix = wikiTokenizer.listItemPrefix();
440         if (lastListSection != null && 
441             prefix.startsWith(lastListSection.firstPrefix) && 
442             prefix.length() > lastListSection.firstPrefix.length()) {
443           lastListSection.nextPrefixes.add(prefix);
444           lastListSection.nextLines.add(wikiTokenizer.listItemWikiText());
445         } else {
446           lastListSection = new ListSection(prefix, wikiTokenizer.listItemWikiText());
447           listSections.add(lastListSection);
448         }
449       } else if (lastListSection != null) {
450         // Don't append anything after the lists, because there's crap.
451       } else if (wikiTokenizer.isWikiLink()) {
452         // Unindexed!
453         foreignBuilder.append(wikiTokenizer.wikiLinkText());
454         
455       } else if (wikiTokenizer.isPlainText()) {
456         // Unindexed!
457         foreignBuilder.append(wikiTokenizer.token());
458         
459       } else if (wikiTokenizer.isMarkup() || wikiTokenizer.isNewline() || wikiTokenizer.isComment()) {
460         // Do nothing.
461       } else {
462         LOG.warning("Unexpected token: " + wikiTokenizer.token());
463       }
464     }
465     
466     } finally {
467       // Here's where we exit.
468       // Should we make an entry even if there are no foreign list items?
469       String foreign = foreignBuilder.toString().trim();
470       if (!titleAppended && !foreign.toLowerCase().startsWith(title.toLowerCase())) {
471         foreign = String.format("%s %s", title, foreign);
472       }
473       if (!langPattern.matcher(lang).matches()) {
474         foreign = String.format("(%s) %s", lang, foreign);
475       }
476       for (final ListSection listSection : listSections) {
477         doForeignListSection(foreign, title, wordForms, listSection);
478       }
479     }
480   }
481   
482   
483   // Might only want to remove "lang" if it's equal to "zh", for example.
484   static final Set<String> USELESS_WIKI_ARGS = new LinkedHashSet<String>(
485       Arrays.asList(
486           "lang",
487           "sc",
488           "sort",
489           "cat",
490           "xs",
491           "nodot"));
492
493   public boolean entryIsFormOfSomething = false;
494
495   private void doForeignListSection(final String foreignText, String title, final Collection<String> forms, final ListSection listSection) {
496     state = State.ENGLISH_DEF_OF_FOREIGN;
497     final String prefix = listSection.firstPrefix;
498     if (prefix.length() > 1) {
499       // Could just get looser and say that any prefix longer than first is a sublist.
500       LOG.warning("Prefix too long: " + listSection);
501       return;
502     }
503     
504     final PairEntry pairEntry = new PairEntry(entrySource);
505     final IndexedEntry indexedEntry = new IndexedEntry(pairEntry);
506
507     entryIsFormOfSomething = false;
508     final StringBuilder englishBuilder = new StringBuilder();
509     final String mainLine = listSection.firstLine;
510     appendAndIndexWikiCallback.reset(englishBuilder, indexedEntry);
511     appendAndIndexWikiCallback.dispatch(mainLine, enIndexBuilder, EntryTypeName.WIKTIONARY_ENGLISH_DEF);
512
513     final String english = trim(englishBuilder.toString());
514     if (english.length() > 0) {
515       final Pair pair = new Pair(english, trim(foreignText), this.swap);
516       pairEntry.pairs.add(pair);
517       foreignIndexBuilder.addEntryWithString(indexedEntry, title, entryIsFormOfSomething ? EntryTypeName.WIKTIONARY_IS_FORM_OF_SOMETHING_ELSE : EntryTypeName.WIKTIONARY_TITLE_MULTI);
518       for (final String form : forms) {
519         foreignIndexBuilder.addEntryWithString(indexedEntry, form, EntryTypeName.WIKTIONARY_INFLECTED_FORM_MULTI);
520       }
521     }
522     
523     // Do examples.
524     String lastForeign = null;
525     for (int i = 0; i < listSection.nextPrefixes.size(); ++i) {
526       final String nextPrefix = listSection.nextPrefixes.get(i);
527       final String nextLine = listSection.nextLines.get(i);
528
529       // TODO: This splitting is not sensitive to wiki code.
530       int dash = nextLine.indexOf("&mdash;");
531       int mdashLen = 7;
532       if (dash == -1) {
533         dash = nextLine.indexOf("—");
534         mdashLen = 1;
535       }
536       if (dash == -1) {
537         dash = nextLine.indexOf(" - ");
538         mdashLen = 3;
539       }
540       
541       if ((nextPrefix.equals("#:") || nextPrefix.equals("##:")) && dash != -1) {
542         final String foreignEx = nextLine.substring(0, dash);
543         final String englishEx = nextLine.substring(dash + mdashLen);
544         final Pair pair = new Pair(formatAndIndexExampleString(englishEx, enIndexBuilder, indexedEntry), formatAndIndexExampleString(foreignEx, foreignIndexBuilder, indexedEntry), swap);
545         if (pair.lang1 != "--" && pair.lang1 != "--") {
546           pairEntry.pairs.add(pair);
547         }
548         lastForeign = null;
549       } else if (nextPrefix.equals("#:") || nextPrefix.equals("##:")){
550         final Pair pair = new Pair("--", formatAndIndexExampleString(nextLine, null, indexedEntry), swap);
551         lastForeign = nextLine;
552         if (pair.lang1 != "--" && pair.lang1 != "--") {
553           pairEntry.pairs.add(pair);
554         }
555       } else if (nextPrefix.equals("#::") || nextPrefix.equals("#**")) {
556         if (lastForeign != null && pairEntry.pairs.size() > 0) {
557           pairEntry.pairs.remove(pairEntry.pairs.size() - 1);
558           final Pair pair = new Pair(formatAndIndexExampleString(nextLine, enIndexBuilder, indexedEntry), formatAndIndexExampleString(lastForeign, foreignIndexBuilder, indexedEntry), swap);
559           if (pair.lang1 != "--" || pair.lang2 != "--") {
560             pairEntry.pairs.add(pair);
561           }
562           lastForeign = null;
563         } else {
564           LOG.warning("TODO: English example with no foreign: " + title + ", " + nextLine);
565           final Pair pair = new Pair("--", formatAndIndexExampleString(nextLine, null, indexedEntry), swap);
566           if (pair.lang1 != "--" || pair.lang2 != "--") {
567             pairEntry.pairs.add(pair);
568           }
569         }
570       } else if (nextPrefix.equals("#*")) {
571         // Can't really index these.
572         final Pair pair = new Pair("--", formatAndIndexExampleString(nextLine, null, indexedEntry), swap);
573         lastForeign = nextLine;
574         if (pair.lang1 != "--" || pair.lang2 != "--") {
575           pairEntry.pairs.add(pair);
576         }
577       } else if (nextPrefix.equals("#::*") || nextPrefix.equals("##") || nextPrefix.equals("#*:") || nextPrefix.equals("#:*") || true) {
578         final Pair pair = new Pair("--", formatAndIndexExampleString(nextLine, null, indexedEntry), swap);
579         if (pair.lang1 != "--" || pair.lang2 != "--") {
580           pairEntry.pairs.add(pair);
581         }
582 //      } else {
583 //        assert false;
584       }
585     }
586   }
587   
588   private String formatAndIndexExampleString(final String example, final IndexBuilder indexBuilder, final IndexedEntry indexedEntry) {
589     // TODO:
590 //    if (wikiTokenizer.token().equals("'''")) {
591 //      insideTripleQuotes = !insideTripleQuotes;
592 //    }
593     final StringBuilder builder = new StringBuilder();
594     appendAndIndexWikiCallback.reset(builder, indexedEntry);
595     appendAndIndexWikiCallback.entryTypeName = EntryTypeName.WIKTIONARY_EXAMPLE;
596     appendAndIndexWikiCallback.entryTypeNameSticks = true;
597     try {
598       // TODO: this is a hack needed because we don't safely split on the dash.
599       appendAndIndexWikiCallback.dispatch(example, indexBuilder, EntryTypeName.WIKTIONARY_EXAMPLE);
600     } catch (AssertionError e) {
601       return "--";
602     }
603     final String result = trim(builder.toString());
604     return result.length() > 0 ? result : "--";
605   }
606
607
608   private void itConjAre(List<String> args, Map<String, String> namedArgs) {
609     final String base = args.get(0);
610     final String aux = args.get(1);
611     
612     putIfMissing(namedArgs, "inf", base + "are");
613     putIfMissing(namedArgs, "aux", aux);
614     putIfMissing(namedArgs, "ger", base + "ando");
615     putIfMissing(namedArgs, "presp", base + "ante");
616     putIfMissing(namedArgs, "pastp", base + "ato");
617     // Present
618     putIfMissing(namedArgs, "pres1s", base + "o");
619     putIfMissing(namedArgs, "pres2s", base + "i");
620     putIfMissing(namedArgs, "pres3s", base + "a");
621     putIfMissing(namedArgs, "pres1p", base + "iamo");
622     putIfMissing(namedArgs, "pres2p", base + "ate");
623     putIfMissing(namedArgs, "pres3p", base + "ano");
624     // Imperfect
625     putIfMissing(namedArgs, "imperf1s", base + "avo");
626     putIfMissing(namedArgs, "imperf2s", base + "avi");
627     putIfMissing(namedArgs, "imperf3s", base + "ava");
628     putIfMissing(namedArgs, "imperf1p", base + "avamo");
629     putIfMissing(namedArgs, "imperf2p", base + "avate");
630     putIfMissing(namedArgs, "imperf3p", base + "avano");
631     // Passato remoto
632     putIfMissing(namedArgs, "prem1s", base + "ai");
633     putIfMissing(namedArgs, "prem2s", base + "asti");
634     putIfMissing(namedArgs, "prem3s", base + "ò");
635     putIfMissing(namedArgs, "prem1p", base + "ammo");
636     putIfMissing(namedArgs, "prem2p", base + "aste");
637     putIfMissing(namedArgs, "prem3p", base + "arono");
638     // Future
639     putIfMissing(namedArgs, "fut1s", base + "erò");
640     putIfMissing(namedArgs, "fut2s", base + "erai");
641     putIfMissing(namedArgs, "fut3s", base + "erà");
642     putIfMissing(namedArgs, "fut1p", base + "eremo");
643     putIfMissing(namedArgs, "fut2p", base + "erete");
644     putIfMissing(namedArgs, "fut3p", base + "eranno");
645     // Conditional
646     putIfMissing(namedArgs, "cond1s", base + "erei");
647     putIfMissing(namedArgs, "cond2s", base + "eresti");
648     putIfMissing(namedArgs, "cond3s", base + "erebbe");
649     putIfMissing(namedArgs, "cond1p", base + "eremmo");
650     putIfMissing(namedArgs, "cond2p", base + "ereste");
651     putIfMissing(namedArgs, "cond3p", base + "erebbero");
652     // Subjunctive / congiuntivo
653     putIfMissing(namedArgs, "sub123s", base + "i");
654     putIfMissing(namedArgs, "sub1p", base + "iamo");
655     putIfMissing(namedArgs, "sub2p", base + "iate");
656     putIfMissing(namedArgs, "sub3p", base + "ino");
657     // Imperfect subjunctive
658     putIfMissing(namedArgs, "impsub12s", base + "assi");
659     putIfMissing(namedArgs, "impsub3s", base + "asse");
660     putIfMissing(namedArgs, "impsub1p", base + "assimo");
661     putIfMissing(namedArgs, "impsub2p", base + "aste");
662     putIfMissing(namedArgs, "impsub3p", base + "assero");
663     // Imperative
664     putIfMissing(namedArgs, "imp2s", base + "a");
665     putIfMissing(namedArgs, "imp3s", base + "i");
666     putIfMissing(namedArgs, "imp1p", base + "iamo");
667     putIfMissing(namedArgs, "imp2p", base + "ate");
668     putIfMissing(namedArgs, "imp3p", base + "ino");
669
670
671     itConj(args, namedArgs);
672   }
673
674
675   private void itConj(List<String> args, Map<String, String> namedArgs) {
676     // TODO Auto-generated method stub
677     
678   }
679
680
681   private static void putIfMissing(final Map<String, String> namedArgs, final String key,
682       final String value) {
683     final String oldValue = namedArgs.get(key);
684     if (oldValue == null || oldValue.length() == 0) {
685       namedArgs.put(key, value);
686     }
687   }
688   
689   // TODO: check how ='' and =| are manifested....
690   // TODO: get this right in -are
691   private static void putOrNullify(final Map<String, String> namedArgs, final String key,
692       final String value) {
693     final String oldValue = namedArgs.get(key);
694     if (oldValue == null/* || oldValue.length() == 0*/) {
695       namedArgs.put(key, value);
696     } else {
697       if (oldValue.equals("''")) {
698         namedArgs.put(key, "");
699       }
700     }
701   }
702
703   static final Pattern whitespace = Pattern.compile("\\s+");
704   static String trim(final String s) {
705     return whitespace.matcher(s).replaceAll(" ").trim();
706   }
707
708   
709 }