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