3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
7 * \author Jürgen Spitzmüller
9 * Full author contact details are available in file CREDITS.
13 #include "InsetIndex.h"
14 #include "InsetIndexMacro.h"
17 #include "BufferParams.h"
18 #include "BufferView.h"
21 #include "DispatchResult.h"
23 #include "ErrorList.h"
24 #include "FuncRequest.h"
25 #include "FuncStatus.h"
26 #include "IndicesList.h"
27 #include "InsetList.h"
30 #include "LaTeXFeatures.h"
33 #include "output_latex.h"
34 #include "output_xhtml.h"
36 #include "texstream.h"
37 #include "TextClass.h"
38 #include "TocBackend.h"
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"
47 #include "frontends/alert.h"
53 #include <QThreadStorage>
56 using namespace lyx::support;
58 // Uncomment to enable InsetIndex-specific debugging mode: the tree for the index will be printed to std::cout.
59 // #define LYX_INSET_INDEX_DEBUG
65 typedef Translator<string, InsetIndexParams::PageRange> PageRangeTranslator;
66 typedef Translator<docstring, InsetIndexParams::PageRange> PageRangeTranslatorLoc;
68 PageRangeTranslator const init_insetindexpagerangetranslator()
70 PageRangeTranslator translator("none", InsetIndexParams::None);
71 translator.addPair("start", InsetIndexParams::Start);
72 translator.addPair("end", InsetIndexParams::End);
76 PageRangeTranslator const init_insetindexpagerangetranslator_latex()
78 PageRangeTranslator translator("", InsetIndexParams::None);
79 translator.addPair("(", InsetIndexParams::Start);
80 translator.addPair(")", InsetIndexParams::End);
85 PageRangeTranslatorLoc const init_insetindexpagerangetranslator_loc()
87 PageRangeTranslatorLoc translator(docstring(), InsetIndexParams::None);
88 translator.addPair(_("Starts page range"), InsetIndexParams::Start);
89 translator.addPair(_("Ends page range"), InsetIndexParams::End);
94 PageRangeTranslator const & insetindexpagerangetranslator()
96 static PageRangeTranslator const prtranslator =
97 init_insetindexpagerangetranslator();
102 PageRangeTranslatorLoc const & insetindexpagerangetranslator_loc()
104 static PageRangeTranslatorLoc const translator =
105 init_insetindexpagerangetranslator_loc();
110 PageRangeTranslator const & insetindexpagerangetranslator_latex()
112 static PageRangeTranslator const lttranslator =
113 init_insetindexpagerangetranslator_latex();
119 /////////////////////////////////////////////////////////////////////
123 ///////////////////////////////////////////////////////////////////////
126 InsetIndex::InsetIndex(Buffer * buf, InsetIndexParams const & params)
127 : InsetCollapsible(buf), params_(params)
131 void InsetIndex::latex(otexstream & ios, OutputParams const & runparams_in) const
133 OutputParams runparams(runparams_in);
134 runparams.inIndexEntry = true;
135 if (runparams_in.postpone_fragile_stuff)
136 // This is not needed and would impact sorting
137 runparams.moving_arg = false;
141 if (buffer().masterBuffer()->params().use_indices && !params_.index.empty()
142 && params_.index != "idx") {
144 os << escape(params_.index);
151 // Get the LaTeX output from InsetText. We need to deconstruct this later
152 // in order to check if we need to generate a sorting key
153 odocstringstream ourlatex;
154 otexstream ots(ourlatex);
155 InsetText::latex(ots, runparams);
156 if (runparams.find_effective()) {
157 // No need for special handling, if we are only searching for some patterns
158 os << ourlatex.str() << "}";
163 getSortkey(os, runparams);
165 os << ourlatex.str();
166 getSubentries(os, runparams, ourlatex.str());
169 os << insetindexpagerangetranslator_latex().find(params_.range);
170 getSeeRefs(os, runparams);
171 } else if (!params_.pagefmt.empty() && params_.pagefmt != "default") {
173 os << insetindexpagerangetranslator_latex().find(params_.range);
174 os << from_utf8(params_.pagefmt);
175 } else if (params_.range != InsetIndexParams::PageRange::None) {
177 os << insetindexpagerangetranslator_latex().find(params_.range);
180 // We check whether we need a sort key.
181 // If so, we use the plaintext version
182 odocstringstream ourplain;
183 InsetText::plaintext(ourplain, runparams);
185 // These are the LaTeX and plaintext representations
186 docstring latexstr = ourlatex.str();
187 docstring plainstr = ourplain.str();
189 // This will get what follows | if anything does,
190 // the command (e.g., see, textbf) for pagination
195 odocstringstream seeref;
196 otexstream otsee(seeref);
197 getSeeRefs(otsee, runparams);
199 } else if (!params_.pagefmt.empty() && params_.pagefmt != "default") {
200 cmd = from_utf8(params_.pagefmt);
202 // Check for the | separator to strip the cmd.
203 // This goes wrong on an escaped "|", but as the escape
204 // character can be changed in style files, we cannot
206 size_t pos = latexstr.find(from_ascii("|"));
207 if (pos != docstring::npos) {
208 // Put the bit after "|" into cmd...
209 cmd = latexstr.substr(pos + 1);
210 // ...and erase that stuff from latexstr
211 latexstr = latexstr.erase(pos);
212 // ...as well as from plainstr
213 size_t ppos = plainstr.find(from_ascii("|"));
214 if (ppos < plainstr.size())
215 plainstr.erase(ppos);
217 LYXERR0("The `|' separator was not found in the plaintext version!");
221 odocstringstream subentries;
222 otexstream otsub(subentries);
223 getSubentries(otsub, runparams, ourlatex.str());
224 if (subentries.str().empty()) {
225 // Separate the entries and subentries, i.e., split on "!".
226 // This goes wrong on an escaped "!", but as the escape
227 // character can be changed in style files, we cannot
229 std::vector<docstring> const levels =
230 getVectorFromString(latexstr, from_ascii("!"), true);
231 std::vector<docstring> const levels_plain =
232 getVectorFromString(plainstr, from_ascii("!"), true);
234 vector<docstring>::const_iterator it = levels.begin();
235 vector<docstring>::const_iterator end = levels.end();
236 vector<docstring>::const_iterator it2 = levels_plain.begin();
238 for (; it != end; ++it) {
240 emptySubentriesWarning(ourlatex.str());
241 if (it2 < levels_plain.end())
245 // The separator needs to be put back when
246 // writing the levels, except for the first level
252 // Now here comes the reason for this whole procedure:
253 // We try to correctly sort macros and formatted strings.
254 // If we find a command, prepend a plain text
255 // version of the content to get sorting right,
256 // e.g. \index{LyX@\LyX}, \index{text@\textbf{text}}.
257 // We do this on all levels.
258 // We don't do it if the level already contains a '@', though.
259 // Plaintext might return nothing (e.g. for ERTs).
260 // In that case, we use LaTeX.
261 docstring const spart = (levels_plain.empty() || (*it2).empty()) ? *it : *it2;
262 processLatexSorting(os, runparams, *it, spart);
263 if (it2 < levels_plain.end())
267 processLatexSorting(os, runparams, latexstr, plainstr);
268 os << subentries.str();
271 // At last, re-insert the command, separated by "|"
274 << insetindexpagerangetranslator_latex().find(params_.range)
276 } else if (params_.range != InsetIndexParams::PageRange::None) {
278 os << insetindexpagerangetranslator_latex().find(params_.range);
283 // In macros with moving arguments, such as \section,
284 // we store the index and output it after the macro (#2154)
285 if (runparams_in.postpone_fragile_stuff)
286 runparams_in.post_macro += os.str();
292 void InsetIndex::processLatexSorting(otexstream & os, OutputParams const & runparams,
293 docstring const latex, docstring const spart) const
295 if (contains(latex, '\\') && !contains(latex, '@')) {
296 // Now we need to validate that all characters in
297 // the sorting part are representable in the current
298 // encoding. If not try the LaTeX macro which might
299 // or might not be a good choice, and issue a warning.
300 pair<docstring, docstring> spart_latexed =
301 runparams.encoding->latexString(spart, runparams.dryrun);
302 if (!spart_latexed.second.empty())
303 LYXERR0("Uncodable character in index entry. Sorting might be wrong!");
304 if (spart != spart_latexed.first && !runparams.dryrun) {
306 ErrorList & errorList = buffer().errorList("Export");
307 docstring const s = bformat(_("LyX's automatic index sorting algorithm faced "
308 "problems with the entry '%1$s'.\n"
309 "Please specify the sorting of this entry manually, as "
310 "explained in the User Guide."), spart);
311 Paragraph const & par = buffer().paragraphs().front();
312 errorList.push_back(ErrorItem(_("Index sorting failed"), s,
313 {par.id(), 0}, {par.id(), -1}));
314 buffer().bufferErrors(terr, errorList);
316 // Remove remaining \'s from the sort key
317 docstring ppart = subst(spart_latexed.first, from_ascii("\\"), docstring());
318 // Plain quotes need to be escaped, however (#10649), as this
319 // is the default escape character
320 ppart = subst(ppart, from_ascii("\""), from_ascii("\\\""));
322 // Now insert the sortkey, separated by '@'.
326 // Insert the actual level text
331 void InsetIndex::docbook(XMLStream & xs, OutputParams const & runparams) const
333 // Two ways of processing this inset are implemented:
334 // - the legacy one, based on parsing the raw LaTeX (before LyX 2.4) -- unlikely to be deprecated
335 // - the modern one, based on precise insets for indexing features
336 // Like the LaTeX implementation, consider the user chooses either of those options.
338 // Get the content of the inset as LaTeX, as some things may be encoded as ERT (like {}).
339 // TODO: if there is an ERT within the index term, its conversion should be tried, in case it becomes useful;
340 // otherwise, ERTs should become comments. For now, they are just copied as-is, which is barely satisfactory.
341 odocstringstream odss;
342 otexstream ots(odss);
343 InsetText::latex(ots, runparams);
344 docstring latexString = trim(odss.str());
346 // Handle several indices (indicated in the inset instead of the raw latexString).
347 docstring indexType = from_utf8("");
348 if (buffer().masterBuffer()->params().use_indices) {
349 indexType += " type=\"" + params_.index + "\"";
352 // Split the string into its main constituents: terms, and command (see, see also, range).
353 size_t positionVerticalBar = latexString.find(from_ascii("|")); // What comes before | is (sub)(sub)entries.
354 docstring indexTerms = latexString.substr(0, positionVerticalBar);
356 if (positionVerticalBar != lyx::docstring::npos) {
357 command = latexString.substr(positionVerticalBar + 1);
360 // Handle sorting issues, with @.
363 sortAs = getSortkeyAsText(runparams);
364 // indexTerms may contain a sort key if the user has both the inset and the manual key.
366 vector<docstring> sortingElements = getVectorFromString(indexTerms, from_ascii("@"), false);
367 if (sortingElements.size() == 2) {
368 sortAs = sortingElements[0];
369 indexTerms = sortingElements[1];
373 // Handle primary, secondary, and tertiary terms (entries, subentries, and subsubentries, for LaTeX).
374 vector<docstring> terms;
375 if (const vector<docstring> potential_terms = getSubentriesAsText(runparams); !potential_terms.empty()) {
376 terms = potential_terms;
377 // The main term is not present in the vector, as it's not a subentry. The main index term is inserted raw in
378 // the index inset. Considering that the user either uses the new or the legacy mechanism, the main term is the
379 // full string within this inset (i.e. without the subinsets).
380 terms.insert(terms.begin(), latexString);
382 terms = getVectorFromString(indexTerms, from_ascii("!"), false);
385 // Handle ranges. Happily, in the raw LaTeX mode, (| and |) can only be at the end of the string!
386 const bool hasInsetRange = params_.range != InsetIndexParams::PageRange::None;
387 const bool hasStartRange = params_.range == InsetIndexParams::PageRange::Start ||
388 latexString.find(from_ascii("|(")) != lyx::docstring::npos;
389 const bool hasEndRange = params_.range == InsetIndexParams::PageRange::End ||
390 latexString.find(from_ascii("|)")) != lyx::docstring::npos;
393 // Remove the ranges from the command if they do not appear at the beginning.
395 while ((index = command.find(from_utf8("|("), index)) != std::string::npos)
396 command.erase(index, 1);
398 while ((index = command.find(from_utf8("|)"), index)) != std::string::npos)
399 command.erase(index, 1);
401 // Remove the ranges when they are the only vertical bar in the complete string.
402 if (command[0] == '(' || command[0] == ')')
406 // Handle see and seealso. As "see" is a prefix of "seealso", the order of the comparisons is important.
407 // Both commands are mutually exclusive!
408 docstring see = getSeeAsText(runparams);
409 vector<docstring> seeAlsoes = getSeeAlsoesAsText(runparams);
411 if (see.empty() && seeAlsoes.empty() && command.substr(0, 3) == "see") {
412 // Unescape brackets.
414 while ((index = command.find(from_utf8("\\{"), index)) != std::string::npos)
415 command.erase(index, 1);
417 while ((index = command.find(from_utf8("\\}"), index)) != std::string::npos)
418 command.erase(index, 1);
420 // Retrieve the part between brackets, and remove the complete seealso.
421 size_t positionOpeningBracket = command.find(from_ascii("{"));
422 size_t positionClosingBracket = command.find(from_ascii("}"));
423 docstring list = command.substr(positionOpeningBracket + 1, positionClosingBracket - positionOpeningBracket - 1);
425 // Parse the list of referenced entries (or a single one for see).
426 if (command.substr(0, 7) == "seealso") {
427 seeAlsoes = getVectorFromString(list, from_ascii(","), false);
431 if (see.find(from_ascii(",")) != std::string::npos) {
432 docstring error = from_utf8("Several index terms found as \"see\"! Only one is acceptable. "
433 "Complete entry: \"") + latexString + from_utf8("\"");
435 xs << XMLStream::ESCAPE_NONE << (from_utf8("<!-- Output Error: ") + error + from_utf8(" -->\n"));
439 // Remove the complete see/seealso from the commands, in case there is something else to parse.
440 command = command.substr(positionClosingBracket + 1);
443 // Some parts of the strings are not parsed, as they do not have anything matching in DocBook: things like
444 // formatting the entry or the page number, other strings for sorting. https://wiki.lyx.org/Tips/Indexing
445 // If there are such things in the index entry, then this code may miserably fail. For example, for "Peter|(textbf",
446 // no range will be detected.
447 // TODO: Could handle formatting as significance="preferred"?
448 if (!command.empty()) {
449 docstring error = from_utf8("Unsupported feature: an index entry contains a | with an unsupported command, ")
450 + command + from_utf8(". ") + from_utf8("Complete entry: \"") + latexString + from_utf8("\"");
452 xs << XMLStream::ESCAPE_NONE << (from_utf8("<!-- Output Error: ") + error + from_utf8(" -->\n"));
455 // Write all of this down.
456 if (terms.empty() && !hasEndRange) {
457 docstring error = from_utf8("No index term found! Complete entry: \"") + latexString + from_utf8("\"");
459 xs << XMLStream::ESCAPE_NONE << (from_utf8("<!-- Output Error: ") + error + from_utf8(" -->\n"));
461 // Generate the attributes for ranges. It is based on the terms that are indexed, but the ID must be unique
462 // to this indexing area (xml::cleanID does not guarantee this: for each call with the same arguments,
463 // the same legal ID is produced; here, as the input would be the same, the output must be, by design).
464 // Hence the thread-local storage, as the numbers must strictly be unique, and thus cannot be shared across
465 // a paragraph (making the solution used for HTML worthless). This solution is very similar to the one used in
467 // indexType can only be used for singular and startofrange types!
469 if (!hasStartRange && !hasEndRange) {
472 // Append an ID if uniqueness is not guaranteed across the document.
473 static QThreadStorage<set<docstring>> tKnownTermLists;
474 static QThreadStorage<int> tID;
476 set<docstring> &knownTermLists = tKnownTermLists.localData();
477 int &ID = tID.localData();
479 if (!tID.hasLocalData()) {
483 // Modify the index terms to add the unique ID if needed.
484 docstring newIndexTerms = indexTerms;
485 if (knownTermLists.find(indexTerms) != knownTermLists.end()) {
486 newIndexTerms += from_ascii(string("-") + to_string(ID));
488 // Only increment for the end of range, so that the same number is used for the start of range.
494 // Term list not yet known: add it to the set AFTER the end of range. After
495 if (knownTermLists.find(indexTerms) == knownTermLists.end() && hasEndRange) {
496 knownTermLists.insert(indexTerms);
499 // Generate the attributes.
500 docstring id = xml::cleanID(newIndexTerms);
502 attrs = indexType + " class=\"startofrange\" xml:id=\"" + id + "\"";
504 attrs = " class=\"endofrange\" startref=\"" + id + "\"";
508 // Handle the index terms (including the specific index for this entry).
510 xs << xml::CompTag("indexterm", attrs);
512 xs << xml::StartTag("indexterm", attrs);
513 if (!terms.empty()) { // hasEndRange has no content.
515 if (!sortAs.empty()) {
516 attr = from_utf8("sortas='") + sortAs + from_utf8("'");
519 xs << xml::StartTag("primary", attr);
521 xs << xml::EndTag("primary");
523 if (terms.size() > 1) {
524 xs << xml::StartTag("secondary");
526 xs << xml::EndTag("secondary");
528 if (terms.size() > 2) {
529 xs << xml::StartTag("tertiary");
531 xs << xml::EndTag("tertiary");
534 // Handle see and see also.
536 xs << xml::StartTag("see");
538 xs << xml::EndTag("see");
541 if (!seeAlsoes.empty()) {
542 for (auto &entry : seeAlsoes) {
543 xs << xml::StartTag("seealso");
545 xs << xml::EndTag("seealso");
550 xs << xml::EndTag("indexterm");
556 docstring InsetIndex::xhtml(XMLStream & xs, OutputParams const &) const
558 // we just print an anchor, taking the paragraph ID from
559 // our own interior paragraph, which doesn't get printed
560 std::string const magic = paragraphs().front().magicLabel();
561 std::string const attr = "id='" + magic + "'";
562 xs << xml::CompTag("a", attr);
567 bool InsetIndex::showInsetDialog(BufferView * bv) const
569 bv->showDialog("index", params2string(params_),
570 const_cast<InsetIndex *>(this));
575 void InsetIndex::doDispatch(Cursor & cur, FuncRequest & cmd)
577 switch (cmd.action()) {
579 case LFUN_INSET_MODIFY: {
580 if (cmd.getArg(0) == "changetype") {
581 cur.recordUndoInset(this);
582 params_.index = from_utf8(cmd.getArg(1));
585 InsetIndexParams params;
586 InsetIndex::string2params(to_utf8(cmd.argument()), params);
587 cur.recordUndoInset(this);
588 params_.index = params.index;
589 params_.range = params.range;
590 params_.pagefmt = params.pagefmt;
591 // what we really want here is a TOC update, but that means
592 // a full buffer update
593 cur.forceBufferUpdate();
597 case LFUN_INSET_DIALOG_UPDATE:
598 cur.bv().updateDialog("index", params2string(params_));
601 case LFUN_PARAGRAPH_BREAK: {
602 // Since this inset in single-par anyway, let's use
603 // return to enter subentries
604 FuncRequest fr(LFUN_INDEXMACRO_INSERT, "subentry");
610 InsetCollapsible::doDispatch(cur, cmd);
616 bool InsetIndex::getStatus(Cursor & cur, FuncRequest const & cmd,
617 FuncStatus & flag) const
619 switch (cmd.action()) {
621 case LFUN_INSET_MODIFY:
622 if (cmd.getArg(0) == "changetype") {
623 docstring const newtype = from_utf8(cmd.getArg(1));
624 Buffer const & realbuffer = *buffer().masterBuffer();
625 IndicesList const & indiceslist = realbuffer.params().indiceslist();
626 Index const * index = indiceslist.findShortcut(newtype);
627 flag.setEnabled(index != 0);
629 from_utf8(cmd.getArg(1)) == params_.index);
632 return InsetCollapsible::getStatus(cur, cmd, flag);
634 case LFUN_INSET_DIALOG_UPDATE: {
635 Buffer const & realbuffer = *buffer().masterBuffer();
636 flag.setEnabled(realbuffer.params().use_indices);
640 case LFUN_PARAGRAPH_BREAK:
641 return macrosPossible("subentry");
643 case LFUN_INDEXMACRO_INSERT:
644 return macrosPossible(cmd.getArg(0));
647 return InsetCollapsible::getStatus(cur, cmd, flag);
652 void InsetIndex::getSortkey(otexstream & os, OutputParams const & runparams) const
654 Paragraph const & par = paragraphs().front();
655 InsetList::const_iterator it = par.insetList().begin();
656 for (; it != par.insetList().end(); ++it) {
657 Inset & inset = *it->inset;
658 if (inset.lyxCode() == INDEXMACRO_SORTKEY_CODE) {
659 InsetIndexMacro const & iim =
660 static_cast<InsetIndexMacro const &>(inset);
661 iim.getLatex(os, runparams);
668 docstring InsetIndex::getSortkeyAsText(OutputParams const & runparams) const
670 Paragraph const & par = paragraphs().front();
671 InsetList::const_iterator it = par.insetList().begin();
672 for (; it != par.insetList().end(); ++it) {
673 Inset & inset = *it->inset;
674 if (inset.lyxCode() == INDEXMACRO_SORTKEY_CODE) {
676 InsetIndexMacro const & iim =
677 static_cast<InsetIndexMacro const &>(inset);
678 iim.getLatex(os, runparams);
682 return from_ascii("");
686 void InsetIndex::emptySubentriesWarning(docstring const & mainentry) const
688 // Empty subentries crash makeindex. So warn and ignore this.
690 ErrorList & errorList = buffer().errorList("Export");
691 docstring const s = bformat(_("There is an empty index subentry in the entry '%1$s'.\n"
692 "It will be ignored in the output."), mainentry);
693 Paragraph const & par = buffer().paragraphs().front();
694 errorList.push_back(ErrorItem(_("Empty index subentry!"), s,
695 {par.id(), 0}, {par.id(), -1}));
696 buffer().bufferErrors(terr, errorList);
700 void InsetIndex::getSubentries(otexstream & os, OutputParams const & runparams,
701 docstring const & mainentry) const
703 Paragraph const & par = paragraphs().front();
704 InsetList::const_iterator it = par.insetList().begin();
706 for (; it != par.insetList().end(); ++it) {
707 Inset & inset = *it->inset;
708 if (inset.lyxCode() == INDEXMACRO_CODE) {
709 InsetIndexMacro const & iim =
710 static_cast<InsetIndexMacro const &>(inset);
711 if (iim.params().type == InsetIndexMacroParams::Subentry) {
712 if (iim.hasNoContent()) {
713 emptySubentriesWarning(mainentry);
720 iim.getLatex(os, runparams);
727 std::vector<docstring> InsetIndex::getSubentriesAsText(OutputParams const & runparams,
728 bool const asLabel) const
730 std::vector<docstring> subentries;
732 Paragraph const & par = paragraphs().front();
733 InsetList::const_iterator it = par.insetList().begin();
735 for (; it != par.insetList().end(); ++it) {
736 Inset & inset = *it->inset;
737 if (inset.lyxCode() == INDEXMACRO_CODE) {
738 InsetIndexMacro const & iim =
739 static_cast<InsetIndexMacro const &>(inset);
740 if (iim.params().type == InsetIndexMacroParams::Subentry) {
746 docstring const sl = iim.getNewLabel(l);
747 subentries.emplace_back(sl);
750 iim.getLatex(os, runparams);
751 subentries.emplace_back(os.str());
761 docstring InsetIndex::getMainSubentryAsText(OutputParams const & runparams) const
764 InsetText::latex(os, runparams);
769 void InsetIndex::getSeeRefs(otexstream & os, OutputParams const & runparams) const
771 Paragraph const & par = paragraphs().front();
772 InsetList::const_iterator it = par.insetList().begin();
773 for (; it != par.insetList().end(); ++it) {
774 Inset & inset = *it->inset;
775 if (inset.lyxCode() == INDEXMACRO_CODE) {
776 InsetIndexMacro const & iim =
777 static_cast<InsetIndexMacro const &>(inset);
778 if (iim.params().type == InsetIndexMacroParams::See
779 || iim.params().type == InsetIndexMacroParams::Seealso) {
780 iim.getLatex(os, runparams);
788 docstring InsetIndex::getSeeAsText(OutputParams const & runparams,
789 bool const asLabel) const
791 Paragraph const & par = paragraphs().front();
792 InsetList::const_iterator it = par.insetList().begin();
793 for (; it != par.insetList().end(); ++it) {
794 Inset & inset = *it->inset;
795 if (inset.lyxCode() == INDEXMACRO_CODE) {
796 InsetIndexMacro const & iim =
797 static_cast<InsetIndexMacro const &>(inset);
798 if (iim.params().type == InsetIndexMacroParams::See) {
801 return iim.getNewLabel(l);
804 iim.getLatex(os, runparams);
810 return from_ascii("");
814 std::vector<docstring> InsetIndex::getSeeAlsoesAsText(OutputParams const & runparams,
815 bool const asLabel) const
817 std::vector<docstring> seeAlsoes;
819 Paragraph const & par = paragraphs().front();
820 InsetList::const_iterator it = par.insetList().begin();
821 for (; it != par.insetList().end(); ++it) {
822 Inset & inset = *it->inset;
823 if (inset.lyxCode() == INDEXMACRO_CODE) {
824 InsetIndexMacro const & iim =
825 static_cast<InsetIndexMacro const &>(inset);
826 if (iim.params().type == InsetIndexMacroParams::Seealso) {
829 seeAlsoes.emplace_back(iim.getNewLabel(l));
832 iim.getLatex(os, runparams);
833 seeAlsoes.emplace_back(os.str());
845 bool hasInsetWithCode(const InsetIndex * const inset_index, const InsetCode code,
846 const std::set<InsetIndexMacroParams::Type> types = {})
848 Paragraph const & par = inset_index->paragraphs().front();
849 InsetList::const_iterator it = par.insetList().begin();
850 for (; it != par.insetList().end(); ++it) {
851 Inset & inset = *it->inset;
852 if (inset.lyxCode() == code) {
856 LASSERT(code == INDEXMACRO_CODE, return false);
857 InsetIndexMacro const & iim =
858 static_cast<InsetIndexMacro const &>(inset);
859 if (types.find(iim.params().type) != types.end())
869 bool InsetIndex::hasSubentries() const
871 return hasInsetWithCode(this, INDEXMACRO_CODE, {InsetIndexMacroParams::Subentry});
875 bool InsetIndex::hasSeeRef() const
877 return hasInsetWithCode(this, INDEXMACRO_CODE, {InsetIndexMacroParams::See, InsetIndexMacroParams::Seealso});
881 bool InsetIndex::hasSortKey() const
883 return hasInsetWithCode(this, INDEXMACRO_SORTKEY_CODE);
887 bool InsetIndex::macrosPossible(string const type) const
889 if (type != "see" && type != "seealso"
890 && type != "sortkey" && type != "subentry")
893 Paragraph const & par = paragraphs().front();
894 InsetList::const_iterator it = par.insetList().begin();
896 for (; it != par.insetList().end(); ++it) {
897 Inset & inset = *it->inset;
898 if (type == "sortkey" && inset.lyxCode() == INDEXMACRO_SORTKEY_CODE)
900 if (inset.lyxCode() == INDEXMACRO_CODE) {
901 InsetIndexMacro const & iim = static_cast<InsetIndexMacro const &>(inset);
902 if ((type == "see" || type == "seealso")
903 && (iim.params().type == InsetIndexMacroParams::See
904 || iim.params().type == InsetIndexMacroParams::Seealso))
906 if (type == "subentry"
907 && iim.params().type == InsetIndexMacroParams::Subentry) {
918 ColorCode InsetIndex::labelColor() const
920 if (params_.index.empty() || params_.index == from_ascii("idx"))
921 return InsetCollapsible::labelColor();
923 ColorCode c = lcolor.getFromLyXName(to_utf8(params_.index)
924 + "@" + buffer().fileName().absFileName());
926 c = InsetCollapsible::labelColor();
931 docstring InsetIndex::toolTip(BufferView const &, int, int) const
933 docstring tip = _("Index Entry");
934 if (buffer().params().use_indices && !params_.index.empty()) {
935 Buffer const & realbuffer = *buffer().masterBuffer();
936 IndicesList const & indiceslist = realbuffer.params().indiceslist();
938 Index const * index = indiceslist.findShortcut(params_.index);
940 tip += _("unknown type!");
942 tip += index->index();
946 docstring res = toolTipText(tip);
947 if (!insetindexpagerangetranslator_loc().find(params_.range).empty())
948 res += "\n" + insetindexpagerangetranslator_loc().find(params_.range);
949 if (!params_.pagefmt.empty() && params_.pagefmt != "default") {
950 res += "\n" + _("Pagination format:") + " ";
951 if (params_.pagefmt == "textbf")
953 else if (params_.pagefmt == "textit")
955 else if (params_.pagefmt == "emph")
956 res += _("emphasized");
958 res += from_utf8(params_.pagefmt);
964 docstring const InsetIndex::buttonLabel(BufferView const & bv) const
966 InsetLayout const & il = getLayout();
967 docstring label = translateIfPossible(il.labelstring());
969 if (buffer().params().use_indices && !params_.index.empty()) {
970 Buffer const & realbuffer = *buffer().masterBuffer();
971 IndicesList const & indiceslist = realbuffer.params().indiceslist();
973 Index const * index = indiceslist.findShortcut(params_.index);
975 label += _("unknown type!");
977 label += index->index();
982 if (!il.contentaslabel() || geometry(bv) != ButtonOnly)
985 res = getNewLabel(label);
986 OutputParams const rp(0);
987 vector<docstring> sublbls = getSubentriesAsText(rp, true);
988 for (auto const & sublbl : sublbls) {
989 res += " " + docstring(1, char_type(0x2023));// TRIANGULAR BULLET
992 docstring see = getSeeAsText(rp, true);
993 if (see.empty() && !getSeeAlsoesAsText(rp, true).empty())
994 see = getSeeAlsoesAsText(rp, true).front();
996 res += " " + docstring(1, char_type(0x261e));// WHITE RIGHT POINTING INDEX
1000 if (!insetindexpagerangetranslator_latex().find(params_.range).empty())
1001 res += " " + from_ascii(insetindexpagerangetranslator_latex().find(params_.range));
1006 void InsetIndex::write(ostream & os) const
1008 os << to_utf8(layoutName());
1010 InsetCollapsible::write(os);
1014 void InsetIndex::read(Lexer & lex)
1017 InsetCollapsible::read(lex);
1021 string InsetIndex::params2string(InsetIndexParams const & params)
1030 void InsetIndex::string2params(string const & in, InsetIndexParams & params)
1032 params = InsetIndexParams();
1036 istringstream data(in);
1038 lex.setStream(data);
1039 lex.setContext("InsetIndex::string2params");
1045 void InsetIndex::addToToc(DocIterator const & cpit, bool output_active,
1046 UpdateType utype, TocBackend & backend) const
1048 DocIterator pit = cpit;
1049 pit.push_back(CursorSlice(const_cast<InsetIndex &>(*this)));
1051 InsetLayout const & il = getLayout();
1052 docstring label = translateIfPossible(il.labelstring());
1053 if (!il.contentaslabel())
1056 str = getNewLabel(label);
1057 OutputParams const rp(0);
1058 vector<docstring> sublbls = getSubentriesAsText(rp, true);
1059 for (auto const & sublbl : sublbls) {
1060 str += " " + docstring(1, char_type(0x2023));// TRIANGULAR BULLET
1061 str += " " + sublbl;
1063 docstring see = getSeeAsText(rp, true);
1064 if (see.empty() && !getSeeAlsoesAsText(rp, true).empty())
1065 see = getSeeAlsoesAsText(rp, true).front();
1067 str += " " + docstring(1, char_type(0x261e));// WHITE RIGHT POINTING INDEX
1071 string type = "index";
1072 if (buffer().masterBuffer()->params().use_indices)
1073 type += ":" + to_utf8(params_.index);
1074 TocBuilder & b = backend.builder(type);
1075 b.pushItem(pit, str, output_active);
1076 // Proceed with the rest of the inset.
1077 InsetCollapsible::addToToc(cpit, output_active, utype, backend);
1082 void InsetIndex::validate(LaTeXFeatures & features) const
1084 if (buffer().masterBuffer()->params().use_indices
1085 && !params_.index.empty()
1086 && params_.index != "idx")
1087 features.require("splitidx");
1088 InsetCollapsible::validate(features);
1092 string InsetIndex::contextMenuName() const
1094 return "context-index";
1098 string InsetIndex::contextMenu(BufferView const & bv, int x, int y) const
1100 // We override the implementation of InsetCollapsible,
1101 // because we have eytra entries.
1102 string owncm = "context-edit-index;";
1103 return owncm + InsetCollapsible::contextMenu(bv, x, y);
1107 bool InsetIndex::hasSettings() const
1113 bool InsetIndex::insetAllowed(InsetCode code) const
1116 case INDEXMACRO_CODE:
1117 case INDEXMACRO_SORTKEY_CODE:
1122 return InsetCollapsible::insetAllowed(code);
1127 /////////////////////////////////////////////////////////////////////
1131 ///////////////////////////////////////////////////////////////////////
1134 void InsetIndexParams::write(ostream & os) const
1138 os << to_utf8(index);
1143 << insetindexpagerangetranslator().find(range)
1151 void InsetIndexParams::read(Lexer & lex)
1154 index = lex.getDocString();
1156 index = from_ascii("idx");
1157 if (lex.checkFor("range")) {
1158 string st = lex.getString();
1159 if (lex.eatLine()) {
1160 st = lex.getString();
1161 range = insetindexpagerangetranslator().find(lex.getString());
1164 if (lex.checkFor("pageformat") && lex.eatLine()) {
1165 pagefmt = lex.getString();
1170 /////////////////////////////////////////////////////////////////////
1174 ///////////////////////////////////////////////////////////////////////
1176 InsetPrintIndex::InsetPrintIndex(Buffer * buf, InsetCommandParams const & p)
1177 : InsetCommand(buf, p)
1181 ParamInfo const & InsetPrintIndex::findInfo(string const & /* cmdName */)
1183 static ParamInfo param_info_;
1184 if (param_info_.empty()) {
1185 param_info_.add("type", ParamInfo::LATEX_OPTIONAL,
1186 ParamInfo::HANDLING_ESCAPE);
1187 param_info_.add("name", ParamInfo::LATEX_OPTIONAL,
1188 ParamInfo::HANDLING_LATEXIFY);
1189 param_info_.add("literal", ParamInfo::LYX_INTERNAL);
1195 docstring InsetPrintIndex::screenLabel() const
1197 bool const printall = suffixIs(getCmdName(), '*');
1198 bool const multind = buffer().masterBuffer()->params().use_indices;
1200 && getParam("type") == from_ascii("idx"))
1201 || (getParam("type").empty() && !printall))
1203 Buffer const & realbuffer = *buffer().masterBuffer();
1204 IndicesList const & indiceslist = realbuffer.params().indiceslist();
1205 Index const * index = indiceslist.findShortcut(getParam("type"));
1206 if (!index && !printall)
1207 return _("Unknown index type!");
1208 docstring res = printall ? _("All indexes") : index->index();
1210 res += " (" + _("non-active") + ")";
1211 else if (contains(getCmdName(), "printsubindex"))
1212 res += " (" + _("subindex") + ")";
1217 bool InsetPrintIndex::isCompatibleCommand(string const & s)
1219 return s == "printindex" || s == "printsubindex"
1220 || s == "printindex*" || s == "printsubindex*";
1224 void InsetPrintIndex::doDispatch(Cursor & cur, FuncRequest & cmd)
1226 switch (cmd.action()) {
1228 case LFUN_INSET_MODIFY: {
1229 if (cmd.argument() == from_ascii("toggle-subindex")) {
1230 string scmd = getCmdName();
1231 if (contains(scmd, "printindex"))
1232 scmd = subst(scmd, "printindex", "printsubindex");
1234 scmd = subst(scmd, "printsubindex", "printindex");
1238 } else if (cmd.argument() == from_ascii("check-printindex*")) {
1239 string scmd = getCmdName();
1240 if (suffixIs(scmd, '*'))
1244 setParam("type", docstring());
1248 InsetCommandParams p(INDEX_PRINT_CODE);
1250 InsetCommand::string2params(to_utf8(cmd.argument()), p);
1251 if (p.getCmdName().empty()) {
1252 cur.noScreenUpdate();
1261 InsetCommand::doDispatch(cur, cmd);
1267 bool InsetPrintIndex::getStatus(Cursor & cur, FuncRequest const & cmd,
1268 FuncStatus & status) const
1270 switch (cmd.action()) {
1272 case LFUN_INSET_MODIFY: {
1273 if (cmd.argument() == from_ascii("toggle-subindex")) {
1274 status.setEnabled(buffer().masterBuffer()->params().use_indices);
1275 status.setOnOff(contains(getCmdName(), "printsubindex"));
1277 } else if (cmd.argument() == from_ascii("check-printindex*")) {
1278 status.setEnabled(buffer().masterBuffer()->params().use_indices);
1279 status.setOnOff(suffixIs(getCmdName(), '*'));
1281 } if (cmd.getArg(0) == "index_print"
1282 && cmd.getArg(1) == "CommandInset") {
1283 InsetCommandParams p(INDEX_PRINT_CODE);
1284 InsetCommand::string2params(to_utf8(cmd.argument()), p);
1285 if (suffixIs(p.getCmdName(), '*')) {
1286 status.setEnabled(true);
1287 status.setOnOff(false);
1290 Buffer const & realbuffer = *buffer().masterBuffer();
1291 IndicesList const & indiceslist =
1292 realbuffer.params().indiceslist();
1293 Index const * index = indiceslist.findShortcut(p["type"]);
1294 status.setEnabled(index != 0);
1295 status.setOnOff(p["type"] == getParam("type"));
1298 return InsetCommand::getStatus(cur, cmd, status);
1301 case LFUN_INSET_DIALOG_UPDATE: {
1302 status.setEnabled(buffer().masterBuffer()->params().use_indices);
1307 return InsetCommand::getStatus(cur, cmd, status);
1312 void InsetPrintIndex::updateBuffer(ParIterator const &, UpdateType, bool const /*deleted*/)
1314 Index const * index =
1315 buffer().masterParams().indiceslist().findShortcut(getParam("type"));
1317 setParam("name", index->index());
1321 void InsetPrintIndex::latex(otexstream & os, OutputParams const & runparams_in) const
1323 if (!buffer().masterBuffer()->params().use_indices) {
1324 if (getParam("type") == from_ascii("idx"))
1325 os << "\\printindex" << termcmd;
1328 OutputParams runparams = runparams_in;
1329 os << getCommand(runparams);
1333 void InsetPrintIndex::validate(LaTeXFeatures & features) const
1335 features.require("makeidx");
1336 if (buffer().masterBuffer()->params().use_indices)
1337 features.require("splitidx");
1338 InsetCommand::validate(features);
1342 string InsetPrintIndex::contextMenuName() const
1344 return buffer().masterBuffer()->params().use_indices ?
1345 "context-indexprint" : string();
1349 bool InsetPrintIndex::hasSettings() const
1351 return buffer().masterBuffer()->params().use_indices;
1358 /// Builds an entry for the index.
1359 IndexEntry(const InsetIndex * inset, OutputParams const * runparams) : inset_(inset), runparams_(runparams)
1361 LASSERT(runparams, return);
1363 // Convert the inset as text. The resulting text usually only contains an XHTML anchor (<a id='...'/>) and text.
1364 odocstringstream entry;
1365 OutputParams ours = *runparams;
1366 ours.for_toc = false;
1367 inset_->plaintext(entry, ours);
1368 entry_ = entry.str();
1370 // Determine in which index this entry belongs to.
1371 if (inset_->buffer().masterBuffer()->params().use_indices) {
1372 index_ = inset_->params_.index;
1375 // Attempt parsing the inset.
1382 /// When parsing this entry, some errors may be found; they are reported as a single string.
1383 // It is up to the caller to send this string to LYXERR and the output file, as needed.
1384 const docstring & output_error() const
1386 return output_error_;
1389 void output_error(XMLStream xs) const
1391 LYXERR0(output_error());
1392 xs << XMLStream::ESCAPE_NONE << (from_utf8("<!-- Output Error: ") + output_error() + from_utf8(" -->\n"));
1399 std::cout << to_utf8(entry_) << std::endl;
1401 // If a modern parameter is present, this is definitely a modern index inset. Similarly, if it contains the
1402 // usual LaTeX symbols (!|@), then it is definitely a legacy index inset. Otherwise, if it has features of
1403 // neither, it is both: consider this is a modern inset, to trigger the least complex code. Mixing both types
1404 // is not allowed (i.e. behaviour is undefined).
1405 const bool is_definitely_modern = inset_->hasSortKey() || inset_->hasSeeRef() || inset_->hasSubentries()
1406 || inset_->params_.range != InsetIndexParams::PageRange::None;
1407 const bool is_definitely_legacy = entry_.find('@') != std::string::npos
1408 || entry_.find('|') != std::string::npos || entry_.find('!') != std::string::npos;
1410 if (is_definitely_legacy && is_definitely_modern)
1411 output_error_ += from_utf8("Mix of index properties and raw LaTeX index commands is unsupported. ");
1414 // - is_definitely_modern == true:
1415 // - is_definitely_legacy == true: error (return whatever)
1416 // - is_definitely_legacy == false: return modern
1417 // - is_definitely_modern == false:
1418 // - is_definitely_legacy == true: return legacy
1419 // - is_definitely_legacy == false: return modern
1420 return !is_definitely_legacy;
1423 void parseAsModern()
1425 LASSERT(runparams_, return);
1427 if (inset_->hasSortKey()) {
1428 sort_as_ = inset_->getSortkeyAsText(*runparams_);
1431 terms_ = inset_->getSubentriesAsText(*runparams_);
1432 // The main term is not present in the vector, as it's not a subentry. The main index term is inserted raw in
1433 // the index inset. Considering that the user either uses the new or the legacy mechanism, the main term is the
1434 // full string within this inset (i.e. without the subinsets).
1435 terms_.insert(terms_.begin(), inset_->getMainSubentryAsText(*runparams_));
1437 has_start_range_ = inset_->params_.range == InsetIndexParams::PageRange::Start;
1438 has_end_range_ = inset_->params_.range == InsetIndexParams::PageRange::End;
1440 see_ = inset_->getSeeAsText(*runparams_);
1441 see_alsoes_ = inset_->getSeeAlsoesAsText(*runparams_);
1444 void parseAsLegacy() {
1445 // Determine if some features are known not to be supported. For now, this is only formatting like
1446 // \index{alpha@\textbf{alpha}} or \index{alpha@$\alpha$}.
1447 // @ is supported, but only for sorting, without specific formatting.
1448 if (entry_.find(from_utf8("@\\")) != lyx::docstring::npos) {
1449 output_error_ += from_utf8("Unsupported feature: an index entry contains an @\\. "
1450 "Complete entry: \"") + entry_ + from_utf8("\". ");
1452 if (entry_.find(from_utf8("@$")) != lyx::docstring::npos) {
1453 output_error_ += from_utf8("Unsupported feature: an index entry contains an @$. "
1454 "Complete entry: \"") + entry_ + from_utf8("\". ");
1457 // Split the string into its main constituents: terms, and command (see, see also, range).
1458 size_t positionVerticalBar = entry_.find(from_ascii("|")); // What comes before | is (sub)(sub)entries.
1459 docstring indexTerms = entry_.substr(0, positionVerticalBar);
1461 if (positionVerticalBar != lyx::docstring::npos) {
1462 command = entry_.substr(positionVerticalBar + 1);
1465 // Handle sorting issues, with @.
1466 vector<docstring> sortingElements = getVectorFromString(indexTerms, from_ascii("@"), false);
1467 if (sortingElements.size() == 2) {
1468 sort_as_ = sortingElements[0];
1469 indexTerms = sortingElements[1];
1472 // Handle entries, subentries, and subsubentries.
1473 terms_ = getVectorFromString(indexTerms, from_ascii("!"), false);
1475 // Handle ranges. Happily, (| and |) can only be at the end of the string!
1476 has_start_range_ = entry_.find(from_ascii("|(")) != lyx::docstring::npos;
1477 has_end_range_ = entry_.find(from_ascii("|)")) != lyx::docstring::npos;
1479 // - Remove the ranges from the command if they do not appear at the beginning.
1480 size_t range_index = 0;
1481 while ((range_index = command.find(from_utf8("|("), range_index)) != std::string::npos)
1482 command.erase(range_index, 1);
1484 while ((range_index = command.find(from_utf8("|)"), range_index)) != std::string::npos)
1485 command.erase(range_index, 1);
1487 // - Remove the ranges when they are the only vertical bar in the complete string.
1488 if (command[0] == '(' || command[0] == ')')
1489 command.erase(0, 1);
1491 // Handle see and seealso. As "see" is a prefix of "seealso", the order of the comparisons is important.
1492 // Both commands are mutually exclusive!
1493 if (command.substr(0, 3) == "see") {
1494 // Unescape brackets.
1495 size_t index_argument_begin = 0;
1496 while ((index_argument_begin = command.find(from_utf8("\\{"), index_argument_begin)) != std::string::npos)
1497 command.erase(index_argument_begin, 1);
1498 size_t index_argument_end = 0;
1499 while ((index_argument_end = command.find(from_utf8("\\}"), index_argument_end)) != std::string::npos)
1500 command.erase(index_argument_end, 1);
1502 // Retrieve the part between brackets, and remove the complete seealso.
1503 size_t position_opening_bracket = command.find(from_ascii("{"));
1504 size_t position_closing_bracket = command.find(from_ascii("}"));
1505 docstring argument = command.substr(position_opening_bracket + 1,
1506 position_closing_bracket - position_opening_bracket - 1);
1508 // Parse the argument of referenced entries (or a single one for see).
1509 if (command.substr(0, 7) == "seealso") {
1510 see_alsoes_ = getVectorFromString(argument, from_ascii(","), false);
1514 if (see_.find(from_ascii(",")) != std::string::npos) {
1515 output_error_ += from_utf8("Several index_argument_end terms found as \"see\"! Only one is "
1516 "acceptable. Complete entry: \"") + entry_ + from_utf8("\". ");
1520 // Remove the complete see/seealso from the commands, in case there is something else to parse.
1521 command = command.substr(position_closing_bracket + 1);
1524 // Some parts of the strings are not parsed, as they do not have anything matching in DocBook or XHTML:
1525 // things like formatting the entry or the page number, other strings for sorting.
1526 // https://wiki.lyx.org/Tips/Indexing
1527 // If there are such things in the index entry, then this code may miserably fail. For example, for
1528 // "Peter|(textbf", no range will be detected.
1529 if (!command.empty()) {
1530 output_error_ += from_utf8("Unsupported feature: an index entry contains a | with an unsupported command, ")
1531 + command + from_utf8(". Complete entry: \"") + entry_ + from_utf8("\". ");
1537 return terms_.size();
1540 const std::vector<docstring>& terms() const {
1544 std::vector<docstring>& terms() {
1548 const InsetIndex* inset() const {
1553 // Input inset. These should only be used when parsing the inset (either parseAsModern or parseAsLegacy, called in
1554 // the constructor).
1555 const InsetIndex * inset_;
1556 OutputParams const * runparams_;
1558 docstring index_; // Useful when there are multiple indices in the same document.
1560 // Errors, concatenated as a single string, available as soon as parsing is done, const afterwards (i.e. once
1561 // constructor is done).
1562 docstring output_error_;
1564 // Parsed index entry.
1565 std::vector<docstring> terms_; // Up to three entries, in general.
1568 bool has_start_range_;
1569 bool has_end_range_;
1571 vector<docstring> see_alsoes_;
1573 // Operators used for sorting entries (alphabetical order).
1574 friend bool operator<(IndexEntry const & lhs, IndexEntry const & rhs);
1577 bool operator<(IndexEntry const & lhs, IndexEntry const & rhs)
1579 if (lhs.terms_.empty())
1582 for (unsigned i = 0; i < min(rhs.terms_.size(), lhs.terms_.size()); ++i) {
1583 int comp = compare_no_case(lhs.terms_[i], rhs.terms_[i]);
1592 std::string generateCssClassAtDepth(unsigned depth) {
1593 std::string css_class = "entry";
1597 css_class.insert(0, "sub");
1604 std::vector<IndexEntry> entries;
1605 std::vector<IndexNode*> children;
1608 docstring termAtLevel(const IndexNode* node, unsigned depth)
1610 // 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
1611 // function could be made constant time by copying the term in each node, but that would make data duplication that
1612 // may fall out of sync; the performance benefit would probably be negligible.
1613 if (!node->entries.empty()) {
1614 LASSERT(node->entries.begin()->terms().size() >= depth + 1, return from_ascii(""));
1615 return node->entries.begin()->terms()[depth];
1618 if (!node->children.empty()) {
1619 return termAtLevel(*node->children.begin(), depth);
1622 LASSERT(false, return from_ascii(""));
1625 void insertIntoNode(const IndexEntry& entry, IndexNode* node, unsigned depth = 0)
1627 // depth == 0 is for the root, not yet the index, hence the increase when going to vector size.
1628 for (IndexNode* child : node->children) {
1629 if (entry.terms()[depth] == termAtLevel(child, depth)) {
1630 if (depth + 1 == entry.terms().size()) { // == child.entries.begin()->terms().size()
1631 // All term entries match: it's an entry.
1632 child->entries.emplace_back(entry);
1635 insertIntoNode(entry, child, depth + 1);
1641 // Out of the loop: no matching child found, create a new (possibly nested) child for this entry. Due to the
1642 // possibility of nestedness, only insert the current entry when the right level is reached. This is needed if the
1643 // first entry for a word has several levels that never appeared.
1644 // In particular, this case is called for the first entry.
1645 IndexNode* new_node = node;
1647 new_node->children.emplace_back(new IndexNode{{}, {}});
1648 new_node = new_node->children.back();
1650 } while (depth + 1 <= entry.terms().size()); // depth == 0: root node, no text associated.
1651 new_node->entries.emplace_back(entry);
1654 IndexNode* buildIndexTree(vector<IndexEntry>& entries)
1656 // Sort the entries, first on the main entry, then the subentry, then the subsubentry,
1657 // thanks to the implementation of operator<.
1658 // If this operation is not performed, the algorithm below is no more correct (and ensuring that it works with
1659 // unsorted entries would make its complexity blow up).
1660 stable_sort(entries.begin(), entries.end());
1662 // Cook the index into a nice tree data structure: entries at a given level in the index as a node, with subentries
1664 auto* index_root = new IndexNode{{}, {}};
1665 for (const IndexEntry& entry : entries) {
1666 insertIntoNode(entry, index_root);
1672 void outputIndexPage(XMLStream & xs, const IndexNode* root_node, unsigned depth = 0) // NOLINT(misc-no-recursion)
1674 LASSERT(root_node->entries.size() + root_node->children.size() > 0, return);
1676 xs << xml::StartTag("li", "class='" + generateCssClassAtDepth(depth) + "'");
1678 xs << XMLStream::ESCAPE_NONE << termAtLevel(root_node, depth);
1679 // By tree assumption, all the entries at this node have the same set of terms.
1681 if (!root_node->entries.empty()) {
1682 xs << XMLStream::ESCAPE_NONE << " — "; // Em dash, i.e. long (---).
1683 unsigned entry_number = 1;
1685 auto writeLinkToEntry = [&xs](const IndexEntry &entry, unsigned entry_number) {
1686 std::string const link_attr = "href='#" + entry.inset()->paragraphs()[0].magicLabel() + "'";
1687 xs << xml::StartTag("a", link_attr);
1688 xs << from_ascii(std::to_string(entry_number));
1689 xs << xml::EndTag("a");
1692 for (unsigned i = 0; i < root_node->entries.size(); ++i) {
1693 const IndexEntry &entry = root_node->entries[i];
1695 switch (entry.inset()->params().range) {
1696 case InsetIndexParams::PageRange::None:
1697 writeLinkToEntry(entry, entry_number);
1699 case InsetIndexParams::PageRange::Start: {
1700 // Try to find the end of the range, if it is just after. Otherwise, the output will be slightly
1701 // scrambled, but understandable. Doing better would mean implementing more of the indexing logic here
1702 // and more complex indexing here (skipping the end is not just incrementing i). Worst case output:
1704 const bool nextEntryIsEnd = i + 1 < root_node->entries.size() &&
1705 root_node->entries[i + 1].inset()->params().range ==
1706 InsetIndexParams::PageRange::End;
1707 // No need to check if both entries are for the same terms: they are in the same IndexNode.
1709 writeLinkToEntry(entry, entry_number);
1710 xs << XMLStream::ESCAPE_NONE << " – "; // En dash, i.e. semi-long (--).
1712 if (nextEntryIsEnd) {
1713 // Skip the next entry in the loop, write it right now, after the dash.
1716 writeLinkToEntry(root_node->entries[i], entry_number);
1720 case InsetIndexParams::PageRange::End:
1721 // This range end was not caught by the range start, do it now to avoid losing content.
1722 xs << XMLStream::ESCAPE_NONE << " – "; // En dash, i.e. semi-long (--).
1723 writeLinkToEntry(root_node->entries[i], entry_number);
1726 if (i < root_node->entries.size() - 1) {
1733 if (!root_node->entries.empty() && !root_node->children.empty()) {
1737 if (!root_node->children.empty()) {
1738 xs << xml::StartTag("ul", "class='" + generateCssClassAtDepth(depth) + "'");
1741 for (const IndexNode* child : root_node->children) {
1742 outputIndexPage(xs, child, depth + 1);
1745 xs << xml::EndTag("ul");
1749 xs << xml::EndTag("li");
1753 #ifdef LYX_INSET_INDEX_DEBUG
1754 void printTree(const IndexNode* root_node, unsigned depth = 0)
1756 static const std::string pattern = " ";
1758 for (unsigned i = 0; i < depth; ++i) {
1761 const std::string prefix_long = prefix + pattern + pattern;
1763 docstring term_at_level;
1765 // The root has no term.
1766 std::cout << "<ROOT>" << std::endl;
1768 LASSERT(depth - 1 <= 10, return); // Check for overflows.
1769 term_at_level = termAtLevel(root_node, depth - 1);
1770 std::cout << prefix << to_utf8(term_at_level) << " (x " << std::to_string(root_node->entries.size()) << ")"
1774 for (const IndexEntry& entry : root_node->entries) {
1775 if (entry.terms().size() != depth) {
1776 std::cout << prefix_long << "ERROR: an entry doesn't have the same number of terms" << std::endl;
1778 if (depth > 0 && entry.terms()[depth - 1] != term_at_level) {
1779 std::cout << prefix_long << "ERROR: an entry doesn't have the right term at depth " << std::to_string(depth)
1784 for (const IndexNode* node : root_node->children) {
1785 printTree(node, depth + 1);
1788 #endif // LYX_INSET_INDEX_DEBUG
1792 docstring InsetPrintIndex::xhtml(XMLStream &, OutputParams const & op) const
1794 BufferParams const & bp = buffer().masterBuffer()->params();
1796 shared_ptr<Toc const> toc = buffer().tocBackend().toc("index");
1800 // Collect the index entries in a form we can use them.
1801 vector<IndexEntry> entries;
1802 const docstring & indexType = params().getParamOr("type", from_ascii("idx"));
1803 for (const TocItem& item : *toc) {
1804 const auto* inset = static_cast<const InsetIndex*>(&(item.dit().inset()));
1805 if (item.isOutput() && inset->params().index == indexType)
1806 entries.emplace_back(IndexEntry{inset, &op});
1809 // If all the index entries are in notes or not displayed, get out sooner.
1810 if (entries.empty())
1813 const IndexNode* index_root = buildIndexTree(entries);
1814 #ifdef LYX_INSET_INDEX_DEBUG
1815 printTree(index_root);
1818 // Start generating the XHTML index.
1819 Layout const & lay = bp.documentClass().htmlTOCLayout();
1820 string const & tocclass = lay.defaultCSSClass();
1821 string const tocattr = "class='index " + tocclass + "'";
1822 docstring const indexName = params().getParamOr("name", from_ascii("Index"));
1824 // we'll use our own stream, because we are going to defer everything.
1825 // that's how we deal with the fact that we're probably inside a standard
1826 // paragraph, and we don't want to be.
1827 odocstringstream ods;
1830 xs << xml::StartTag("div", tocattr);
1832 xs << xml::StartTag(lay.htmltag(), lay.htmlattr());
1833 xs << translateIfPossible(indexName, op.local_font->language()->lang());
1834 xs << xml::EndTag(lay.htmltag());
1836 xs << xml::StartTag("ul", "class='main'");
1839 LASSERT(index_root->entries.empty(), return docstring()); // No index entry should have zero terms.
1840 for (const IndexNode* node : index_root->children) {
1841 outputIndexPage(xs, node);
1844 xs << xml::EndTag("ul");
1846 xs << xml::EndTag("div");