]> git.lyx.org Git - features.git/blob - src/insets/InsetIndex.cpp
InsetIndex: when building the IndexNode tree, ignore IndexEntry when empty
[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 "CutAndPaste.h"
22 #include "DispatchResult.h"
23 #include "Encoding.h"
24 #include "ErrorList.h"
25 #include "FuncRequest.h"
26 #include "FuncStatus.h"
27 #include "IndicesList.h"
28 #include "InsetList.h"
29 #include "Language.h"
30 #include "LaTeX.h"
31 #include "LaTeXFeatures.h"
32 #include "Lexer.h"
33 #include "LyX.h"
34 #include "output_latex.h"
35 #include "output_xhtml.h"
36 #include "xml.h"
37 #include "texstream.h"
38 #include "TextClass.h"
39 #include "TocBackend.h"
40
41 #include "support/debug.h"
42 #include "support/docstream.h"
43 #include "support/FileName.h"
44 #include "support/gettext.h"
45 #include "support/lstrings.h"
46 #include "support/Translator.h"
47
48 #include "frontends/alert.h"
49
50 #include <algorithm>
51 #include <set>
52 #include <iostream>
53
54 #include <QThreadStorage>
55
56 using namespace std;
57 using namespace lyx::support;
58
59 // Uncomment to enable InsetIndex-specific debugging mode: the tree for the index will be printed to std::cout.
60 // #define LYX_INSET_INDEX_DEBUG
61
62 namespace lyx {
63
64 namespace {
65
66 typedef Translator<string, InsetIndexParams::PageRange> PageRangeTranslator;
67 typedef Translator<docstring, InsetIndexParams::PageRange> PageRangeTranslatorLoc;
68
69 PageRangeTranslator const init_insetindexpagerangetranslator()
70 {
71         PageRangeTranslator translator("none", InsetIndexParams::None);
72         translator.addPair("start", InsetIndexParams::Start);
73         translator.addPair("end", InsetIndexParams::End);
74         return translator;
75 }
76
77 PageRangeTranslator const init_insetindexpagerangetranslator_latex()
78 {
79         PageRangeTranslator translator("", InsetIndexParams::None);
80         translator.addPair("(", InsetIndexParams::Start);
81         translator.addPair(")", InsetIndexParams::End);
82         return translator;
83 }
84
85
86 PageRangeTranslatorLoc const init_insetindexpagerangetranslator_loc()
87 {
88         PageRangeTranslatorLoc translator(docstring(), InsetIndexParams::None);
89         translator.addPair(_("Starts page range"), InsetIndexParams::Start);
90         translator.addPair(_("Ends page range"), InsetIndexParams::End);
91         return translator;
92 }
93
94
95 PageRangeTranslator const & insetindexpagerangetranslator()
96 {
97         static PageRangeTranslator const prtranslator =
98                         init_insetindexpagerangetranslator();
99         return prtranslator;
100 }
101
102
103 PageRangeTranslatorLoc const & insetindexpagerangetranslator_loc()
104 {
105         static PageRangeTranslatorLoc const translator =
106                         init_insetindexpagerangetranslator_loc();
107         return translator;
108 }
109
110
111 PageRangeTranslator const & insetindexpagerangetranslator_latex()
112 {
113         static PageRangeTranslator const lttranslator =
114                         init_insetindexpagerangetranslator_latex();
115         return lttranslator;
116 }
117
118 } // namespace anon
119
120 /////////////////////////////////////////////////////////////////////
121 //
122 // InsetIndex
123 //
124 ///////////////////////////////////////////////////////////////////////
125
126
127 InsetIndex::InsetIndex(Buffer * buf, InsetIndexParams const & params)
128         : InsetCollapsible(buf), params_(params)
129 {}
130
131
132 void InsetIndex::latex(otexstream & ios, OutputParams const & runparams_in) const
133 {
134         OutputParams runparams(runparams_in);
135         runparams.inIndexEntry = true;
136         if (runparams_in.postpone_fragile_stuff)
137                 // This is not needed and would impact sorting
138                 runparams.moving_arg = false;
139
140         otexstringstream os;
141
142         if (buffer().masterBuffer()->params().use_indices && !params_.index.empty()
143                 && params_.index != "idx") {
144                 os << "\\sindex[";
145                 os << escape(params_.index);
146                 os << "]{";
147         } else {
148                 os << "\\index";
149                 os << '{';
150         }
151
152         // Get the LaTeX output from InsetText. We need to deconstruct this later
153         // in order to check if we need to generate a sorting key
154         odocstringstream ourlatex;
155         otexstream ots(ourlatex);
156         InsetText::latex(ots, runparams);
157         if (runparams.find_effective()) {
158                 // No need for special handling, if we are only searching for some patterns
159                 os << ourlatex.str() << "}";
160                 return;
161         }
162
163         if (hasSortKey()) {
164                 getSortkey(os, runparams);
165                 os << "@";
166                 os << ourlatex.str();
167                 getSubentries(os, runparams, ourlatex.str());
168                 if (hasSeeRef()) {
169                         os << "|";
170                         os << insetindexpagerangetranslator_latex().find(params_.range);
171                         getSeeRefs(os, runparams);
172                 } else if (!params_.pagefmt.empty() && params_.pagefmt != "default") {
173                         os << "|";
174                         os << insetindexpagerangetranslator_latex().find(params_.range);
175                         os << from_utf8(params_.pagefmt);
176                 } else if (params_.range != InsetIndexParams::PageRange::None) {
177                         os << "|";
178                         os << insetindexpagerangetranslator_latex().find(params_.range);
179                 }
180         } else {
181                 // We check whether we need a sort key.
182                 // If so, we use the plaintext version
183                 odocstringstream ourplain;
184                 InsetText::plaintext(ourplain, runparams);
185
186                 // These are the LaTeX and plaintext representations
187                 docstring latexstr = ourlatex.str();
188                 docstring plainstr = ourplain.str();
189         
190                 // This will get what follows | if anything does,
191                 // the command (e.g., see, textbf) for pagination
192                 // formatting
193                 docstring cmd;
194
195                 if (hasSeeRef()) {
196                         odocstringstream seeref;
197                         otexstream otsee(seeref);
198                         getSeeRefs(otsee, runparams);
199                         cmd = seeref.str();
200                 } else if (!params_.pagefmt.empty() && params_.pagefmt != "default") {
201                         cmd = from_utf8(params_.pagefmt);
202                 } else {
203                         // Check for the | separator to strip the cmd.
204                         // This goes wrong on an escaped "|", but as the escape
205                         // character can be changed in style files, we cannot
206                         // prevent that.
207                         size_t pos = latexstr.find(from_ascii("|"));
208                         if (pos != docstring::npos) {
209                                 // Put the bit after "|" into cmd...
210                                 cmd = latexstr.substr(pos + 1);
211                                 // ...and erase that stuff from latexstr
212                                 latexstr = latexstr.erase(pos);
213                                 // ...as well as from plainstr
214                                 size_t ppos = plainstr.find(from_ascii("|"));
215                                 if (ppos < plainstr.size())
216                                         plainstr.erase(ppos);
217                                 else
218                                         LYXERR0("The `|' separator was not found in the plaintext version!");
219                         }
220                 }
221
222                 odocstringstream subentries;
223                 otexstream otsub(subentries);
224                 getSubentries(otsub, runparams, ourlatex.str());
225                 if (subentries.str().empty()) {
226                         // Separate the entries and subentries, i.e., split on "!".
227                         // This goes wrong on an escaped "!", but as the escape
228                         // character can be changed in style files, we cannot
229                         // prevent that.
230                         std::vector<docstring> const levels =
231                                         getVectorFromString(latexstr, from_ascii("!"), true);
232                         std::vector<docstring> const levels_plain =
233                                         getVectorFromString(plainstr, from_ascii("!"), true);
234                 
235                         vector<docstring>::const_iterator it = levels.begin();
236                         vector<docstring>::const_iterator end = levels.end();
237                         vector<docstring>::const_iterator it2 = levels_plain.begin();
238                         bool first = true;
239                         for (; it != end; ++it) {
240                                 if ((*it).empty()) {
241                                         emptySubentriesWarning(ourlatex.str());
242                                         if (it2 < levels_plain.end())
243                                                 ++it2;
244                                         continue;
245                                 }
246                                 // The separator needs to be put back when
247                                 // writing the levels, except for the first level
248                                 if (!first)
249                                         os << '!';
250                                 else
251                                         first = false;
252                 
253                                 // Now here comes the reason for this whole procedure:
254                                 // We try to correctly sort macros and formatted strings.
255                                 // If we find a command, prepend a plain text
256                                 // version of the content to get sorting right,
257                                 // e.g. \index{LyX@\LyX}, \index{text@\textbf{text}}.
258                                 // We do this on all levels.
259                                 // We don't do it if the level already contains a '@', though.
260                                 // Plaintext might return nothing (e.g. for ERTs).
261                                 // In that case, we use LaTeX.
262                                 docstring const spart = (levels_plain.empty() || (*it2).empty()) ? *it : *it2;
263                                 processLatexSorting(os, runparams, *it, spart);
264                                 if (it2 < levels_plain.end())
265                                         ++it2;
266                         }
267                 } else {
268                         processLatexSorting(os, runparams, latexstr, plainstr);
269                         os << subentries.str();
270                 }
271
272                 // At last, re-insert the command, separated by "|"
273                 if (!cmd.empty()) {
274                         os << "|"
275                            << insetindexpagerangetranslator_latex().find(params_.range)
276                            << cmd;
277                 } else if (params_.range != InsetIndexParams::PageRange::None) {
278                         os << "|";
279                         os << insetindexpagerangetranslator_latex().find(params_.range);
280                 }
281         }
282         os << '}';
283
284         // In macros with moving arguments, such as \section,
285         // we store the index and output it after the macro (#2154)
286         if (runparams_in.postpone_fragile_stuff)
287                 runparams_in.post_macro += os.str();
288         else
289                 ios << os.release();
290 }
291
292
293 void InsetIndex::processLatexSorting(otexstream & os, OutputParams const & runparams,
294                                 docstring const latex, docstring const spart) const
295 {
296         if (contains(latex, '\\') && !contains(latex, '@')) {
297                 // Now we need to validate that all characters in
298                 // the sorting part are representable in the current
299                 // encoding. If not try the LaTeX macro which might
300                 // or might not be a good choice, and issue a warning.
301                 pair<docstring, docstring> spart_latexed =
302                                 runparams.encoding->latexString(spart, runparams.dryrun);
303                 if (!spart_latexed.second.empty())
304                         LYXERR0("Uncodable character in index entry. Sorting might be wrong!");
305                 if (spart != spart_latexed.first && !runparams.dryrun) {
306                         TeXErrors terr;
307                         ErrorList & errorList = buffer().errorList("Export");
308                         docstring const s = bformat(_("LyX's automatic index sorting algorithm faced "
309                                                       "problems with the entry '%1$s'.\n"
310                                                       "Please specify the sorting of this entry manually, as "
311                                                       "explained in the User Guide."), spart);
312                         Paragraph const & par = buffer().paragraphs().front();
313                         errorList.push_back(ErrorItem(_("Index sorting failed"), s,
314                                                       {par.id(), 0}, {par.id(), -1}));
315                         buffer().bufferErrors(terr, errorList);
316                 }
317                 // Remove remaining \'s from the sort key
318                 docstring ppart = subst(spart_latexed.first, from_ascii("\\"), docstring());
319                 // Plain quotes need to be escaped, however (#10649), as this
320                 // is the default escape character
321                 ppart = subst(ppart, from_ascii("\""), from_ascii("\\\""));
322
323                 // Now insert the sortkey, separated by '@'.
324                 os << ppart;
325                 os << '@';
326         }
327         // Insert the actual level text
328         os << latex;
329 }
330
331
332 void InsetIndex::docbook(XMLStream & xs, OutputParams const & runparams) const
333 {
334         // Two ways of processing this inset are implemented:
335         // - the legacy one, based on parsing the raw LaTeX (before LyX 2.4) -- unlikely to be deprecated
336         // - the modern one, based on precise insets for indexing features
337         // Like the LaTeX implementation, consider the user chooses either of those options.
338
339         // Get the content of the inset as LaTeX, as some things may be encoded as ERT (like {}).
340         // TODO: if there is an ERT within the index term, its conversion should be tried, in case it becomes useful;
341         //  otherwise, ERTs should become comments. For now, they are just copied as-is, which is barely satisfactory.
342         odocstringstream odss;
343         otexstream ots(odss);
344         InsetText::latex(ots, runparams);
345         docstring latexString = trim(odss.str());
346
347         // Handle several indices (indicated in the inset instead of the raw latexString).
348         docstring indexType = from_utf8("");
349         if (buffer().masterBuffer()->params().use_indices) {
350                 indexType += " type=\"" + params_.index + "\"";
351         }
352
353         // Split the string into its main constituents: terms, and command (see, see also, range).
354         size_t positionVerticalBar = latexString.find(from_ascii("|")); // What comes before | is (sub)(sub)entries.
355         docstring indexTerms = latexString.substr(0, positionVerticalBar);
356         docstring command;
357         if (positionVerticalBar != lyx::docstring::npos) {
358                 command = latexString.substr(positionVerticalBar + 1);
359         }
360
361         // Handle sorting issues, with @.
362         docstring sortAs;
363         if (hasSortKey()) {
364                 sortAs = getSortkeyAsText(runparams);
365                 // indexTerms may contain a sort key if the user has both the inset and the manual key.
366         } else {
367                 vector<docstring> sortingElements = getVectorFromString(indexTerms, from_ascii("@"), false);
368                 if (sortingElements.size() == 2) {
369                         sortAs = sortingElements[0];
370                         indexTerms = sortingElements[1];
371                 }
372         }
373
374         // Handle primary, secondary, and tertiary terms (entries, subentries, and subsubentries, for LaTeX).
375         vector<docstring> terms;
376         const vector<docstring> potential_terms = getSubentriesAsText(runparams);
377         if (!potential_terms.empty()) {
378                 terms = potential_terms;
379                 // The main term is not present in the vector, as it's not a subentry. The main index term is inserted raw in
380                 // the index inset. Considering that the user either uses the new or the legacy mechanism, the main term is the
381                 // full string within this inset (i.e. without the subinsets).
382                 terms.insert(terms.begin(), latexString);
383         } else {
384                 terms = getVectorFromString(indexTerms, from_ascii("!"), false);
385         }
386
387         // Handle ranges. Happily, in the raw LaTeX mode, (| and |) can only be at the end of the string!
388         const bool hasInsetRange = params_.range != InsetIndexParams::PageRange::None;
389         const bool hasStartRange = params_.range == InsetIndexParams::PageRange::Start ||
390                         latexString.find(from_ascii("|(")) != lyx::docstring::npos;
391         const bool hasEndRange = params_.range == InsetIndexParams::PageRange::End ||
392                         latexString.find(from_ascii("|)")) != lyx::docstring::npos;
393
394         if (hasInsetRange) {
395                 // Remove the ranges from the command if they do not appear at the beginning.
396                 size_t index = 0;
397                 while ((index = command.find(from_utf8("|("), index)) != std::string::npos)
398                         command.erase(index, 1);
399                 index = 0;
400                 while ((index = command.find(from_utf8("|)"), index)) != std::string::npos)
401                         command.erase(index, 1);
402
403                 // Remove the ranges when they are the only vertical bar in the complete string.
404                 if (command[0] == '(' || command[0] == ')')
405                         command.erase(0, 1);
406         }
407
408         // Handle see and seealso. As "see" is a prefix of "seealso", the order of the comparisons is important.
409         // Both commands are mutually exclusive!
410         docstring see = getSeeAsText(runparams);
411         vector<docstring> seeAlsoes = getSeeAlsoesAsText(runparams);
412
413         if (see.empty() && seeAlsoes.empty() && command.substr(0, 3) == "see") {
414                 // Unescape brackets.
415                 size_t index = 0;
416                 while ((index = command.find(from_utf8("\\{"), index)) != std::string::npos)
417                         command.erase(index, 1);
418                 index = 0;
419                 while ((index = command.find(from_utf8("\\}"), index)) != std::string::npos)
420                         command.erase(index, 1);
421
422                 // Retrieve the part between brackets, and remove the complete seealso.
423                 size_t positionOpeningBracket = command.find(from_ascii("{"));
424                 size_t positionClosingBracket = command.find(from_ascii("}"));
425                 docstring list = command.substr(positionOpeningBracket + 1, positionClosingBracket - positionOpeningBracket - 1);
426
427                 // Parse the list of referenced entries (or a single one for see).
428                 if (command.substr(0, 7) == "seealso") {
429                         seeAlsoes = getVectorFromString(list, from_ascii(","), false);
430                 } else {
431                         see = list;
432
433                         if (see.find(from_ascii(",")) != std::string::npos) {
434                                 docstring error = from_utf8("Several index terms found as \"see\"! Only one is acceptable. "
435                                                                                         "Complete entry: \"") + latexString + from_utf8("\"");
436                                 LYXERR0(error);
437                                 xs << XMLStream::ESCAPE_NONE << (from_utf8("<!-- Output Error: ") + error + from_utf8(" -->\n"));
438                         }
439                 }
440
441                 // Remove the complete see/seealso from the commands, in case there is something else to parse.
442                 command = command.substr(positionClosingBracket + 1);
443         }
444
445         // Some parts of the strings are not parsed, as they do not have anything matching in DocBook: things like
446         // formatting the entry or the page number, other strings for sorting. https://wiki.lyx.org/Tips/Indexing
447         // If there are such things in the index entry, then this code may miserably fail. For example, for "Peter|(textbf",
448         // no range will be detected.
449         // TODO: Could handle formatting as significance="preferred"?
450         if (!command.empty()) {
451                 docstring error = from_utf8("Unsupported feature: an index entry contains a | with an unsupported command, ")
452                                           + command + from_utf8(". ") + from_utf8("Complete entry: \"") + latexString + from_utf8("\"");
453                 LYXERR0(error);
454                 xs << XMLStream::ESCAPE_NONE << (from_utf8("<!-- Output Error: ") + error + from_utf8(" -->\n"));
455         }
456
457         // Write all of this down.
458         if (terms.empty() && !hasEndRange) {
459                 docstring error = from_utf8("No index term found! Complete entry: \"") + latexString + from_utf8("\"");
460                 LYXERR0(error);
461                 xs << XMLStream::ESCAPE_NONE << (from_utf8("<!-- Output Error: ") + error + from_utf8(" -->\n"));
462         } else {
463                 // Generate the attributes for ranges. It is based on the terms that are indexed, but the ID must be unique
464                 // to this indexing area (xml::cleanID does not guarantee this: for each call with the same arguments,
465                 // the same legal ID is produced; here, as the input would be the same, the output must be, by design).
466                 // Hence the thread-local storage, as the numbers must strictly be unique, and thus cannot be shared across
467                 // a paragraph (making the solution used for HTML worthless). This solution is very similar to the one used in
468                 // xml::cleanID.
469                 // indexType can only be used for singular and startofrange types!
470                 docstring attrs;
471                 if (!hasStartRange && !hasEndRange) {
472                         attrs = indexType;
473                 } else {
474                         // Append an ID if uniqueness is not guaranteed across the document.
475                         static QThreadStorage<set<docstring>> tKnownTermLists;
476                         static QThreadStorage<int> tID;
477
478                         set<docstring> &knownTermLists = tKnownTermLists.localData();
479                         int &ID = tID.localData();
480
481                         if (!tID.hasLocalData()) {
482                                 tID.localData() = 0;
483                         }
484
485                         // Modify the index terms to add the unique ID if needed.
486                         docstring newIndexTerms = indexTerms;
487                         if (knownTermLists.find(indexTerms) != knownTermLists.end()) {
488                                 newIndexTerms += from_ascii(string("-") + to_string(ID));
489
490                                 // Only increment for the end of range, so that the same number is used for the start of range.
491                                 if (hasEndRange) {
492                                         ID++;
493                                 }
494                         }
495
496                         // Term list not yet known: add it to the set AFTER the end of range. After
497                         if (knownTermLists.find(indexTerms) == knownTermLists.end() && hasEndRange) {
498                                 knownTermLists.insert(indexTerms);
499                         }
500
501                         // Generate the attributes.
502                         docstring id = xml::cleanID(newIndexTerms);
503                         if (hasStartRange) {
504                                 attrs = indexType + " class=\"startofrange\" xml:id=\"" + id + "\"";
505                         } else {
506                                 attrs = " class=\"endofrange\" startref=\"" + id + "\"";
507                         }
508                 }
509
510                 // Handle the index terms (including the specific index for this entry).
511                 if (hasEndRange) {
512                         xs << xml::CompTag("indexterm", attrs);
513                 } else {
514                         xs << xml::StartTag("indexterm", attrs);
515                         if (!terms.empty()) { // hasEndRange has no content.
516                                 docstring attr;
517                                 if (!sortAs.empty()) {
518                                         attr = from_utf8("sortas='") + sortAs + from_utf8("'");
519                                 }
520
521                                 xs << xml::StartTag("primary", attr);
522                                 xs << terms[0];
523                                 xs << xml::EndTag("primary");
524                         }
525                         if (terms.size() > 1) {
526                                 xs << xml::StartTag("secondary");
527                                 xs << terms[1];
528                                 xs << xml::EndTag("secondary");
529                         }
530                         if (terms.size() > 2) {
531                                 xs << xml::StartTag("tertiary");
532                                 xs << terms[2];
533                                 xs << xml::EndTag("tertiary");
534                         }
535
536                         // Handle see and see also.
537                         if (!see.empty()) {
538                                 xs << xml::StartTag("see");
539                                 xs << see;
540                                 xs << xml::EndTag("see");
541                         }
542
543                         if (!seeAlsoes.empty()) {
544                                 for (auto &entry : seeAlsoes) {
545                                         xs << xml::StartTag("seealso");
546                                         xs << entry;
547                                         xs << xml::EndTag("seealso");
548                                 }
549                         }
550
551                         // Close the entry.
552                         xs << xml::EndTag("indexterm");
553                 }
554         }
555 }
556
557
558 docstring InsetIndex::xhtml(XMLStream & xs, OutputParams const &) const
559 {
560         // we just print an anchor, taking the paragraph ID from
561         // our own interior paragraph, which doesn't get printed
562         std::string const magic = paragraphs().front().magicLabel();
563         std::string const attr = "id='" + magic + "'";
564         xs << xml::CompTag("a", attr);
565         return docstring();
566 }
567
568
569 bool InsetIndex::showInsetDialog(BufferView * bv) const
570 {
571         bv->showDialog("index", params2string(params_),
572                         const_cast<InsetIndex *>(this));
573         return true;
574 }
575
576
577 void InsetIndex::doDispatch(Cursor & cur, FuncRequest & cmd)
578 {
579         switch (cmd.action()) {
580
581         case LFUN_INSET_MODIFY: {
582                 if (cmd.getArg(0) == "changetype") {
583                         cur.recordUndoInset(this);
584                         params_.index = from_utf8(cmd.getArg(1));
585                         break;
586                 }
587                 if (cmd.getArg(0) == "changeparam") {
588                         string const p = cmd.getArg(1);
589                         string const v = cmd.getArg(2);
590                         cur.recordUndoInset(this);
591                         if (p == "range")
592                                 params_.range = insetindexpagerangetranslator().find(v);
593                         if (p == "pagefmt") {
594                                 if (v == "default" || v == "textbf"
595                                     || v == "textit" || v == "emph")
596                                         params_.pagefmt = v;
597                                 else
598                                         lyx::dispatch(FuncRequest(LFUN_INSET_SETTINGS, "index"));
599                         }
600                         break;
601                 }
602                 InsetIndexParams params;
603                 InsetIndex::string2params(to_utf8(cmd.argument()), params);
604                 cur.recordUndoInset(this);
605                 params_.index = params.index;
606                 params_.range = params.range;
607                 params_.pagefmt = params.pagefmt;
608                 // what we really want here is a TOC update, but that means
609                 // a full buffer update
610                 cur.forceBufferUpdate();
611                 break;
612         }
613
614         case LFUN_INSET_DIALOG_UPDATE:
615                 cur.bv().updateDialog("index", params2string(params_));
616                 break;
617
618         case LFUN_PARAGRAPH_BREAK: {
619                 // Since this inset in single-par anyway, let's use
620                 // return to enter subentries
621                 FuncRequest fr(LFUN_INDEXMACRO_INSERT, "subentry");
622                 lyx::dispatch(fr);
623                 break;
624         }
625
626         case LFUN_INSET_INSERT_COPY: {
627                 Cursor & bvcur = cur.bv().cursor();
628                 if (cmd.origin() == FuncRequest::TOC && bvcur.inTexted()) {
629                         cap::copyInsetToTemp(cur, clone());
630                         cap::pasteFromTemp(bvcur, bvcur.buffer()->errorList("Paste"));
631                 } else
632                         cur.undispatched();
633                 break;
634         }
635
636         default:
637                 InsetCollapsible::doDispatch(cur, cmd);
638                 break;
639         }
640 }
641
642
643 bool InsetIndex::getStatus(Cursor & cur, FuncRequest const & cmd,
644                 FuncStatus & flag) const
645 {
646         switch (cmd.action()) {
647
648         case LFUN_INSET_MODIFY:
649                 if (cmd.getArg(0) == "changetype") {
650                         docstring const newtype = from_utf8(cmd.getArg(1));
651                         Buffer const & realbuffer = *buffer().masterBuffer();
652                         IndicesList const & indiceslist = realbuffer.params().indiceslist();
653                         Index const * index = indiceslist.findShortcut(newtype);
654                         flag.setEnabled(index != 0);
655                         flag.setOnOff(
656                                 from_utf8(cmd.getArg(1)) == params_.index);
657                         return true;
658                 }
659                 if (cmd.getArg(0) == "changeparam") {
660                         string const p = cmd.getArg(1);
661                         string const v = cmd.getArg(2);
662                         if (p == "range") {
663                                 flag.setEnabled(v == "none" || v == "start" || v == "end");
664                                 flag.setOnOff(params_.range == insetindexpagerangetranslator().find(v));
665                         }
666                         if (p == "pagefmt") {
667                                 flag.setEnabled(!v.empty());
668                                 if (params_.pagefmt == "default" || params_.pagefmt == "textbf"
669                                     || params_.pagefmt == "textit" || params_.pagefmt == "emph")
670                                         flag.setOnOff(params_.pagefmt == v);
671                                 else
672                                         flag.setOnOff(v == "custom");
673                         }
674                         return true;
675                 }
676                 return InsetCollapsible::getStatus(cur, cmd, flag);
677
678         case LFUN_INSET_DIALOG_UPDATE: {
679                 Buffer const & realbuffer = *buffer().masterBuffer();
680                 flag.setEnabled(realbuffer.params().use_indices);
681                 return true;
682         }
683
684         case LFUN_INSET_INSERT_COPY:
685                 // This can only be invoked by ToC widget
686                 flag.setEnabled(cmd.origin() == FuncRequest::TOC
687                                 && cur.bv().cursor().inset().insetAllowed(lyxCode()));
688                 return true;
689
690         case LFUN_PARAGRAPH_BREAK:
691                 return macrosPossible("subentry");
692
693         case LFUN_INDEXMACRO_INSERT:
694                 return macrosPossible(cmd.getArg(0));
695
696         case LFUN_INDEX_TAG_ALL:
697                 return true;
698
699         default:
700                 return InsetCollapsible::getStatus(cur, cmd, flag);
701         }
702 }
703
704
705 void InsetIndex::getSortkey(otexstream & os, OutputParams const & runparams) const
706 {
707         Paragraph const & par = paragraphs().front();
708         InsetList::const_iterator it = par.insetList().begin();
709         for (; it != par.insetList().end(); ++it) {
710                 Inset & inset = *it->inset;
711                 if (inset.lyxCode() == INDEXMACRO_SORTKEY_CODE) {
712                         InsetIndexMacro const & iim =
713                                 static_cast<InsetIndexMacro const &>(inset);
714                         iim.getLatex(os, runparams);
715                         return;
716                 }
717         }
718 }
719
720
721 docstring InsetIndex::getSortkeyAsText(OutputParams const & runparams) const
722 {
723         Paragraph const & par = paragraphs().front();
724         InsetList::const_iterator it = par.insetList().begin();
725         for (; it != par.insetList().end(); ++it) {
726                 Inset & inset = *it->inset;
727                 if (inset.lyxCode() == INDEXMACRO_SORTKEY_CODE) {
728                         otexstringstream os;
729                         InsetIndexMacro const & iim =
730                                 static_cast<InsetIndexMacro const &>(inset);
731                         iim.getLatex(os, runparams);
732                         return os.str();
733                 }
734         }
735         return from_ascii("");
736 }
737
738
739 void InsetIndex::emptySubentriesWarning(docstring const & mainentry) const
740 {
741         // Empty subentries crash makeindex. So warn and ignore this.
742         TeXErrors terr;
743         ErrorList & errorList = buffer().errorList("Export");
744         docstring const s = bformat(_("There is an empty index subentry in the entry '%1$s'.\n"
745                                       "It will be ignored in the output."), mainentry);
746         Paragraph const & par = buffer().paragraphs().front();
747         errorList.push_back(ErrorItem(_("Empty index subentry!"), s,
748                                       {par.id(), 0}, {par.id(), -1}));
749         buffer().bufferErrors(terr, errorList);
750 }
751
752
753 void InsetIndex::getSubentries(otexstream & os, OutputParams const & runparams,
754                                docstring const & mainentry) const
755 {
756         Paragraph const & par = paragraphs().front();
757         InsetList::const_iterator it = par.insetList().begin();
758         int i = 0;
759         for (; it != par.insetList().end(); ++it) {
760                 Inset & inset = *it->inset;
761                 if (inset.lyxCode() == INDEXMACRO_CODE) {
762                         InsetIndexMacro const & iim =
763                                 static_cast<InsetIndexMacro const &>(inset);
764                         if (iim.params().type == InsetIndexMacroParams::Subentry) {
765                                 if (iim.hasNoContent()) {
766                                         emptySubentriesWarning(mainentry);
767                                         continue;
768                                 }
769                                 ++i;
770                                 if (i > 2)
771                                         return;
772                                 os << "!";
773                                 iim.getLatex(os, runparams);
774                         }
775                 }
776         }
777 }
778
779
780 std::vector<docstring> InsetIndex::getSubentriesAsText(OutputParams const & runparams,
781                                                        bool const asLabel) const
782 {
783         std::vector<docstring> subentries;
784
785         Paragraph const & par = paragraphs().front();
786         InsetList::const_iterator it = par.insetList().begin();
787         int i = 0;
788         for (; it != par.insetList().end(); ++it) {
789                 Inset & inset = *it->inset;
790                 if (inset.lyxCode() == INDEXMACRO_CODE) {
791                         InsetIndexMacro const & iim =
792                                 static_cast<InsetIndexMacro const &>(inset);
793                         if (iim.params().type == InsetIndexMacroParams::Subentry) {
794                                 ++i;
795                                 if (i > 2)
796                                         break;
797                                 if (asLabel) {
798                                         docstring const l;
799                                         docstring const sl = iim.getNewLabel(l);
800                                         subentries.emplace_back(sl);
801                                 } else {
802                                         otexstringstream os;
803                                         iim.getLatex(os, runparams);
804                                         subentries.emplace_back(os.str());
805                                 }
806                         }
807                 }
808         }
809
810         return subentries;
811 }
812
813
814 docstring InsetIndex::getMainSubentryAsText(OutputParams const & runparams) const
815 {
816         otexstringstream os;
817         InsetText::latex(os, runparams);
818         return os.str();
819 }
820
821
822 void InsetIndex::getSeeRefs(otexstream & os, OutputParams const & runparams) const
823 {
824         Paragraph const & par = paragraphs().front();
825         InsetList::const_iterator it = par.insetList().begin();
826         for (; it != par.insetList().end(); ++it) {
827                 Inset & inset = *it->inset;
828                 if (inset.lyxCode() == INDEXMACRO_CODE) {
829                         InsetIndexMacro const & iim =
830                                 static_cast<InsetIndexMacro const &>(inset);
831                         if (iim.params().type == InsetIndexMacroParams::See
832                             || iim.params().type == InsetIndexMacroParams::Seealso) {
833                                 iim.getLatex(os, runparams);
834                                 return;
835                         }
836                 }
837         }
838 }
839
840
841 docstring InsetIndex::getSeeAsText(OutputParams const & runparams,
842                                    bool const asLabel) const
843 {
844         Paragraph const & par = paragraphs().front();
845         InsetList::const_iterator it = par.insetList().begin();
846         for (; it != par.insetList().end(); ++it) {
847                 Inset & inset = *it->inset;
848                 if (inset.lyxCode() == INDEXMACRO_CODE) {
849                         InsetIndexMacro const & iim =
850                                 static_cast<InsetIndexMacro const &>(inset);
851                         if (iim.params().type == InsetIndexMacroParams::See) {
852                                 if (asLabel) {
853                                         docstring const l;
854                                         return iim.getNewLabel(l);
855                                 } else {
856                                         otexstringstream os;
857                                         iim.getLatex(os, runparams);
858                                         return os.str();
859                                 }
860                         }
861                 }
862         }
863         return from_ascii("");
864 }
865
866
867 std::vector<docstring> InsetIndex::getSeeAlsoesAsText(OutputParams const & runparams,
868                                                       bool const asLabel) const
869 {
870         std::vector<docstring> seeAlsoes;
871
872         Paragraph const & par = paragraphs().front();
873         InsetList::const_iterator it = par.insetList().begin();
874         for (; it != par.insetList().end(); ++it) {
875                 Inset & inset = *it->inset;
876                 if (inset.lyxCode() == INDEXMACRO_CODE) {
877                         InsetIndexMacro const & iim =
878                                 static_cast<InsetIndexMacro const &>(inset);
879                         if (iim.params().type == InsetIndexMacroParams::Seealso) {
880                                 if (asLabel) {
881                                         docstring const l;
882                                         seeAlsoes.emplace_back(iim.getNewLabel(l));
883                                 } else {
884                                         otexstringstream os;
885                                         iim.getLatex(os, runparams);
886                                         seeAlsoes.emplace_back(os.str());
887                                 }
888                         }
889                 }
890         }
891
892         return seeAlsoes;
893 }
894
895
896 namespace {
897
898 bool hasInsetWithCode(const InsetIndex * const inset_index, const InsetCode code,
899                                           const std::set<InsetIndexMacroParams::Type> types = {})
900 {
901         Paragraph const & par = inset_index->paragraphs().front();
902         InsetList::const_iterator it = par.insetList().begin();
903         for (; it != par.insetList().end(); ++it) {
904                 Inset & inset = *it->inset;
905                 if (inset.lyxCode() == code) {
906                         if (types.empty())
907                                 return true;
908
909                         LASSERT(code == INDEXMACRO_CODE, return false);
910                         InsetIndexMacro const & iim =
911                                         static_cast<InsetIndexMacro const &>(inset);
912                         if (types.find(iim.params().type) != types.end())
913                                 return true;
914                 }
915         }
916         return false;
917 }
918
919 } // namespace
920
921
922 bool InsetIndex::hasSubentries() const
923 {
924         return hasInsetWithCode(this, INDEXMACRO_CODE, {InsetIndexMacroParams::Subentry});
925 }
926
927
928 bool InsetIndex::hasSeeRef() const
929 {
930         return hasInsetWithCode(this, INDEXMACRO_CODE, {InsetIndexMacroParams::See, InsetIndexMacroParams::Seealso});
931 }
932
933
934 bool InsetIndex::hasSortKey() const
935 {
936         return hasInsetWithCode(this, INDEXMACRO_SORTKEY_CODE);
937 }
938
939
940 bool InsetIndex::macrosPossible(string const type) const
941 {
942         if (type != "see" && type != "seealso"
943             && type != "sortkey" && type != "subentry")
944                 return false;
945
946         Paragraph const & par = paragraphs().front();
947         InsetList::const_iterator it = par.insetList().begin();
948         int subidxs = 0;
949         for (; it != par.insetList().end(); ++it) {
950                 Inset & inset = *it->inset;
951                 if (type == "sortkey" && inset.lyxCode() == INDEXMACRO_SORTKEY_CODE)
952                         return false;
953                 if (inset.lyxCode() == INDEXMACRO_CODE) {
954                         InsetIndexMacro const & iim = static_cast<InsetIndexMacro const &>(inset);
955                         if ((type == "see" || type == "seealso")
956                              && (iim.params().type == InsetIndexMacroParams::See
957                                  || iim.params().type == InsetIndexMacroParams::Seealso))
958                                 return false;
959                         if (type == "subentry"
960                              && iim.params().type == InsetIndexMacroParams::Subentry) {
961                                 ++subidxs;
962                                 if (subidxs > 1)
963                                         return false;
964                         }
965                 }
966         }
967         return true;
968 }
969
970
971 ColorCode InsetIndex::labelColor() const
972 {
973         if (params_.index.empty() || params_.index == from_ascii("idx"))
974                 return InsetCollapsible::labelColor();
975         // FIXME UNICODE
976         ColorCode c = lcolor.getFromLyXName(to_utf8(params_.index)
977                                             + "@" + buffer().fileName().absFileName());
978         if (c == Color_none)
979                 c = InsetCollapsible::labelColor();
980         return c;
981 }
982
983
984 docstring InsetIndex::toolTip(BufferView const &, int, int) const
985 {
986         docstring tip = _("Index Entry");
987         if (buffer().params().use_indices && !params_.index.empty()) {
988                 Buffer const & realbuffer = *buffer().masterBuffer();
989                 IndicesList const & indiceslist = realbuffer.params().indiceslist();
990                 tip += " (";
991                 Index const * index = indiceslist.findShortcut(params_.index);
992                 if (!index)
993                         tip += _("unknown type!");
994                 else
995                         tip += index->index();
996                 tip += ")";
997         }
998         tip += ": ";
999         docstring res = toolTipText(tip);
1000         if (!insetindexpagerangetranslator_loc().find(params_.range).empty())
1001                 res += "\n" + insetindexpagerangetranslator_loc().find(params_.range);
1002         if (!params_.pagefmt.empty() && params_.pagefmt != "default") {
1003                 res += "\n" + _("Pagination format:") + " ";
1004                 if (params_.pagefmt == "textbf")
1005                         res += _("bold");
1006                 else if (params_.pagefmt == "textit")
1007                         res += _("italic");
1008                 else if (params_.pagefmt == "emph")
1009                         res += _("emphasized");
1010                 else
1011                         res += from_utf8(params_.pagefmt);
1012         }
1013         return res;
1014 }
1015
1016
1017 docstring const InsetIndex::buttonLabel(BufferView const & bv) const
1018 {
1019         InsetLayout const & il = getLayout();
1020         docstring label = translateIfPossible(il.labelstring());
1021
1022         if (buffer().params().use_indices && !params_.index.empty()) {
1023                 Buffer const & realbuffer = *buffer().masterBuffer();
1024                 IndicesList const & indiceslist = realbuffer.params().indiceslist();
1025                 label += " (";
1026                 Index const * index = indiceslist.findShortcut(params_.index);
1027                 if (!index)
1028                         label += _("unknown type!");
1029                 else
1030                         label += index->index();
1031                 label += ")";
1032         }
1033
1034         docstring res;
1035         if (!il.contentaslabel() || geometry(bv) != ButtonOnly)
1036                 res = label;
1037         else {
1038                 res = getNewLabel(label);
1039                 OutputParams const rp(0);
1040                 vector<docstring> sublbls = getSubentriesAsText(rp, true);
1041                 for (auto const & sublbl : sublbls) {
1042                         res += " " + docstring(1, char_type(0x2023));// TRIANGULAR BULLET
1043                         res += " " + sublbl;
1044                 }
1045                 docstring see = getSeeAsText(rp, true);
1046                 if (see.empty() && !getSeeAlsoesAsText(rp, true).empty())
1047                         see = getSeeAlsoesAsText(rp, true).front();
1048                 if (!see.empty()) {
1049                         res += " " + docstring(1, char_type(0x261e));// WHITE RIGHT POINTING INDEX
1050                         res += " " + see;
1051                 }
1052         }
1053         if (!insetindexpagerangetranslator_latex().find(params_.range).empty())
1054                 res += " " + from_ascii(insetindexpagerangetranslator_latex().find(params_.range));
1055         return res;
1056 }
1057
1058
1059 void InsetIndex::write(ostream & os) const
1060 {
1061         os << to_utf8(layoutName());
1062         params_.write(os);
1063         InsetCollapsible::write(os);
1064 }
1065
1066
1067 void InsetIndex::read(Lexer & lex)
1068 {
1069         params_.read(lex);
1070         InsetCollapsible::read(lex);
1071 }
1072
1073
1074 string InsetIndex::params2string(InsetIndexParams const & params)
1075 {
1076         ostringstream data;
1077         data << "index";
1078         params.write(data);
1079         return data.str();
1080 }
1081
1082
1083 void InsetIndex::string2params(string const & in, InsetIndexParams & params)
1084 {
1085         params = InsetIndexParams();
1086         if (in.empty())
1087                 return;
1088
1089         istringstream data(in);
1090         Lexer lex;
1091         lex.setStream(data);
1092         lex.setContext("InsetIndex::string2params");
1093         lex >> "index";
1094         params.read(lex);
1095 }
1096
1097
1098 void InsetIndex::addToToc(DocIterator const & cpit, bool output_active,
1099                                                   UpdateType utype, TocBackend & backend) const
1100 {
1101         DocIterator pit = cpit;
1102         pit.push_back(CursorSlice(const_cast<InsetIndex &>(*this)));
1103         docstring str;
1104         InsetLayout const & il = getLayout();
1105         docstring label = translateIfPossible(il.labelstring());
1106         if (!il.contentaslabel())
1107                 str = label;
1108         else {
1109                 str = getNewLabel(label);
1110                 OutputParams const rp(0);
1111                 vector<docstring> sublbls = getSubentriesAsText(rp, true);
1112                 for (auto const & sublbl : sublbls) {
1113                         str += " " + docstring(1, char_type(0x2023));// TRIANGULAR BULLET
1114                         str += " " + sublbl;
1115                 }
1116                 docstring see = getSeeAsText(rp, true);
1117                 if (see.empty() && !getSeeAlsoesAsText(rp, true).empty())
1118                         see = getSeeAlsoesAsText(rp, true).front();
1119                 if (!see.empty()) {
1120                         str += " " + docstring(1, char_type(0x261e));// WHITE RIGHT POINTING INDEX
1121                         str += " " + see;
1122                 }
1123         }
1124         string type = "index";
1125         if (buffer().masterBuffer()->params().use_indices)
1126                 type += ":" + to_utf8(params_.index);
1127         TocBuilder & b = backend.builder(type);
1128         b.pushItem(pit, str, output_active);
1129         // Proceed with the rest of the inset.
1130         InsetCollapsible::addToToc(cpit, output_active, utype, backend);
1131         b.pop();
1132 }
1133
1134
1135 void InsetIndex::validate(LaTeXFeatures & features) const
1136 {
1137         if (buffer().masterBuffer()->params().use_indices
1138             && !params_.index.empty()
1139             && params_.index != "idx")
1140                 features.require("splitidx");
1141         InsetCollapsible::validate(features);
1142 }
1143
1144
1145 string InsetIndex::contextMenuName() const
1146 {
1147         return "context-index";
1148 }
1149
1150
1151 string InsetIndex::contextMenu(BufferView const & bv, int x, int y) const
1152 {
1153         // We override the implementation of InsetCollapsible,
1154         // because we have eytra entries.
1155         string owncm = "context-edit-index;";
1156         return owncm + InsetCollapsible::contextMenu(bv, x, y);
1157 }
1158
1159
1160 bool InsetIndex::hasSettings() const
1161 {
1162         return true;
1163 }
1164
1165
1166 bool InsetIndex::insetAllowed(InsetCode code) const
1167 {
1168         switch (code) {
1169         case INDEXMACRO_CODE:
1170         case INDEXMACRO_SORTKEY_CODE:
1171                 return true;
1172         case INDEX_CODE:
1173                 return false;
1174         default:
1175                 return InsetCollapsible::insetAllowed(code);
1176         }
1177 }
1178
1179
1180 /////////////////////////////////////////////////////////////////////
1181 //
1182 // InsetIndexParams
1183 //
1184 ///////////////////////////////////////////////////////////////////////
1185
1186
1187 void InsetIndexParams::write(ostream & os) const
1188 {
1189         os << ' ';
1190         if (!index.empty())
1191                 os << to_utf8(index);
1192         else
1193                 os << "idx";
1194         os << '\n';
1195         os << "range "
1196            << insetindexpagerangetranslator().find(range)
1197            << '\n';
1198         os << "pageformat "
1199            << pagefmt
1200            << '\n';
1201 }
1202
1203
1204 void InsetIndexParams::read(Lexer & lex)
1205 {
1206         if (lex.eatLine())
1207                 index = lex.getDocString();
1208         else
1209                 index = from_ascii("idx");
1210         if (lex.checkFor("range")) {
1211                 string st = lex.getString();
1212                 if (lex.eatLine()) {
1213                         st = lex.getString();
1214                         range = insetindexpagerangetranslator().find(lex.getString());
1215                 }
1216         }
1217         if (lex.checkFor("pageformat") && lex.eatLine()) {
1218                 pagefmt = lex.getString();
1219         }
1220 }
1221
1222
1223 /////////////////////////////////////////////////////////////////////
1224 //
1225 // InsetPrintIndex
1226 //
1227 ///////////////////////////////////////////////////////////////////////
1228
1229 InsetPrintIndex::InsetPrintIndex(Buffer * buf, InsetCommandParams const & p)
1230         : InsetCommand(buf, p)
1231 {}
1232
1233
1234 ParamInfo const & InsetPrintIndex::findInfo(string const & /* cmdName */)
1235 {
1236         static ParamInfo param_info_;
1237         if (param_info_.empty()) {
1238                 param_info_.add("type", ParamInfo::LATEX_OPTIONAL,
1239                                 ParamInfo::HANDLING_ESCAPE);
1240                 param_info_.add("name", ParamInfo::LATEX_OPTIONAL,
1241                                 ParamInfo::HANDLING_LATEXIFY);
1242                 param_info_.add("literal", ParamInfo::LYX_INTERNAL);
1243         }
1244         return param_info_;
1245 }
1246
1247
1248 docstring InsetPrintIndex::screenLabel() const
1249 {
1250         bool const printall = suffixIs(getCmdName(), '*');
1251         bool const multind = buffer().masterBuffer()->params().use_indices;
1252         if ((!multind
1253              && getParam("type") == from_ascii("idx"))
1254             || (getParam("type").empty() && !printall))
1255                 return _("Index");
1256         Buffer const & realbuffer = *buffer().masterBuffer();
1257         IndicesList const & indiceslist = realbuffer.params().indiceslist();
1258         Index const * index = indiceslist.findShortcut(getParam("type"));
1259         if (!index && !printall)
1260                 return _("Unknown index type!");
1261         docstring res = printall ? _("All indexes") : index->index();
1262         if (!multind)
1263                 res += " (" + _("non-active") + ")";
1264         else if (contains(getCmdName(), "printsubindex"))
1265                 res += " (" + _("subindex") + ")";
1266         return res;
1267 }
1268
1269
1270 bool InsetPrintIndex::isCompatibleCommand(string const & s)
1271 {
1272         return s == "printindex" || s == "printsubindex"
1273                 || s == "printindex*" || s == "printsubindex*";
1274 }
1275
1276
1277 void InsetPrintIndex::doDispatch(Cursor & cur, FuncRequest & cmd)
1278 {
1279         switch (cmd.action()) {
1280
1281         case LFUN_INSET_MODIFY: {
1282                 if (cmd.argument() == from_ascii("toggle-subindex")) {
1283                         string scmd = getCmdName();
1284                         if (contains(scmd, "printindex"))
1285                                 scmd = subst(scmd, "printindex", "printsubindex");
1286                         else
1287                                 scmd = subst(scmd, "printsubindex", "printindex");
1288                         cur.recordUndo();
1289                         setCmdName(scmd);
1290                         break;
1291                 } else if (cmd.argument() == from_ascii("check-printindex*")) {
1292                         string scmd = getCmdName();
1293                         if (suffixIs(scmd, '*'))
1294                                 break;
1295                         scmd += '*';
1296                         cur.recordUndo();
1297                         setParam("type", docstring());
1298                         setCmdName(scmd);
1299                         break;
1300                 }
1301                 InsetCommandParams p(INDEX_PRINT_CODE);
1302                 // FIXME UNICODE
1303                 InsetCommand::string2params(to_utf8(cmd.argument()), p);
1304                 if (p.getCmdName().empty()) {
1305                         cur.noScreenUpdate();
1306                         break;
1307                 }
1308                 cur.recordUndo();
1309                 setParams(p);
1310                 break;
1311         }
1312
1313         default:
1314                 InsetCommand::doDispatch(cur, cmd);
1315                 break;
1316         }
1317 }
1318
1319
1320 bool InsetPrintIndex::getStatus(Cursor & cur, FuncRequest const & cmd,
1321         FuncStatus & status) const
1322 {
1323         switch (cmd.action()) {
1324
1325         case LFUN_INSET_MODIFY: {
1326                 if (cmd.argument() == from_ascii("toggle-subindex")) {
1327                         status.setEnabled(buffer().masterBuffer()->params().use_indices);
1328                         status.setOnOff(contains(getCmdName(), "printsubindex"));
1329                         return true;
1330                 } else if (cmd.argument() == from_ascii("check-printindex*")) {
1331                         status.setEnabled(buffer().masterBuffer()->params().use_indices);
1332                         status.setOnOff(suffixIs(getCmdName(), '*'));
1333                         return true;
1334                 } if (cmd.getArg(0) == "index_print"
1335                     && cmd.getArg(1) == "CommandInset") {
1336                         InsetCommandParams p(INDEX_PRINT_CODE);
1337                         InsetCommand::string2params(to_utf8(cmd.argument()), p);
1338                         if (suffixIs(p.getCmdName(), '*')) {
1339                                 status.setEnabled(true);
1340                                 status.setOnOff(false);
1341                                 return true;
1342                         }
1343                         Buffer const & realbuffer = *buffer().masterBuffer();
1344                         IndicesList const & indiceslist =
1345                                 realbuffer.params().indiceslist();
1346                         Index const * index = indiceslist.findShortcut(p["type"]);
1347                         status.setEnabled(index != 0);
1348                         status.setOnOff(p["type"] == getParam("type"));
1349                         return true;
1350                 } else
1351                         return InsetCommand::getStatus(cur, cmd, status);
1352         }
1353
1354         case LFUN_INSET_DIALOG_UPDATE: {
1355                 status.setEnabled(buffer().masterBuffer()->params().use_indices);
1356                 return true;
1357         }
1358
1359         default:
1360                 return InsetCommand::getStatus(cur, cmd, status);
1361         }
1362 }
1363
1364
1365 void InsetPrintIndex::updateBuffer(ParIterator const &, UpdateType, bool const /*deleted*/)
1366 {
1367         Index const * index =
1368                 buffer().masterParams().indiceslist().findShortcut(getParam("type"));
1369         if (index)
1370                 setParam("name", index->index());
1371 }
1372
1373
1374 void InsetPrintIndex::latex(otexstream & os, OutputParams const & runparams_in) const
1375 {
1376         if (!buffer().masterBuffer()->params().use_indices) {
1377                 if (getParam("type") == from_ascii("idx"))
1378                         os << "\\printindex" << termcmd;
1379                 return;
1380         }
1381         OutputParams runparams = runparams_in;
1382         os << getCommand(runparams);
1383 }
1384
1385
1386 void InsetPrintIndex::validate(LaTeXFeatures & features) const
1387 {
1388         features.require("makeidx");
1389         if (buffer().masterBuffer()->params().use_indices)
1390                 features.require("splitidx");
1391         InsetCommand::validate(features);
1392 }
1393
1394
1395 string InsetPrintIndex::contextMenuName() const
1396 {
1397         return buffer().masterBuffer()->params().use_indices ?
1398                 "context-indexprint" : string();
1399 }
1400
1401
1402 bool InsetPrintIndex::hasSettings() const
1403 {
1404         return buffer().masterBuffer()->params().use_indices;
1405 }
1406
1407
1408 class IndexEntry
1409 {
1410 public:
1411         /// Builds an entry for the index.
1412         IndexEntry(const InsetIndex * inset, OutputParams const * runparams) : inset_(inset), runparams_(runparams)
1413         {
1414                 LASSERT(runparams, return);
1415
1416                 // Convert the inset as text. The resulting text usually only contains an XHTML anchor (<a id='...'/>) and text.
1417                 odocstringstream entry;
1418                 OutputParams ours = *runparams;
1419                 ours.for_toc = false;
1420                 inset_->plaintext(entry, ours);
1421                 entry_ = entry.str();
1422
1423                 // Determine in which index this entry belongs to.
1424                 if (inset_->buffer().masterBuffer()->params().use_indices) {
1425                         index_ = inset_->params_.index;
1426                 }
1427
1428                 // Attempt parsing the inset.
1429                 if (isModern())
1430                         parseAsModern();
1431                 else
1432                         parseAsLegacy();
1433         }
1434
1435         /// When parsing this entry, some errors may be found; they are reported as a single string.
1436         // It is up to the caller to send this string to LYXERR and the output file, as needed.
1437         const docstring & output_error() const
1438         {
1439                 return output_error_;
1440         }
1441
1442         void output_error(XMLStream xs) const
1443         {
1444                 LYXERR0(output_error());
1445                 xs << XMLStream::ESCAPE_NONE << (from_utf8("<!-- Output Error: ") + output_error() + from_utf8(" -->\n"));
1446         }
1447
1448
1449 private:
1450         bool isModern()
1451         {
1452 #ifdef LYX_INSET_INDEX_DEBUG
1453                 std::cout << to_utf8(entry_) << std::endl;
1454 #endif // LYX_INSET_INDEX_DEBUG
1455
1456                 // If a modern parameter is present, this is definitely a modern index inset. Similarly, if it contains the
1457                 // usual LaTeX symbols (!|@), then it is definitely a legacy index inset. Otherwise, if it has features of
1458                 // neither, it is both: consider this is a modern inset, to trigger the least complex code. Mixing both types
1459                 // is not allowed (i.e. behaviour is undefined).
1460                 const bool is_definitely_modern = inset_->hasSortKey() || inset_->hasSeeRef() || inset_->hasSubentries()
1461                                             || inset_->params_.range != InsetIndexParams::PageRange::None;
1462                 const bool is_definitely_legacy = entry_.find('@') != std::string::npos
1463                                 || entry_.find('|') != std::string::npos || entry_.find('!') != std::string::npos;
1464
1465                 if (is_definitely_legacy && is_definitely_modern)
1466                         output_error_ += from_utf8("Mix of index properties and raw LaTeX index commands is unsupported. ");
1467
1468                 // Truth table:
1469                 // - is_definitely_modern == true:
1470                 //   - is_definitely_legacy == true: error (return whatever)
1471                 //   - is_definitely_legacy == false: return modern
1472                 // - is_definitely_modern == false:
1473                 //   - is_definitely_legacy == true: return legacy
1474                 //   - is_definitely_legacy == false: return modern
1475                 return !is_definitely_legacy;
1476         }
1477
1478         void parseAsModern()
1479         {
1480                 LASSERT(runparams_, return);
1481
1482                 if (inset_->hasSortKey()) {
1483                         sort_as_ = inset_->getSortkeyAsText(*runparams_);
1484                 }
1485
1486                 terms_ = inset_->getSubentriesAsText(*runparams_);
1487                 // The main term is not present in the vector, as it's not a subentry. The main index term is inserted raw in
1488                 // the index inset. Considering that the user either uses the new or the legacy mechanism, the main term is the
1489                 // full string within this inset (i.e. without the subinsets).
1490                 terms_.insert(terms_.begin(), inset_->getMainSubentryAsText(*runparams_));
1491
1492                 has_start_range_ = inset_->params_.range == InsetIndexParams::PageRange::Start;
1493                 has_end_range_ = inset_->params_.range == InsetIndexParams::PageRange::End;
1494
1495                 see_ = inset_->getSeeAsText(*runparams_);
1496                 see_alsoes_ = inset_->getSeeAlsoesAsText(*runparams_);
1497         }
1498
1499         void parseAsLegacy() {
1500                 // Determine if some features are known not to be supported. For now, this is only formatting like
1501                 // \index{alpha@\textbf{alpha}} or \index{alpha@$\alpha$}.
1502                 // @ is supported, but only for sorting, without specific formatting.
1503                 if (entry_.find(from_utf8("@\\")) != lyx::docstring::npos) {
1504                         output_error_ += from_utf8("Unsupported feature: an index entry contains an @\\. "
1505                                                    "Complete entry: \"") + entry_ + from_utf8("\". ");
1506                 }
1507                 if (entry_.find(from_utf8("@$")) != lyx::docstring::npos) {
1508                         output_error_ += from_utf8("Unsupported feature: an index entry contains an @$. "
1509                                                    "Complete entry: \"") + entry_ + from_utf8("\". ");
1510                 }
1511
1512                 // Split the string into its main constituents: terms, and command (see, see also, range).
1513                 size_t positionVerticalBar = entry_.find(from_ascii("|")); // What comes before | is (sub)(sub)entries.
1514                 docstring indexTerms = entry_.substr(0, positionVerticalBar);
1515                 docstring command;
1516                 if (positionVerticalBar != lyx::docstring::npos) {
1517                         command = entry_.substr(positionVerticalBar + 1);
1518                 }
1519
1520                 // Handle sorting issues, with @.
1521                 vector<docstring> sortingElements = getVectorFromString(indexTerms, from_ascii("@"), false);
1522                 if (sortingElements.size() == 2) {
1523                         sort_as_ = sortingElements[0];
1524                         indexTerms = sortingElements[1];
1525                 }
1526
1527                 // Handle entries, subentries, and subsubentries.
1528                 terms_ = getVectorFromString(indexTerms, from_ascii("!"), false);
1529
1530                 // Handle ranges. Happily, (| and |) can only be at the end of the string!
1531                 has_start_range_ = entry_.find(from_ascii("|(")) != lyx::docstring::npos;
1532                 has_end_range_ = entry_.find(from_ascii("|)")) != lyx::docstring::npos;
1533
1534                 // - Remove the ranges from the command if they do not appear at the beginning.
1535                 size_t range_index = 0;
1536                 while ((range_index = command.find(from_utf8("|("), range_index)) != std::string::npos)
1537                         command.erase(range_index, 1);
1538                 range_index = 0;
1539                 while ((range_index = command.find(from_utf8("|)"), range_index)) != std::string::npos)
1540                         command.erase(range_index, 1);
1541
1542                 // - Remove the ranges when they are the only vertical bar in the complete string.
1543                 if (command[0] == '(' || command[0] == ')')
1544                         command.erase(0, 1);
1545
1546                 // Handle see and seealso. As "see" is a prefix of "seealso", the order of the comparisons is important.
1547                 // Both commands are mutually exclusive!
1548                 if (command.substr(0, 3) == "see") {
1549                         // Unescape brackets.
1550                         size_t index_argument_begin = 0;
1551                         while ((index_argument_begin = command.find(from_utf8("\\{"), index_argument_begin)) != std::string::npos)
1552                                 command.erase(index_argument_begin, 1);
1553                         size_t index_argument_end = 0;
1554                         while ((index_argument_end = command.find(from_utf8("\\}"), index_argument_end)) != std::string::npos)
1555                                 command.erase(index_argument_end, 1);
1556
1557                         // Retrieve the part between brackets, and remove the complete seealso.
1558                         size_t position_opening_bracket = command.find(from_ascii("{"));
1559                         size_t position_closing_bracket = command.find(from_ascii("}"));
1560                         docstring argument = command.substr(position_opening_bracket + 1,
1561                                                                                                 position_closing_bracket - position_opening_bracket - 1);
1562
1563                         // Parse the argument of referenced entries (or a single one for see).
1564                         if (command.substr(0, 7) == "seealso") {
1565                                 see_alsoes_ = getVectorFromString(argument, from_ascii(","), false);
1566                         } else {
1567                                 see_ = argument;
1568
1569                                 if (see_.find(from_ascii(",")) != std::string::npos) {
1570                                         output_error_ += from_utf8("Several index_argument_end terms found as \"see\"! Only one is "
1571                                                                    "acceptable. Complete entry: \"") + entry_ + from_utf8("\". ");
1572                                 }
1573                         }
1574
1575                         // Remove the complete see/seealso from the commands, in case there is something else to parse.
1576                         command = command.substr(position_closing_bracket + 1);
1577                 }
1578
1579                 // Some parts of the strings are not parsed, as they do not have anything matching in DocBook or XHTML:
1580                 // things like formatting the entry or the page number, other strings for sorting.
1581                 // https://wiki.lyx.org/Tips/Indexing
1582                 // If there are such things in the index entry, then this code may miserably fail. For example, for
1583                 // "Peter|(textbf", no range will be detected.
1584                 if (!command.empty()) {
1585                         output_error_ += from_utf8("Unsupported feature: an index entry contains a | with an unsupported command, ")
1586                                          + command + from_utf8(". Complete entry: \"") + entry_ + from_utf8("\". ");
1587                 }
1588         }
1589
1590 public:
1591         int level() const {
1592                 return terms_.size();
1593         }
1594
1595         const std::vector<docstring>& terms() const {
1596                 return terms_;
1597         }
1598
1599         std::vector<docstring>& terms() {
1600                 return terms_;
1601         }
1602
1603         const InsetIndex* inset() const {
1604                 return inset_;
1605         }
1606
1607 private:
1608         // Input inset. These should only be used when parsing the inset (either parseAsModern or parseAsLegacy, called in
1609         // the constructor).
1610         const InsetIndex * inset_;
1611         OutputParams const * runparams_;
1612         docstring entry_;
1613         docstring index_; // Useful when there are multiple indices in the same document.
1614
1615         // Errors, concatenated as a single string, available as soon as parsing is done, const afterwards (i.e. once
1616         // constructor is done).
1617         docstring output_error_;
1618
1619         // Parsed index entry.
1620         std::vector<docstring> terms_; // Up to three entries, in general.
1621         docstring sort_as_;
1622         docstring command_;
1623         bool has_start_range_;
1624         bool has_end_range_;
1625         docstring see_;
1626         vector<docstring> see_alsoes_;
1627
1628         // Operators used for sorting entries (alphabetical order).
1629         friend bool operator<(IndexEntry const & lhs, IndexEntry const & rhs);
1630 };
1631
1632 bool operator<(IndexEntry const & lhs, IndexEntry const & rhs)
1633 {
1634         if (lhs.terms_.empty())
1635                 return false;
1636
1637         for (unsigned i = 0; i < min(rhs.terms_.size(), lhs.terms_.size()); ++i) {
1638                 int comp = compare_no_case(lhs.terms_[i], rhs.terms_[i]);
1639                 if (comp != 0)
1640                         return comp < 0;
1641         }
1642         return false;
1643 }
1644
1645
1646 namespace {
1647 std::string generateCssClassAtDepth(unsigned depth) {
1648         std::string css_class = "entry";
1649
1650         while (depth > 0) {
1651                 depth -= 1;
1652                 css_class.insert(0, "sub");
1653         }
1654
1655         return css_class;
1656 }
1657
1658 struct IndexNode {
1659         std::vector<IndexEntry> entries;
1660         std::vector<IndexNode*> children;
1661 };
1662
1663 docstring termAtLevel(const IndexNode* node, unsigned depth)
1664 {
1665         // The typical entry has a depth of 1 to 3: the call stack would then be at most 4 (due to the root node). This
1666         // function could be made constant time by copying the term in each node, but that would make data duplication that
1667         // may fall out of sync; the performance benefit would probably be negligible.
1668         if (!node->entries.empty()) {
1669                 LASSERT(node->entries.begin()->terms().size() >= depth + 1, return from_ascii(""));
1670                 return node->entries.begin()->terms()[depth];
1671         }
1672
1673         if (!node->children.empty()) {
1674                 return termAtLevel(*node->children.begin(), depth);
1675         }
1676
1677         LASSERT(false, return from_ascii(""));
1678 }
1679
1680 void insertIntoNode(const IndexEntry& entry, IndexNode* node, unsigned depth = 0)
1681 {
1682         // Do not insert empty entries.
1683         if (entry.terms().empty())
1684                 return;
1685
1686         // depth == 0 is for the root, not yet the index, hence the increase when going to vector size.
1687         for (IndexNode* child : node->children) {
1688                 if (entry.terms()[depth] == termAtLevel(child, depth)) {
1689                         if (depth + 1 == entry.terms().size()) { // == child.entries.begin()->terms().size()
1690                                 // All term entries match: it's an entry.
1691                                 if (!entry.terms()[depth].empty())
1692                                         child->entries.emplace_back(entry);
1693                                 return;
1694                         } else {
1695                                 insertIntoNode(entry, child, depth + 1);
1696                                 return;
1697                         }
1698                 }
1699         }
1700
1701         // Out of the loop: no matching child found, create a new (possibly nested) child for this entry. Due to the
1702         // possibility of nestedness, only insert the current entry when the right level is reached. This is needed if the
1703         // first entry for a word has several levels that never appeared.
1704         // In particular, this case is called for the first entry.
1705         IndexNode* new_node = node;
1706         do {
1707                 new_node->children.emplace_back(new IndexNode{{}, {}});
1708                 new_node = new_node->children.back();
1709                 depth += 1;
1710         } while (depth + 1 <= entry.terms().size()); // depth == 0: root node, no text associated.
1711         new_node->entries.emplace_back(entry);
1712 }
1713
1714 IndexNode* buildIndexTree(vector<IndexEntry>& entries)
1715 {
1716         // Sort the entries, first on the main entry, then the subentry, then the subsubentry,
1717         // thanks to the implementation of operator<.
1718         // If this operation is not performed, the algorithm below is no more correct (and ensuring that it works with
1719         // unsorted entries would make its complexity blow up).
1720         stable_sort(entries.begin(), entries.end());
1721
1722         // Cook the index into a nice tree data structure: entries at a given level in the index as a node, with subentries
1723         // as children.
1724         auto* index_root = new IndexNode{{}, {}};
1725         for (const IndexEntry& entry : entries) {
1726                 std::cout << "Entry: " << std::endl;
1727                 std::cout << entry.terms().empty() << std::endl;
1728                 std::cout << entry.terms().size() << std::endl;
1729                 for (const docstring& d : entry.terms()) {
1730                         std::cout << "\"" << to_utf8(d) << "\"" << std::endl;
1731                 }
1732                 insertIntoNode(entry, index_root);
1733         }
1734
1735         return index_root;
1736 }
1737
1738 void outputIndexPage(XMLStream & xs, const IndexNode* root_node, unsigned depth = 0) // NOLINT(misc-no-recursion)
1739 {
1740         LASSERT(root_node->entries.size() + root_node->children.size() > 0, return);
1741
1742         xs << xml::StartTag("li", "class='" + generateCssClassAtDepth(depth) + "'");
1743         xs << xml::CR();
1744         xs << termAtLevel(root_node, depth);
1745         // By tree assumption, all the entries at this node have the same set of terms.
1746
1747         if (!root_node->entries.empty()) {
1748                 xs << XMLStream::ESCAPE_NONE << " &#8212; "; // Em dash, i.e. long (---).
1749                 unsigned entry_number = 1;
1750
1751                 auto writeLinkToEntry = [&xs](const IndexEntry &entry, unsigned entry_number) {
1752                         std::string const link_attr = "href='#" + entry.inset()->paragraphs()[0].magicLabel() + "'";
1753                         xs << xml::StartTag("a", link_attr);
1754                         xs << from_ascii(std::to_string(entry_number));
1755                         xs << xml::EndTag("a");
1756                 };
1757
1758                 for (unsigned i = 0; i < root_node->entries.size(); ++i) {
1759                         const IndexEntry &entry = root_node->entries[i];
1760
1761                         switch (entry.inset()->params().range) {
1762                                 case InsetIndexParams::PageRange::None:
1763                                         writeLinkToEntry(entry, entry_number);
1764                                         break;
1765                                 case InsetIndexParams::PageRange::Start: {
1766                                         // Try to find the end of the range, if it is just after. Otherwise, the output will be slightly
1767                                         // scrambled, but understandable. Doing better would mean implementing more of the indexing logic here
1768                                         // and more complex indexing here (skipping the end is not just incrementing i). Worst case output:
1769                                         //     1--, 2, --3
1770                                         const bool nextEntryIsEnd = i + 1 < root_node->entries.size() &&
1771                                                                     root_node->entries[i + 1].inset()->params().range ==
1772                                                                     InsetIndexParams::PageRange::End;
1773                                         // No need to check if both entries are for the same terms: they are in the same IndexNode.
1774
1775                                         writeLinkToEntry(entry, entry_number);
1776                                         xs << XMLStream::ESCAPE_NONE << " &#8211; "; // En dash, i.e. semi-long (--).
1777
1778                                         if (nextEntryIsEnd) {
1779                                                 // Skip the next entry in the loop, write it right now, after the dash.
1780                                                 entry_number += 1;
1781                                                 i += 1;
1782                                                 writeLinkToEntry(root_node->entries[i], entry_number);
1783                                         }
1784                                 }
1785                                         break;
1786                                 case InsetIndexParams::PageRange::End:
1787                                         // This range end was not caught by the range start, do it now to avoid losing content.
1788                                         xs << XMLStream::ESCAPE_NONE << " &#8211; "; // En dash, i.e. semi-long (--).
1789                                         writeLinkToEntry(root_node->entries[i], entry_number);
1790                         }
1791
1792                         if (i < root_node->entries.size() - 1) {
1793                                 xs << ", ";
1794                         }
1795                         entry_number += 1;
1796                 }
1797                 xs << xml::CR();
1798         }
1799
1800         if (!root_node->entries.empty() && !root_node->children.empty()) {
1801                 xs << xml::CR();
1802         }
1803
1804         if (!root_node->children.empty()) {
1805                 xs << xml::StartTag("ul", "class='" + generateCssClassAtDepth(depth) + "'");
1806                 xs << xml::CR();
1807
1808                 for (const IndexNode* child : root_node->children) {
1809                         outputIndexPage(xs, child, depth + 1);
1810                 }
1811
1812                 xs << xml::EndTag("ul");
1813                 xs << xml::CR();
1814         }
1815
1816         xs << xml::EndTag("li");
1817         xs << xml::CR();
1818 }
1819
1820 #ifdef LYX_INSET_INDEX_DEBUG
1821 void printTree(const IndexNode* root_node, unsigned depth = 0)
1822 {
1823         static const std::string pattern = "    ";
1824         std::string prefix;
1825         for (unsigned i = 0; i < depth; ++i) {
1826                 prefix += pattern;
1827         }
1828         const std::string prefix_long = prefix + pattern + pattern;
1829
1830         docstring term_at_level;
1831         if (depth == 0) {
1832                 // The root has no term.
1833                 std::cout << "<ROOT>" << std::endl;
1834         } else {
1835                 LASSERT(depth - 1 <= 10, return); // Check for overflows.
1836                 term_at_level = termAtLevel(root_node, depth - 1);
1837                 std::cout << prefix << to_utf8(term_at_level) << " (x " << std::to_string(root_node->entries.size()) << ")"
1838                           << std::endl;
1839         }
1840
1841         for (const IndexEntry& entry : root_node->entries) {
1842                 if (entry.terms().size() != depth) {
1843                         std::cout << prefix_long << "ERROR: an entry doesn't have the same number of terms" << std::endl;
1844                 }
1845                 if (depth > 0 && entry.terms()[depth - 1] != term_at_level) {
1846                         std::cout << prefix_long << "ERROR: an entry doesn't have the right term at depth " << std::to_string(depth)
1847                                 << std::endl;
1848                 }
1849         }
1850
1851         for (const IndexNode* node : root_node->children) {
1852                 printTree(node, depth + 1);
1853         }
1854 }
1855 #endif // LYX_INSET_INDEX_DEBUG
1856 }
1857
1858
1859 docstring InsetPrintIndex::xhtml(XMLStream &, OutputParams const & op) const
1860 {
1861         BufferParams const & bp = buffer().masterBuffer()->params();
1862
1863         shared_ptr<Toc const> toc = buffer().tocBackend().toc("index");
1864         if (toc->empty())
1865                 return docstring();
1866
1867         // Collect the index entries in a form we can use them.
1868         vector<IndexEntry> entries;
1869         const docstring & indexType = params().getParamOr("type", from_ascii("idx"));
1870         for (const TocItem& item : *toc) {
1871                 const auto* inset = static_cast<const InsetIndex*>(&(item.dit().inset()));
1872                 if (item.isOutput() && inset->params().index == indexType)
1873                         entries.emplace_back(IndexEntry{inset, &op});
1874         }
1875
1876         // If all the index entries are in notes or not displayed, get out sooner.
1877         if (entries.empty())
1878                 return docstring();
1879
1880         const IndexNode* index_root = buildIndexTree(entries);
1881 #ifdef LYX_INSET_INDEX_DEBUG
1882         printTree(index_root);
1883 #endif
1884
1885         // Start generating the XHTML index.
1886         Layout const & lay = bp.documentClass().htmlTOCLayout();
1887         string const & tocclass = lay.defaultCSSClass();
1888         string const tocattr = "class='index " + tocclass + "'";
1889         docstring const indexName = params().getParamOr("name", from_ascii("Index"));
1890
1891         // we'll use our own stream, because we are going to defer everything.
1892         // that's how we deal with the fact that we're probably inside a standard
1893         // paragraph, and we don't want to be.
1894         odocstringstream ods;
1895         XMLStream xs(ods);
1896
1897         xs << xml::StartTag("div", tocattr);
1898         xs << xml::CR();
1899         xs << xml::StartTag(lay.htmltag(), lay.htmlattr());
1900         xs << translateIfPossible(indexName, op.local_font->language()->lang());
1901         xs << xml::EndTag(lay.htmltag());
1902         xs << xml::CR();
1903         xs << xml::StartTag("ul", "class='main'");
1904         xs << xml::CR();
1905
1906         LASSERT(index_root->entries.empty(), return docstring()); // No index entry should have zero terms.
1907         for (const IndexNode* node : index_root->children) {
1908                 outputIndexPage(xs, node);
1909         }
1910
1911         xs << xml::EndTag("ul");
1912         xs << xml::CR();
1913         xs << xml::EndTag("div");
1914
1915         return ods.str();
1916 }
1917
1918 } // namespace lyx