]> git.lyx.org Git - features.git/blob - src/insets/InsetIndex.cpp
Introduce InsetIndexMacros
[features.git] / src / insets / InsetIndex.cpp
1 /**
2  * \file InsetIndex.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author Jürgen Spitzmüller
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11 #include <config.h>
12
13 #include "InsetIndex.h"
14 #include "InsetIndexMacro.h"
15
16 #include "Buffer.h"
17 #include "BufferParams.h"
18 #include "BufferView.h"
19 #include "ColorSet.h"
20 #include "Cursor.h"
21 #include "DispatchResult.h"
22 #include "Encoding.h"
23 #include "ErrorList.h"
24 #include "FuncRequest.h"
25 #include "FuncStatus.h"
26 #include "IndicesList.h"
27 #include "InsetList.h"
28 #include "Language.h"
29 #include "LaTeX.h"
30 #include "LaTeXFeatures.h"
31 #include "Lexer.h"
32 #include "output_latex.h"
33 #include "output_xhtml.h"
34 #include "xml.h"
35 #include "texstream.h"
36 #include "TextClass.h"
37 #include "TocBackend.h"
38
39 #include "support/debug.h"
40 #include "support/docstream.h"
41 #include "support/FileName.h"
42 #include "support/gettext.h"
43 #include "support/lstrings.h"
44 #include "support/Translator.h"
45
46 #include "frontends/alert.h"
47
48 #include <algorithm>
49 #include <set>
50 #include <ostream>
51
52 #include <QThreadStorage>
53
54 using namespace std;
55 using namespace lyx::support;
56
57 namespace lyx {
58
59 namespace {
60
61 typedef Translator<string, InsetIndexParams::PageRange> PageRangeTranslator;
62 typedef Translator<docstring, InsetIndexParams::PageRange> PageRangeTranslatorLoc;
63
64 PageRangeTranslator const init_insetindexpagerangetranslator()
65 {
66         PageRangeTranslator translator("none", InsetIndexParams::None);
67         translator.addPair("start", InsetIndexParams::Start);
68         translator.addPair("end", InsetIndexParams::End);
69         return translator;
70 }
71
72 PageRangeTranslator const init_insetindexpagerangetranslator_latex()
73 {
74         PageRangeTranslator translator("", InsetIndexParams::None);
75         translator.addPair("(", InsetIndexParams::Start);
76         translator.addPair(")", InsetIndexParams::End);
77         return translator;
78 }
79
80
81 PageRangeTranslatorLoc const init_insetindexpagerangetranslator_loc()
82 {
83         PageRangeTranslatorLoc translator(docstring(), InsetIndexParams::None);
84         translator.addPair(_("Starts page range"), InsetIndexParams::Start);
85         translator.addPair(_("Ends page range"), InsetIndexParams::End);
86         return translator;
87 }
88
89
90 PageRangeTranslator const & insetindexpagerangetranslator()
91 {
92         static PageRangeTranslator const prtranslator =
93                         init_insetindexpagerangetranslator();
94         return prtranslator;
95 }
96
97
98 PageRangeTranslatorLoc const & insetindexpagerangetranslator_loc()
99 {
100         static PageRangeTranslatorLoc const translator =
101                         init_insetindexpagerangetranslator_loc();
102         return translator;
103 }
104
105
106 PageRangeTranslator const & insetindexpagerangetranslator_latex()
107 {
108         static PageRangeTranslator const lttranslator =
109                         init_insetindexpagerangetranslator_latex();
110         return lttranslator;
111 }
112
113 } // namespace anon
114
115 /////////////////////////////////////////////////////////////////////
116 //
117 // InsetIndex
118 //
119 ///////////////////////////////////////////////////////////////////////
120
121
122 InsetIndex::InsetIndex(Buffer * buf, InsetIndexParams const & params)
123         : InsetCollapsible(buf), params_(params)
124 {}
125
126
127 void InsetIndex::latex(otexstream & ios, OutputParams const & runparams_in) const
128 {
129         OutputParams runparams(runparams_in);
130         runparams.inIndexEntry = true;
131
132         otexstringstream os;
133
134         if (buffer().masterBuffer()->params().use_indices && !params_.index.empty()
135                 && params_.index != "idx") {
136                 os << "\\sindex[";
137                 os << escape(params_.index);
138                 os << "]{";
139         } else {
140                 os << "\\index";
141                 os << '{';
142         }
143
144         // Get the LaTeX output from InsetText. We need to deconstruct this later
145         // in order to check if we need to generate a sorting key
146         odocstringstream ourlatex;
147         otexstream ots(ourlatex);
148         InsetText::latex(ots, runparams);
149         if (runparams.for_search != OutputParams::NoSearch) {
150                 // No need for special handling, if we are only searching for some patterns
151                 os << ourlatex.str() << "}";
152                 return;
153         }
154
155         if (hasSortKey()) {
156                 getSortkey(os, runparams);
157                 os << "@";
158                 os << ourlatex.str();
159                 getSubentries(os, runparams);
160                 if (hasSeeRef()) {
161                         os << "|";
162                         os << insetindexpagerangetranslator_latex().find(params_.range);
163                         getSeeRefs(os, runparams);
164                 }
165         } else {
166                 // We check whether we need a sort key.
167                 // If so, we use the plaintext version
168                 odocstringstream ourplain;
169                 InsetText::plaintext(ourplain, runparams);
170
171                 // These are the LaTeX and plaintext representations
172                 docstring latexstr = ourlatex.str();
173                 docstring plainstr = ourplain.str();
174         
175                 // This will get what follows | if anything does,
176                 // the command (e.g., see, textbf) for pagination
177                 // formatting
178                 docstring cmd;
179
180                 if (hasSeeRef()) {
181                         odocstringstream seeref;
182                         otexstream otsee(seeref);
183                         getSeeRefs(otsee, runparams);
184                         cmd = seeref.str();
185                 } else if (!params_.pagefmt.empty() && params_.pagefmt != "default") {
186                         cmd = from_utf8(params_.pagefmt);
187                 } else {
188                         // Check for the | separator to strip the cmd.
189                         // This goes wrong on an escaped "|", but as the escape
190                         // character can be changed in style files, we cannot
191                         // prevent that.
192                         size_t pos = latexstr.find(from_ascii("|"));
193                         if (pos != docstring::npos) {
194                                 // Put the bit after "|" into cmd...
195                                 cmd = latexstr.substr(pos + 1);
196                                 // ...and erase that stuff from latexstr
197                                 latexstr = latexstr.erase(pos);
198                                 // ...as well as from plainstr
199                                 size_t ppos = plainstr.find(from_ascii("|"));
200                                 if (ppos < plainstr.size())
201                                         plainstr.erase(ppos);
202                                 else
203                                         LYXERR0("The `|' separator was not found in the plaintext version!");
204                         }
205                 }
206
207                 odocstringstream subentries;
208                 otexstream otsub(subentries);
209                 getSubentries(otsub, runparams);
210                 if (subentries.str().empty()) {
211                         // Separate the entries and subentries, i.e., split on "!".
212                         // This goes wrong on an escaped "!", but as the escape
213                         // character can be changed in style files, we cannot
214                         // prevent that.
215                         std::vector<docstring> const levels =
216                                         getVectorFromString(latexstr, from_ascii("!"), true);
217                         std::vector<docstring> const levels_plain =
218                                         getVectorFromString(plainstr, from_ascii("!"), true);
219                 
220                         vector<docstring>::const_iterator it = levels.begin();
221                         vector<docstring>::const_iterator end = levels.end();
222                         vector<docstring>::const_iterator it2 = levels_plain.begin();
223                         bool first = true;
224                         for (; it != end; ++it) {
225                                 // The separator needs to be put back when
226                                 // writing the levels, except for the first level
227                                 if (!first)
228                                         os << '!';
229                                 else
230                                         first = false;
231                 
232                                 // Now here comes the reason for this whole procedure:
233                                 // We try to correctly sort macros and formatted strings.
234                                 // If we find a command, prepend a plain text
235                                 // version of the content to get sorting right,
236                                 // e.g. \index{LyX@\LyX}, \index{text@\textbf{text}}.
237                                 // We do this on all levels.
238                                 // We don't do it if the level already contains a '@', though.
239                                 // Plaintext might return nothing (e.g. for ERTs).
240                                 // In that case, we use LaTeX.
241                                 docstring const spart = (levels_plain.empty() || (*it2).empty()) ? *it : *it2;
242                                 processLatexSorting(os, runparams, *it, spart);
243                                 if (it2 < levels_plain.end())
244                                         ++it2;
245                         }
246                 } else {
247                         processLatexSorting(os, runparams, latexstr, plainstr);
248                         os << subentries.str();
249                 }
250
251                 // At last, re-insert the command, separated by "|"
252                 if (!cmd.empty()) {
253                         os << "|"
254                            << insetindexpagerangetranslator_latex().find(params_.range)
255                            << cmd;
256                 }
257         }
258         os << '}';
259
260         // In macros with moving arguments, such as \section,
261         // we store the index and output it after the macro (#2154)
262         if (runparams_in.postpone_fragile_stuff)
263                 runparams_in.post_macro += os.str();
264         else
265                 ios << os.release();
266 }
267
268
269 void InsetIndex::processLatexSorting(otexstream & os, OutputParams const & runparams,
270                                 docstring const latex, docstring const spart) const
271 {
272         if (contains(latex, '\\') && !contains(latex, '@')) {
273                 // Now we need to validate that all characters in
274                 // the sorting part are representable in the current
275                 // encoding. If not try the LaTeX macro which might
276                 // or might not be a good choice, and issue a warning.
277                 pair<docstring, docstring> spart_latexed =
278                                 runparams.encoding->latexString(spart, runparams.dryrun);
279                 if (!spart_latexed.second.empty())
280                         LYXERR0("Uncodable character in index entry. Sorting might be wrong!");
281                 if (spart != spart_latexed.first && !runparams.dryrun) {
282                         TeXErrors terr;
283                         ErrorList & errorList = buffer().errorList("Export");
284                         docstring const s = bformat(_("LyX's automatic index sorting algorithm faced "
285                                                       "problems with the entry '%1$s'.\n"
286                                                       "Please specify the sorting of this entry manually, as "
287                                                       "explained in the User Guide."), spart);
288                         Paragraph const & par = buffer().paragraphs().front();
289                         errorList.push_back(ErrorItem(_("Index sorting failed"), s,
290                                                       {par.id(), 0}, {par.id(), -1}));
291                         buffer().bufferErrors(terr, errorList);
292                 }
293                 // Remove remaining \'s from the sort key
294                 docstring ppart = subst(spart_latexed.first, from_ascii("\\"), docstring());
295                 // Plain quotes need to be escaped, however (#10649), as this
296                 // is the default escape character
297                 ppart = subst(ppart, from_ascii("\""), from_ascii("\\\""));
298
299                 // Now insert the sortkey, separated by '@'.
300                 os << ppart;
301                 os << '@';
302         }
303         // Insert the actual level text
304         os << latex;
305 }
306
307
308 void InsetIndex::docbook(XMLStream & xs, OutputParams const & runparams) const
309 {
310         // Get the content of the inset as LaTeX, as some things may be encoded as ERT (like {}).
311         // TODO: if there is an ERT within the index term, its conversion should be tried, in case it becomes useful;
312         //  otherwise, ERTs should become comments. For now, they are just copied as-is, which is barely satisfactory.
313         odocstringstream odss;
314         otexstream ots(odss);
315         InsetText::latex(ots, runparams);
316         docstring latexString = trim(odss.str());
317
318         // Check whether there are unsupported things. @ is supported, but only for sorting, without specific formatting.
319         if (latexString.find(from_utf8("@\\")) != lyx::docstring::npos) {
320                 docstring error = from_utf8("Unsupported feature: an index entry contains an @\\. "
321                                                                         "Complete entry: \"") + latexString + from_utf8("\"");
322                 LYXERR0(error);
323                 xs << XMLStream::ESCAPE_NONE << (from_utf8("<!-- Output Error: ") + error + from_utf8(" -->\n"));
324         }
325
326         // Handle several indices (indicated in the inset instead of the raw latexString).
327         docstring indexType = from_utf8("");
328         if (buffer().masterBuffer()->params().use_indices) {
329                 indexType += " type=\"" + params_.index + "\"";
330         }
331
332         // Split the string into its main constituents: terms, and command (see, see also, range).
333         size_t positionVerticalBar = latexString.find(from_ascii("|")); // What comes before | is (sub)(sub)entries.
334         docstring indexTerms = latexString.substr(0, positionVerticalBar);
335         docstring command;
336         if (positionVerticalBar != lyx::docstring::npos) {
337                 command =  latexString.substr(positionVerticalBar + 1);
338         }
339
340         // Handle sorting issues, with @.
341         vector<docstring> sortingElements = getVectorFromString(indexTerms, from_ascii("@"), false);
342         docstring sortAs;
343         if (sortingElements.size() == 2) {
344                 sortAs = sortingElements[0];
345                 indexTerms = sortingElements[1];
346         }
347
348         // Handle primary, secondary, and tertiary terms (entries, subentries, and subsubentries, for LaTeX).
349         vector<docstring> terms = getVectorFromString(indexTerms, from_ascii("!"), false);
350
351         // Handle ranges. Happily, (| and |) can only be at the end of the string!
352         bool hasStartRange = latexString.find(from_ascii("|(")) != lyx::docstring::npos;
353         bool hasEndRange = latexString.find(from_ascii("|)")) != lyx::docstring::npos;
354         if (hasStartRange || hasEndRange) {
355                 // Remove the ranges from the command if they do not appear at the beginning.
356                 size_t index = 0;
357                 while ((index = command.find(from_utf8("|("), index)) != std::string::npos)
358                         command.erase(index, 1);
359                 index = 0;
360                 while ((index = command.find(from_utf8("|)"), index)) != std::string::npos)
361                         command.erase(index, 1);
362
363                 // Remove the ranges when they are the only vertical bar in the complete string.
364                 if (command[0] == '(' || command[0] == ')')
365                         command.erase(0, 1);
366         }
367
368         // Handle see and seealso. As "see" is a prefix of "seealso", the order of the comparisons is important.
369         // Both commands are mutually exclusive!
370         docstring see = from_utf8("");
371         vector<docstring> seeAlsoes;
372         if (command.substr(0, 3) == "see") {
373                 // Unescape brackets.
374                 size_t index = 0;
375                 while ((index = command.find(from_utf8("\\{"), index)) != std::string::npos)
376                         command.erase(index, 1);
377                 index = 0;
378                 while ((index = command.find(from_utf8("\\}"), index)) != std::string::npos)
379                         command.erase(index, 1);
380
381                 // Retrieve the part between brackets, and remove the complete seealso.
382                 size_t positionOpeningBracket = command.find(from_ascii("{"));
383                 size_t positionClosingBracket = command.find(from_ascii("}"));
384                 docstring list = command.substr(positionOpeningBracket + 1, positionClosingBracket - positionOpeningBracket - 1);
385
386                 // Parse the list of referenced entries (or a single one for see).
387                 if (command.substr(0, 7) == "seealso") {
388                         seeAlsoes = getVectorFromString(list, from_ascii(","), false);
389                 } else {
390                         see = list;
391
392                         if (see.find(from_ascii(",")) != std::string::npos) {
393                                 docstring error = from_utf8("Several index terms found as \"see\"! Only one is acceptable. "
394                                                                                         "Complete entry: \"") + latexString + from_utf8("\"");
395                                 LYXERR0(error);
396                                 xs << XMLStream::ESCAPE_NONE << (from_utf8("<!-- Output Error: ") + error + from_utf8(" -->\n"));
397                         }
398                 }
399
400                 // Remove the complete see/seealso from the commands, in case there is something else to parse.
401                 command = command.substr(positionClosingBracket + 1);
402         }
403
404         // Some parts of the strings are not parsed, as they do not have anything matching in DocBook: things like
405         // formatting the entry or the page number, other strings for sorting. https://wiki.lyx.org/Tips/Indexing
406         // If there are such things in the index entry, then this code may miserably fail. For example, for "Peter|(textbf",
407         // no range will be detected.
408         // TODO: Could handle formatting as significance="preferred"?
409         if (!command.empty()) {
410                 docstring error = from_utf8("Unsupported feature: an index entry contains a | with an unsupported command, ")
411                                           + command + from_utf8(". ") + from_utf8("Complete entry: \"") + latexString + from_utf8("\"");
412                 LYXERR0(error);
413                 xs << XMLStream::ESCAPE_NONE << (from_utf8("<!-- Output Error: ") + error + from_utf8(" -->\n"));
414         }
415
416     // Write all of this down.
417         if (terms.empty() && !hasEndRange) {
418                 docstring error = from_utf8("No index term found! Complete entry: \"") + latexString + from_utf8("\"");
419                 LYXERR0(error);
420                 xs << XMLStream::ESCAPE_NONE << (from_utf8("<!-- Output Error: ") + error + from_utf8(" -->\n"));
421         } else {
422                 // Generate the attributes for ranges. It is based on the terms that are indexed, but the ID must be unique
423                 // to this indexing area (xml::cleanID does not guarantee this: for each call with the same arguments,
424                 // the same legal ID is produced; here, as the input would be the same, the output must be, by design).
425                 // Hence the thread-local storage, as the numbers must strictly be unique, and thus cannot be shared across
426                 // a paragraph (making the solution used for HTML worthless). This solution is very similar to the one used in
427                 // xml::cleanID.
428                 // indexType can only be used for singular and startofrange types!
429                 docstring attrs;
430                 if (!hasStartRange && !hasEndRange) {
431                         attrs = indexType;
432                 } else {
433                         // Append an ID if uniqueness is not guaranteed across the document.
434                         static QThreadStorage<set<docstring>> tKnownTermLists;
435                         static QThreadStorage<int> tID;
436
437                         set<docstring> &knownTermLists = tKnownTermLists.localData();
438                         int &ID = tID.localData();
439
440                         if (!tID.hasLocalData()) {
441                                 tID.localData() = 0;
442                         }
443
444                         // Modify the index terms to add the unique ID if needed.
445                         docstring newIndexTerms = indexTerms;
446                         if (knownTermLists.find(indexTerms) != knownTermLists.end()) {
447                                 newIndexTerms += from_ascii(string("-") + to_string(ID));
448
449                                 // Only increment for the end of range, so that the same number is used for the start of range.
450                                 if (hasEndRange) {
451                                         ID++;
452                                 }
453                         }
454
455                         // Term list not yet known: add it to the set AFTER the end of range. After
456                         if (knownTermLists.find(indexTerms) == knownTermLists.end() && hasEndRange) {
457                                 knownTermLists.insert(indexTerms);
458                         }
459
460                         // Generate the attributes.
461                         docstring id = xml::cleanID(newIndexTerms);
462                         if (hasStartRange) {
463                                 attrs = indexType + " class=\"startofrange\" xml:id=\"" + id + "\"";
464                         } else {
465                                 attrs = " class=\"endofrange\" startref=\"" + id + "\"";
466                         }
467                 }
468
469                 // Handle the index terms (including the specific index for this entry).
470                 if (hasEndRange) {
471                         xs << xml::CompTag("indexterm", attrs);
472                 } else {
473                         xs << xml::StartTag("indexterm", attrs);
474                         if (!terms.empty()) { // hasEndRange has no content.
475                                 docstring attr;
476                                 if (!sortAs.empty()) {
477                                         attr = from_utf8("sortas='") + sortAs + from_utf8("'");
478                                 }
479
480                                 xs << xml::StartTag("primary", attr);
481                                 xs << terms[0];
482                                 xs << xml::EndTag("primary");
483                         }
484                         if (terms.size() > 1) {
485                                 xs << xml::StartTag("secondary");
486                                 xs << terms[1];
487                                 xs << xml::EndTag("secondary");
488                         }
489                         if (terms.size() > 2) {
490                                 xs << xml::StartTag("tertiary");
491                                 xs << terms[2];
492                                 xs << xml::EndTag("tertiary");
493                         }
494
495                         // Handle see and see also.
496                         if (!see.empty()) {
497                                 xs << xml::StartTag("see");
498                                 xs << see;
499                                 xs << xml::EndTag("see");
500                         }
501
502                         if (!seeAlsoes.empty()) {
503                                 for (auto &entry : seeAlsoes) {
504                                         xs << xml::StartTag("seealso");
505                                         xs << entry;
506                                         xs << xml::EndTag("seealso");
507                                 }
508                         }
509
510                         // Close the entry.
511                         xs << xml::EndTag("indexterm");
512                 }
513         }
514 }
515
516
517 docstring InsetIndex::xhtml(XMLStream & xs, OutputParams const &) const
518 {
519         // we just print an anchor, taking the paragraph ID from
520         // our own interior paragraph, which doesn't get printed
521         std::string const magic = paragraphs().front().magicLabel();
522         std::string const attr = "id='" + magic + "'";
523         xs << xml::CompTag("a", attr);
524         return docstring();
525 }
526
527
528 bool InsetIndex::showInsetDialog(BufferView * bv) const
529 {
530         bv->showDialog("index", params2string(params_),
531                         const_cast<InsetIndex *>(this));
532         return true;
533 }
534
535
536 void InsetIndex::doDispatch(Cursor & cur, FuncRequest & cmd)
537 {
538         switch (cmd.action()) {
539
540         case LFUN_INSET_MODIFY: {
541                 if (cmd.getArg(0) == "changetype") {
542                         cur.recordUndoInset(this);
543                         params_.index = from_utf8(cmd.getArg(1));
544                         break;
545                 }
546                 InsetIndexParams params;
547                 InsetIndex::string2params(to_utf8(cmd.argument()), params);
548                 cur.recordUndoInset(this);
549                 params_.index = params.index;
550                 params_.range = params.range;
551                 params_.pagefmt = params.pagefmt;
552                 // what we really want here is a TOC update, but that means
553                 // a full buffer update
554                 cur.forceBufferUpdate();
555                 break;
556         }
557
558         case LFUN_INSET_DIALOG_UPDATE:
559                 cur.bv().updateDialog("index", params2string(params_));
560                 break;
561
562         default:
563                 InsetCollapsible::doDispatch(cur, cmd);
564                 break;
565         }
566 }
567
568
569 bool InsetIndex::getStatus(Cursor & cur, FuncRequest const & cmd,
570                 FuncStatus & flag) const
571 {
572         switch (cmd.action()) {
573
574         case LFUN_INSET_MODIFY:
575                 if (cmd.getArg(0) == "changetype") {
576                         docstring const newtype = from_utf8(cmd.getArg(1));
577                         Buffer const & realbuffer = *buffer().masterBuffer();
578                         IndicesList const & indiceslist = realbuffer.params().indiceslist();
579                         Index const * index = indiceslist.findShortcut(newtype);
580                         flag.setEnabled(index != 0);
581                         flag.setOnOff(
582                                 from_utf8(cmd.getArg(1)) == params_.index);
583                         return true;
584                 }
585                 return InsetCollapsible::getStatus(cur, cmd, flag);
586
587         case LFUN_INSET_DIALOG_UPDATE: {
588                 Buffer const & realbuffer = *buffer().masterBuffer();
589                 flag.setEnabled(realbuffer.params().use_indices);
590                 return true;
591         }
592         
593         case LFUN_INDEXMACRO_INSERT:
594                 return macrosPossible(cmd.getArg(0));
595
596         default:
597                 return InsetCollapsible::getStatus(cur, cmd, flag);
598         }
599 }
600
601
602 void InsetIndex::getSortkey(otexstream & os, OutputParams const & runparams) const
603 {
604         Paragraph const & par = paragraphs().front();
605         InsetList::const_iterator it = par.insetList().begin();
606         for (; it != par.insetList().end(); ++it) {
607                 Inset & inset = *it->inset;
608                 if (inset.lyxCode() == INDEXMACRO_SORTKEY_CODE) {
609                         InsetIndexMacro const & iim =
610                                 static_cast<InsetIndexMacro const &>(inset);
611                         iim.getLatex(os, runparams);
612                         return;
613                 }
614         }
615 }
616
617
618 void InsetIndex::getSubentries(otexstream & os, OutputParams const & runparams) const
619 {
620         Paragraph const & par = paragraphs().front();
621         InsetList::const_iterator it = par.insetList().begin();
622         int i = 0;
623         for (; it != par.insetList().end(); ++it) {
624                 Inset & inset = *it->inset;
625                 if (inset.lyxCode() == INDEXMACRO_CODE) {
626                         InsetIndexMacro const & iim =
627                                 static_cast<InsetIndexMacro const &>(inset);
628                         if (iim.params().type == InsetIndexMacroParams::Subindex) {
629                                 ++i;
630                                 if (i > 2)
631                                         return;
632                                 os << "!";
633                                 iim.getLatex(os, runparams);
634                         }
635                 }
636         }
637 }
638
639
640 void InsetIndex::getSeeRefs(otexstream & os, OutputParams const & runparams) const
641 {
642         Paragraph const & par = paragraphs().front();
643         InsetList::const_iterator it = par.insetList().begin();
644         for (; it != par.insetList().end(); ++it) {
645                 Inset & inset = *it->inset;
646                 if (inset.lyxCode() == INDEXMACRO_CODE) {
647                         InsetIndexMacro const & iim =
648                                 static_cast<InsetIndexMacro const &>(inset);
649                         if (iim.params().type == InsetIndexMacroParams::See
650                             || iim.params().type == InsetIndexMacroParams::Seealso) {
651                                 iim.getLatex(os, runparams);
652                                 return;
653                         }
654                 }
655         }
656 }
657
658
659 bool InsetIndex::hasSeeRef() const
660 {
661         Paragraph const & par = paragraphs().front();
662         InsetList::const_iterator it = par.insetList().begin();
663         for (; it != par.insetList().end(); ++it) {
664                 Inset & inset = *it->inset;
665                 if (inset.lyxCode() == INDEXMACRO_CODE) {
666                         InsetIndexMacro const & iim =
667                                 static_cast<InsetIndexMacro const &>(inset);
668                         if (iim.params().type == InsetIndexMacroParams::See
669                             || iim.params().type == InsetIndexMacroParams::Seealso)
670                                 return true;
671                 }
672         }
673         return false;
674 }
675
676
677 bool InsetIndex::hasSortKey() const
678 {
679         Paragraph const & par = paragraphs().front();
680         InsetList::const_iterator it = par.insetList().begin();
681         for (; it != par.insetList().end(); ++it) {
682                 Inset & inset = *it->inset;
683                 if (inset.lyxCode() == INDEXMACRO_SORTKEY_CODE)
684                         return true;
685         }
686         return false;
687 }
688
689
690 bool InsetIndex::macrosPossible(string const type) const
691 {
692         if (type != "see" && type != "seealso"
693             && type != "sortkey" && type != "subindex")
694                 return false;
695
696         Paragraph const & par = paragraphs().front();
697         InsetList::const_iterator it = par.insetList().begin();
698         int subidxs = 0;
699         for (; it != par.insetList().end(); ++it) {
700                 Inset & inset = *it->inset;
701                 if (type == "sortkey" && inset.lyxCode() == INDEXMACRO_SORTKEY_CODE)
702                         return false;
703                 if (inset.lyxCode() == INDEXMACRO_CODE) {
704                         InsetIndexMacro const & iim = static_cast<InsetIndexMacro const &>(inset);
705                         if ((type == "see" || type == "seealso")
706                              && (iim.params().type == InsetIndexMacroParams::See
707                                  || iim.params().type == InsetIndexMacroParams::Seealso))
708                                 return false;
709                         if (type == "subindex"
710                              && iim.params().type == InsetIndexMacroParams::Subindex) {
711                                 ++subidxs;
712                                 if (subidxs > 1)
713                                         return false;
714                         }
715                 }
716         }
717         return true;
718 }
719
720
721 ColorCode InsetIndex::labelColor() const
722 {
723         if (params_.index.empty() || params_.index == from_ascii("idx"))
724                 return InsetCollapsible::labelColor();
725         // FIXME UNICODE
726         ColorCode c = lcolor.getFromLyXName(to_utf8(params_.index)
727                                             + "@" + buffer().fileName().absFileName());
728         if (c == Color_none)
729                 c = InsetCollapsible::labelColor();
730         return c;
731 }
732
733
734 docstring InsetIndex::toolTip(BufferView const &, int, int) const
735 {
736         docstring tip = _("Index Entry");
737         if (buffer().params().use_indices && !params_.index.empty()) {
738                 Buffer const & realbuffer = *buffer().masterBuffer();
739                 IndicesList const & indiceslist = realbuffer.params().indiceslist();
740                 tip += " (";
741                 Index const * index = indiceslist.findShortcut(params_.index);
742                 if (!index)
743                         tip += _("unknown type!");
744                 else
745                         tip += index->index();
746                 tip += ")";
747         }
748         tip += ": ";
749         docstring res = toolTipText(tip);
750         if (!insetindexpagerangetranslator_loc().find(params_.range).empty())
751                 res += "\n" + insetindexpagerangetranslator_loc().find(params_.range);
752         if (!params_.pagefmt.empty() && params_.pagefmt != "default") {
753                 res += "\n" + _("Pagination format:") + " ";
754                 if (params_.pagefmt == "textbf")
755                         res += _("bold");
756                 else if (params_.pagefmt == "textit")
757                         res += _("italic");
758                 else if (params_.pagefmt == "emph")
759                         res += _("emphasized");
760                 else
761                         res += from_utf8(params_.pagefmt);
762         }
763         return res;
764 }
765
766
767 docstring const InsetIndex::buttonLabel(BufferView const & bv) const
768 {
769         InsetLayout const & il = getLayout();
770         docstring label = translateIfPossible(il.labelstring());
771
772         if (buffer().params().use_indices && !params_.index.empty()) {
773                 Buffer const & realbuffer = *buffer().masterBuffer();
774                 IndicesList const & indiceslist = realbuffer.params().indiceslist();
775                 label += " (";
776                 Index const * index = indiceslist.findShortcut(params_.index);
777                 if (!index)
778                         label += _("unknown type!");
779                 else
780                         label += index->index();
781                 label += ")";
782         }
783
784         docstring res;
785         if (!il.contentaslabel() || geometry(bv) != ButtonOnly)
786                 res = label;
787         else
788                 res = getNewLabel(label);
789         if (!insetindexpagerangetranslator_latex().find(params_.range).empty())
790                 res += " " + from_ascii(insetindexpagerangetranslator_latex().find(params_.range));
791         return res;
792 }
793
794
795 void InsetIndex::write(ostream & os) const
796 {
797         os << to_utf8(layoutName());
798         params_.write(os);
799         InsetCollapsible::write(os);
800 }
801
802
803 void InsetIndex::read(Lexer & lex)
804 {
805         params_.read(lex);
806         InsetCollapsible::read(lex);
807 }
808
809
810 string InsetIndex::params2string(InsetIndexParams const & params)
811 {
812         ostringstream data;
813         data << "index";
814         params.write(data);
815         return data.str();
816 }
817
818
819 void InsetIndex::string2params(string const & in, InsetIndexParams & params)
820 {
821         params = InsetIndexParams();
822         if (in.empty())
823                 return;
824
825         istringstream data(in);
826         Lexer lex;
827         lex.setStream(data);
828         lex.setContext("InsetIndex::string2params");
829         lex >> "index";
830         params.read(lex);
831 }
832
833
834 void InsetIndex::addToToc(DocIterator const & cpit, bool output_active,
835                                                   UpdateType utype, TocBackend & backend) const
836 {
837         DocIterator pit = cpit;
838         pit.push_back(CursorSlice(const_cast<InsetIndex &>(*this)));
839         docstring str;
840         string type = "index";
841         if (buffer().masterBuffer()->params().use_indices)
842                 type += ":" + to_utf8(params_.index);
843         // this is unlikely to be terribly long
844         text().forOutliner(str, INT_MAX);
845         TocBuilder & b = backend.builder(type);
846         b.pushItem(pit, str, output_active);
847         // Proceed with the rest of the inset.
848         InsetCollapsible::addToToc(cpit, output_active, utype, backend);
849         b.pop();
850 }
851
852
853 void InsetIndex::validate(LaTeXFeatures & features) const
854 {
855         if (buffer().masterBuffer()->params().use_indices
856             && !params_.index.empty()
857             && params_.index != "idx")
858                 features.require("splitidx");
859         InsetCollapsible::validate(features);
860 }
861
862
863 string InsetIndex::contextMenuName() const
864 {
865         return "context-index";
866 }
867
868
869 string InsetIndex::contextMenu(BufferView const & bv, int x, int y) const
870 {
871         // We override the implementation of InsetCollapsible,
872         // because we have eytra entries.
873         string owncm = "context-edit-index;";
874         return owncm + InsetCollapsible::contextMenu(bv, x, y);
875 }
876
877
878 bool InsetIndex::hasSettings() const
879 {
880         return true;
881 }
882
883
884 bool InsetIndex::insetAllowed(InsetCode code) const
885 {
886         switch (code) {
887         case INDEXMACRO_CODE:
888         case INDEXMACRO_SORTKEY_CODE:
889                 return true;
890         case INDEX_CODE:
891                 return false;
892         default:
893                 return InsetCollapsible::insetAllowed(code);
894         }
895 }
896
897
898 /////////////////////////////////////////////////////////////////////
899 //
900 // InsetIndexParams
901 //
902 ///////////////////////////////////////////////////////////////////////
903
904
905 void InsetIndexParams::write(ostream & os) const
906 {
907         os << ' ';
908         if (!index.empty())
909                 os << to_utf8(index);
910         else
911                 os << "idx";
912         os << '\n';
913         os << "range "
914            << insetindexpagerangetranslator().find(range)
915            << '\n';
916         os << "pageformat "
917            << pagefmt
918            << '\n';
919 }
920
921
922 void InsetIndexParams::read(Lexer & lex)
923 {
924         if (lex.eatLine())
925                 index = lex.getDocString();
926         else
927                 index = from_ascii("idx");
928         if (lex.checkFor("range")) {
929                 string st = lex.getString();
930                 if (lex.eatLine()) {
931                         st = lex.getString();
932                         range = insetindexpagerangetranslator().find(lex.getString());
933                 }
934         }
935         if (lex.checkFor("pageformat") && lex.eatLine()) {
936                 pagefmt = lex.getString();
937         }
938 }
939
940
941 /////////////////////////////////////////////////////////////////////
942 //
943 // InsetPrintIndex
944 //
945 ///////////////////////////////////////////////////////////////////////
946
947 InsetPrintIndex::InsetPrintIndex(Buffer * buf, InsetCommandParams const & p)
948         : InsetCommand(buf, p)
949 {}
950
951
952 ParamInfo const & InsetPrintIndex::findInfo(string const & /* cmdName */)
953 {
954         static ParamInfo param_info_;
955         if (param_info_.empty()) {
956                 param_info_.add("type", ParamInfo::LATEX_OPTIONAL,
957                                 ParamInfo::HANDLING_ESCAPE);
958                 param_info_.add("name", ParamInfo::LATEX_OPTIONAL,
959                                 ParamInfo::HANDLING_LATEXIFY);
960                 param_info_.add("literal", ParamInfo::LYX_INTERNAL);
961         }
962         return param_info_;
963 }
964
965
966 docstring InsetPrintIndex::screenLabel() const
967 {
968         bool const printall = suffixIs(getCmdName(), '*');
969         bool const multind = buffer().masterBuffer()->params().use_indices;
970         if ((!multind
971              && getParam("type") == from_ascii("idx"))
972             || (getParam("type").empty() && !printall))
973                 return _("Index");
974         Buffer const & realbuffer = *buffer().masterBuffer();
975         IndicesList const & indiceslist = realbuffer.params().indiceslist();
976         Index const * index = indiceslist.findShortcut(getParam("type"));
977         if (!index && !printall)
978                 return _("Unknown index type!");
979         docstring res = printall ? _("All indexes") : index->index();
980         if (!multind)
981                 res += " (" + _("non-active") + ")";
982         else if (contains(getCmdName(), "printsubindex"))
983                 res += " (" + _("subindex") + ")";
984         return res;
985 }
986
987
988 bool InsetPrintIndex::isCompatibleCommand(string const & s)
989 {
990         return s == "printindex" || s == "printsubindex"
991                 || s == "printindex*" || s == "printsubindex*";
992 }
993
994
995 void InsetPrintIndex::doDispatch(Cursor & cur, FuncRequest & cmd)
996 {
997         switch (cmd.action()) {
998
999         case LFUN_INSET_MODIFY: {
1000                 if (cmd.argument() == from_ascii("toggle-subindex")) {
1001                         string scmd = getCmdName();
1002                         if (contains(scmd, "printindex"))
1003                                 scmd = subst(scmd, "printindex", "printsubindex");
1004                         else
1005                                 scmd = subst(scmd, "printsubindex", "printindex");
1006                         cur.recordUndo();
1007                         setCmdName(scmd);
1008                         break;
1009                 } else if (cmd.argument() == from_ascii("check-printindex*")) {
1010                         string scmd = getCmdName();
1011                         if (suffixIs(scmd, '*'))
1012                                 break;
1013                         scmd += '*';
1014                         cur.recordUndo();
1015                         setParam("type", docstring());
1016                         setCmdName(scmd);
1017                         break;
1018                 }
1019                 InsetCommandParams p(INDEX_PRINT_CODE);
1020                 // FIXME UNICODE
1021                 InsetCommand::string2params(to_utf8(cmd.argument()), p);
1022                 if (p.getCmdName().empty()) {
1023                         cur.noScreenUpdate();
1024                         break;
1025                 }
1026                 cur.recordUndo();
1027                 setParams(p);
1028                 break;
1029         }
1030
1031         default:
1032                 InsetCommand::doDispatch(cur, cmd);
1033                 break;
1034         }
1035 }
1036
1037
1038 bool InsetPrintIndex::getStatus(Cursor & cur, FuncRequest const & cmd,
1039         FuncStatus & status) const
1040 {
1041         switch (cmd.action()) {
1042
1043         case LFUN_INSET_MODIFY: {
1044                 if (cmd.argument() == from_ascii("toggle-subindex")) {
1045                         status.setEnabled(buffer().masterBuffer()->params().use_indices);
1046                         status.setOnOff(contains(getCmdName(), "printsubindex"));
1047                         return true;
1048                 } else if (cmd.argument() == from_ascii("check-printindex*")) {
1049                         status.setEnabled(buffer().masterBuffer()->params().use_indices);
1050                         status.setOnOff(suffixIs(getCmdName(), '*'));
1051                         return true;
1052                 } if (cmd.getArg(0) == "index_print"
1053                     && cmd.getArg(1) == "CommandInset") {
1054                         InsetCommandParams p(INDEX_PRINT_CODE);
1055                         InsetCommand::string2params(to_utf8(cmd.argument()), p);
1056                         if (suffixIs(p.getCmdName(), '*')) {
1057                                 status.setEnabled(true);
1058                                 status.setOnOff(false);
1059                                 return true;
1060                         }
1061                         Buffer const & realbuffer = *buffer().masterBuffer();
1062                         IndicesList const & indiceslist =
1063                                 realbuffer.params().indiceslist();
1064                         Index const * index = indiceslist.findShortcut(p["type"]);
1065                         status.setEnabled(index != 0);
1066                         status.setOnOff(p["type"] == getParam("type"));
1067                         return true;
1068                 } else
1069                         return InsetCommand::getStatus(cur, cmd, status);
1070         }
1071
1072         case LFUN_INSET_DIALOG_UPDATE: {
1073                 status.setEnabled(buffer().masterBuffer()->params().use_indices);
1074                 return true;
1075         }
1076
1077         default:
1078                 return InsetCommand::getStatus(cur, cmd, status);
1079         }
1080 }
1081
1082
1083 void InsetPrintIndex::updateBuffer(ParIterator const &, UpdateType, bool const /*deleted*/)
1084 {
1085         Index const * index =
1086                 buffer().masterParams().indiceslist().findShortcut(getParam("type"));
1087         if (index)
1088                 setParam("name", index->index());
1089 }
1090
1091
1092 void InsetPrintIndex::latex(otexstream & os, OutputParams const & runparams_in) const
1093 {
1094         if (!buffer().masterBuffer()->params().use_indices) {
1095                 if (getParam("type") == from_ascii("idx"))
1096                         os << "\\printindex" << termcmd;
1097                 return;
1098         }
1099         OutputParams runparams = runparams_in;
1100         os << getCommand(runparams);
1101 }
1102
1103
1104 void InsetPrintIndex::validate(LaTeXFeatures & features) const
1105 {
1106         features.require("makeidx");
1107         if (buffer().masterBuffer()->params().use_indices)
1108                 features.require("splitidx");
1109         InsetCommand::validate(features);
1110 }
1111
1112
1113 string InsetPrintIndex::contextMenuName() const
1114 {
1115         return buffer().masterBuffer()->params().use_indices ?
1116                 "context-indexprint" : string();
1117 }
1118
1119
1120 bool InsetPrintIndex::hasSettings() const
1121 {
1122         return buffer().masterBuffer()->params().use_indices;
1123 }
1124
1125
1126 namespace {
1127
1128 void parseItem(docstring & s, bool for_output)
1129 {
1130         // this does not yet check for escaped things
1131         size_type loc = s.find(from_ascii("@"));
1132         if (loc != string::npos) {
1133                 if (for_output)
1134                         s.erase(0, loc + 1);
1135                 else
1136                         s.erase(loc);
1137         }
1138         loc = s.find(from_ascii("|"));
1139         if (loc != string::npos)
1140                 s.erase(loc);
1141 }
1142
1143
1144 void extractSubentries(docstring const & entry, docstring & main,
1145                 docstring & sub1, docstring & sub2)
1146 {
1147         if (entry.empty())
1148                 return;
1149         size_type const loc = entry.find(from_ascii(" ! "));
1150         if (loc == string::npos)
1151                 main = entry;
1152         else {
1153                 main = trim(entry.substr(0, loc));
1154                 size_t const locend = loc + 3;
1155                 size_type const loc2 = entry.find(from_ascii(" ! "), locend);
1156                 if (loc2 == string::npos) {
1157                         sub1 = trim(entry.substr(locend));
1158                 } else {
1159                         sub1 = trim(entry.substr(locend, loc2 - locend));
1160                         sub2 = trim(entry.substr(loc2 + 3));
1161                 }
1162         }
1163 }
1164
1165
1166 struct IndexEntry
1167 {
1168         IndexEntry()
1169         {}
1170
1171         IndexEntry(docstring const & s, DocIterator const & d)
1172                         : dit(d)
1173         {
1174                 extractSubentries(s, main, sub, subsub);
1175                 parseItem(main, false);
1176                 parseItem(sub, false);
1177                 parseItem(subsub, false);
1178         }
1179
1180         bool equal(IndexEntry const & rhs) const
1181         {
1182                 return main == rhs.main && sub == rhs.sub && subsub == rhs.subsub;
1183         }
1184
1185         bool same_sub(IndexEntry const & rhs) const
1186         {
1187                 return main == rhs.main && sub == rhs.sub;
1188         }
1189
1190         bool same_main(IndexEntry const & rhs) const
1191         {
1192                 return main == rhs.main;
1193         }
1194
1195         docstring main;
1196         docstring sub;
1197         docstring subsub;
1198         DocIterator dit;
1199 };
1200
1201 bool operator<(IndexEntry const & lhs, IndexEntry const & rhs)
1202 {
1203         int comp = compare_no_case(lhs.main, rhs.main);
1204         if (comp == 0)
1205                 comp = compare_no_case(lhs.sub, rhs.sub);
1206         if (comp == 0)
1207                 comp = compare_no_case(lhs.subsub, rhs.subsub);
1208         return (comp < 0);
1209 }
1210
1211 } // namespace
1212
1213
1214 docstring InsetPrintIndex::xhtml(XMLStream &, OutputParams const & op) const
1215 {
1216         BufferParams const & bp = buffer().masterBuffer()->params();
1217
1218         // we do not presently support multiple indices, so we refuse to print
1219         // anything but the main index, so as not to generate multiple indices.
1220         // NOTE Multiple index support would require some work. The reason
1221         // is that the TOC does not know about multiple indices. Either it would
1222         // need to be told about them (not a bad idea), or else the index entries
1223         // would need to be collected differently, say, during validation.
1224         if (bp.use_indices && getParam("type") != from_ascii("idx"))
1225                 return docstring();
1226
1227         shared_ptr<Toc const> toc = buffer().tocBackend().toc("index");
1228         if (toc->empty())
1229                 return docstring();
1230
1231         // Collect the index entries in a form we can use them.
1232         Toc::const_iterator it = toc->begin();
1233         Toc::const_iterator const en = toc->end();
1234         vector<IndexEntry> entries;
1235         for (; it != en; ++it)
1236                 if (it->isOutput())
1237                         entries.push_back(IndexEntry(it->str(), it->dit()));
1238
1239         if (entries.empty())
1240                 // not very likely that all the index entries are in notes or
1241                 // whatever, but....
1242                 return docstring();
1243
1244         stable_sort(entries.begin(), entries.end());
1245
1246         Layout const & lay = bp.documentClass().htmlTOCLayout();
1247         string const & tocclass = lay.defaultCSSClass();
1248         string const tocattr = "class='index " + tocclass + "'";
1249
1250         // we'll use our own stream, because we are going to defer everything.
1251         // that's how we deal with the fact that we're probably inside a standard
1252         // paragraph, and we don't want to be.
1253         odocstringstream ods;
1254         XMLStream xs(ods);
1255
1256         xs << xml::StartTag("div", tocattr);
1257         xs << xml::StartTag(lay.htmltag(), lay.htmlattr())
1258                  << translateIfPossible(from_ascii("Index"),
1259                                   op.local_font->language()->lang())
1260                  << xml::EndTag(lay.htmltag());
1261         xs << xml::StartTag("ul", "class='main'");
1262         Font const dummy;
1263
1264         vector<IndexEntry>::const_iterator eit = entries.begin();
1265         vector<IndexEntry>::const_iterator const een = entries.end();
1266         // tracks whether we are already inside a main entry (1),
1267         // a sub-entry (2), or a sub-sub-entry (3). see below for the
1268         // details.
1269         int level = 1;
1270         // the last one we saw
1271         IndexEntry last;
1272         int entry_number = -1;
1273         for (; eit != een; ++eit) {
1274                 Paragraph const & par = eit->dit.innerParagraph();
1275                 if (entry_number == -1 || !eit->equal(last)) {
1276                         if (entry_number != -1) {
1277                                 // not the first time through the loop, so
1278                                 // close last entry or entries, depending.
1279                                 if (level == 3) {
1280                                         // close this sub-sub-entry
1281                                         xs << xml::EndTag("li") << xml::CR();
1282                                         // is this another sub-sub-entry within the same sub-entry?
1283                                         if (!eit->same_sub(last)) {
1284                                                 // close this level
1285                                                 xs << xml::EndTag("ul") << xml::CR();
1286                                                 level = 2;
1287                                         }
1288                                 }
1289                                 // the point of the second test here is that we might get
1290                                 // here two ways: (i) by falling through from above; (ii) because,
1291                                 // though the sub-entry hasn't changed, the sub-sub-entry has,
1292                                 // which means that it is the first sub-sub-entry within this
1293                                 // sub-entry. In that case, we do not want to close anything.
1294                                 if (level == 2 && !eit->same_sub(last)) {
1295                                         // close sub-entry
1296                                         xs << xml::EndTag("li") << xml::CR();
1297                                         // is this another sub-entry with the same main entry?
1298                                         if (!eit->same_main(last)) {
1299                                                 // close this level
1300                                                 xs << xml::EndTag("ul") << xml::CR();
1301                                                 level = 1;
1302                                         }
1303                                 }
1304                                 // again, we can get here two ways: from above, or because we have
1305                                 // found the first sub-entry. in the latter case, we do not want to
1306                                 // close the entry.
1307                                 if (level == 1 && !eit->same_main(last)) {
1308                                         // close entry
1309                                         xs << xml::EndTag("li") << xml::CR();
1310                                 }
1311                         }
1312
1313                         // we'll be starting new entries
1314                         entry_number = 0;
1315
1316                         // We need to use our own stream, since we will have to
1317                         // modify what we get back.
1318                         odocstringstream ent;
1319                         XMLStream entstream(ent);
1320                         OutputParams ours = op;
1321                         ours.for_toc = true;
1322                         par.simpleLyXHTMLOnePar(buffer(), entstream, ours, dummy);
1323
1324                         // these will contain XHTML versions of the main entry, etc
1325                         // remember that everything will already have been escaped,
1326                         // so we'll need to use NextRaw() during output.
1327                         docstring main;
1328                         docstring sub;
1329                         docstring subsub;
1330                         extractSubentries(ent.str(), main, sub, subsub);
1331                         parseItem(main, true);
1332                         parseItem(sub, true);
1333                         parseItem(subsub, true);
1334
1335                         if (level == 3) {
1336                                 // another subsubentry
1337                                 xs << xml::StartTag("li", "class='subsubentry'")
1338                                    << XMLStream::ESCAPE_NONE << subsub;
1339                         } else if (level == 2) {
1340                                 // there are two ways we can be here:
1341                                 // (i) we can actually be inside a sub-entry already and be about
1342                                 //     to output the first sub-sub-entry. in this case, our sub
1343                                 //     and the last sub will be the same.
1344                                 // (ii) we can just have closed a sub-entry, possibly after also
1345                                 //     closing a list of sub-sub-entries. here our sub and the last
1346                                 //     sub are different.
1347                                 // only in the latter case do we need to output the new sub-entry.
1348                                 // note that in this case, too, though, the sub-entry might already
1349                                 // have a sub-sub-entry.
1350                                 if (eit->sub != last.sub)
1351                                         xs << xml::StartTag("li", "class='subentry'")
1352                                            << XMLStream::ESCAPE_NONE << sub;
1353                                 if (!subsub.empty()) {
1354                                         // it's actually a subsubentry, so we need to start that list
1355                                         xs << xml::CR()
1356                                            << xml::StartTag("ul", "class='subsubentry'")
1357                                            << xml::StartTag("li", "class='subsubentry'")
1358                                            << XMLStream::ESCAPE_NONE << subsub;
1359                                         level = 3;
1360                                 }
1361                         } else {
1362                                 // there are also two ways we can be here:
1363                                 // (i) we can actually be inside an entry already and be about
1364                                 //     to output the first sub-entry. in this case, our main
1365                                 //     and the last main will be the same.
1366                                 // (ii) we can just have closed an entry, possibly after also
1367                                 //     closing a list of sub-entries. here our main and the last
1368                                 //     main are different.
1369                                 // only in the latter case do we need to output the new main entry.
1370                                 // note that in this case, too, though, the main entry might already
1371                                 // have a sub-entry, or even a sub-sub-entry.
1372                                 if (eit->main != last.main)
1373                                         xs << xml::StartTag("li", "class='main'") << main;
1374                                 if (!sub.empty()) {
1375                                         // there's a sub-entry, too
1376                                         xs << xml::CR()
1377                                            << xml::StartTag("ul", "class='subentry'")
1378                                            << xml::StartTag("li", "class='subentry'")
1379                                            << XMLStream::ESCAPE_NONE << sub;
1380                                         level = 2;
1381                                         if (!subsub.empty()) {
1382                                                 // and a sub-sub-entry
1383                                                 xs << xml::CR()
1384                                                    << xml::StartTag("ul", "class='subsubentry'")
1385                                                    << xml::StartTag("li", "class='subsubentry'")
1386                                                    << XMLStream::ESCAPE_NONE << subsub;
1387                                                 level = 3;
1388                                         }
1389                                 }
1390                         }
1391                 }
1392                 // finally, then, we can output the index link itself
1393                 string const parattr = "href='#" + par.magicLabel() + "'";
1394                 xs << (entry_number == 0 ? ":" : ",");
1395                 xs << " " << xml::StartTag("a", parattr)
1396                    << ++entry_number << xml::EndTag("a");
1397                 last = *eit;
1398         }
1399         // now we have to close all the open levels
1400         while (level > 0) {
1401                 xs << xml::EndTag("li") << xml::EndTag("ul") << xml::CR();
1402                 --level;
1403         }
1404         xs << xml::EndTag("div") << xml::CR();
1405         return ods.str();
1406 }
1407
1408 } // namespace lyx