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 if (cmd.getArg(0) == "changeparam") {
586 string const p = cmd.getArg(1);
587 string const v = cmd.getArg(2);
588 cur.recordUndoInset(this);
590 params_.range = insetindexpagerangetranslator().find(v);
591 if (p == "pagefmt") {
592 if (v == "default" || v == "textbf"
593 || v == "textit" || v == "emph")
596 lyx::dispatch(FuncRequest(LFUN_INSET_SETTINGS, "index"));
600 InsetIndexParams params;
601 InsetIndex::string2params(to_utf8(cmd.argument()), params);
602 cur.recordUndoInset(this);
603 params_.index = params.index;
604 params_.range = params.range;
605 params_.pagefmt = params.pagefmt;
606 // what we really want here is a TOC update, but that means
607 // a full buffer update
608 cur.forceBufferUpdate();
612 case LFUN_INSET_DIALOG_UPDATE:
613 cur.bv().updateDialog("index", params2string(params_));
616 case LFUN_PARAGRAPH_BREAK: {
617 // Since this inset in single-par anyway, let's use
618 // return to enter subentries
619 FuncRequest fr(LFUN_INDEXMACRO_INSERT, "subentry");
625 InsetCollapsible::doDispatch(cur, cmd);
631 bool InsetIndex::getStatus(Cursor & cur, FuncRequest const & cmd,
632 FuncStatus & flag) const
634 switch (cmd.action()) {
636 case LFUN_INSET_MODIFY:
637 if (cmd.getArg(0) == "changetype") {
638 docstring const newtype = from_utf8(cmd.getArg(1));
639 Buffer const & realbuffer = *buffer().masterBuffer();
640 IndicesList const & indiceslist = realbuffer.params().indiceslist();
641 Index const * index = indiceslist.findShortcut(newtype);
642 flag.setEnabled(index != 0);
644 from_utf8(cmd.getArg(1)) == params_.index);
647 if (cmd.getArg(0) == "changeparam") {
648 string const p = cmd.getArg(1);
649 string const v = cmd.getArg(2);
651 flag.setEnabled(v == "none" || v == "start" || v == "end");
652 flag.setOnOff(params_.range == insetindexpagerangetranslator().find(v));
654 if (p == "pagefmt") {
655 flag.setEnabled(!v.empty());
656 if (params_.pagefmt == "default" || params_.pagefmt == "textbf"
657 || params_.pagefmt == "textit" || params_.pagefmt == "emph")
658 flag.setOnOff(params_.pagefmt == v);
660 flag.setOnOff(v == "custom");
664 return InsetCollapsible::getStatus(cur, cmd, flag);
666 case LFUN_INSET_DIALOG_UPDATE: {
667 Buffer const & realbuffer = *buffer().masterBuffer();
668 flag.setEnabled(realbuffer.params().use_indices);
672 case LFUN_PARAGRAPH_BREAK:
673 return macrosPossible("subentry");
675 case LFUN_INDEXMACRO_INSERT:
676 return macrosPossible(cmd.getArg(0));
679 return InsetCollapsible::getStatus(cur, cmd, flag);
684 void InsetIndex::getSortkey(otexstream & os, OutputParams const & runparams) const
686 Paragraph const & par = paragraphs().front();
687 InsetList::const_iterator it = par.insetList().begin();
688 for (; it != par.insetList().end(); ++it) {
689 Inset & inset = *it->inset;
690 if (inset.lyxCode() == INDEXMACRO_SORTKEY_CODE) {
691 InsetIndexMacro const & iim =
692 static_cast<InsetIndexMacro const &>(inset);
693 iim.getLatex(os, runparams);
700 docstring InsetIndex::getSortkeyAsText(OutputParams const & runparams) const
702 Paragraph const & par = paragraphs().front();
703 InsetList::const_iterator it = par.insetList().begin();
704 for (; it != par.insetList().end(); ++it) {
705 Inset & inset = *it->inset;
706 if (inset.lyxCode() == INDEXMACRO_SORTKEY_CODE) {
708 InsetIndexMacro const & iim =
709 static_cast<InsetIndexMacro const &>(inset);
710 iim.getLatex(os, runparams);
714 return from_ascii("");
718 void InsetIndex::emptySubentriesWarning(docstring const & mainentry) const
720 // Empty subentries crash makeindex. So warn and ignore this.
722 ErrorList & errorList = buffer().errorList("Export");
723 docstring const s = bformat(_("There is an empty index subentry in the entry '%1$s'.\n"
724 "It will be ignored in the output."), mainentry);
725 Paragraph const & par = buffer().paragraphs().front();
726 errorList.push_back(ErrorItem(_("Empty index subentry!"), s,
727 {par.id(), 0}, {par.id(), -1}));
728 buffer().bufferErrors(terr, errorList);
732 void InsetIndex::getSubentries(otexstream & os, OutputParams const & runparams,
733 docstring const & mainentry) const
735 Paragraph const & par = paragraphs().front();
736 InsetList::const_iterator it = par.insetList().begin();
738 for (; it != par.insetList().end(); ++it) {
739 Inset & inset = *it->inset;
740 if (inset.lyxCode() == INDEXMACRO_CODE) {
741 InsetIndexMacro const & iim =
742 static_cast<InsetIndexMacro const &>(inset);
743 if (iim.params().type == InsetIndexMacroParams::Subentry) {
744 if (iim.hasNoContent()) {
745 emptySubentriesWarning(mainentry);
752 iim.getLatex(os, runparams);
759 std::vector<docstring> InsetIndex::getSubentriesAsText(OutputParams const & runparams,
760 bool const asLabel) const
762 std::vector<docstring> subentries;
764 Paragraph const & par = paragraphs().front();
765 InsetList::const_iterator it = par.insetList().begin();
767 for (; it != par.insetList().end(); ++it) {
768 Inset & inset = *it->inset;
769 if (inset.lyxCode() == INDEXMACRO_CODE) {
770 InsetIndexMacro const & iim =
771 static_cast<InsetIndexMacro const &>(inset);
772 if (iim.params().type == InsetIndexMacroParams::Subentry) {
778 docstring const sl = iim.getNewLabel(l);
779 subentries.emplace_back(sl);
782 iim.getLatex(os, runparams);
783 subentries.emplace_back(os.str());
793 docstring InsetIndex::getMainSubentryAsText(OutputParams const & runparams) const
796 InsetText::latex(os, runparams);
801 void InsetIndex::getSeeRefs(otexstream & os, OutputParams const & runparams) const
803 Paragraph const & par = paragraphs().front();
804 InsetList::const_iterator it = par.insetList().begin();
805 for (; it != par.insetList().end(); ++it) {
806 Inset & inset = *it->inset;
807 if (inset.lyxCode() == INDEXMACRO_CODE) {
808 InsetIndexMacro const & iim =
809 static_cast<InsetIndexMacro const &>(inset);
810 if (iim.params().type == InsetIndexMacroParams::See
811 || iim.params().type == InsetIndexMacroParams::Seealso) {
812 iim.getLatex(os, runparams);
820 docstring InsetIndex::getSeeAsText(OutputParams const & runparams,
821 bool const asLabel) const
823 Paragraph const & par = paragraphs().front();
824 InsetList::const_iterator it = par.insetList().begin();
825 for (; it != par.insetList().end(); ++it) {
826 Inset & inset = *it->inset;
827 if (inset.lyxCode() == INDEXMACRO_CODE) {
828 InsetIndexMacro const & iim =
829 static_cast<InsetIndexMacro const &>(inset);
830 if (iim.params().type == InsetIndexMacroParams::See) {
833 return iim.getNewLabel(l);
836 iim.getLatex(os, runparams);
842 return from_ascii("");
846 std::vector<docstring> InsetIndex::getSeeAlsoesAsText(OutputParams const & runparams,
847 bool const asLabel) const
849 std::vector<docstring> seeAlsoes;
851 Paragraph const & par = paragraphs().front();
852 InsetList::const_iterator it = par.insetList().begin();
853 for (; it != par.insetList().end(); ++it) {
854 Inset & inset = *it->inset;
855 if (inset.lyxCode() == INDEXMACRO_CODE) {
856 InsetIndexMacro const & iim =
857 static_cast<InsetIndexMacro const &>(inset);
858 if (iim.params().type == InsetIndexMacroParams::Seealso) {
861 seeAlsoes.emplace_back(iim.getNewLabel(l));
864 iim.getLatex(os, runparams);
865 seeAlsoes.emplace_back(os.str());
877 bool hasInsetWithCode(const InsetIndex * const inset_index, const InsetCode code,
878 const std::set<InsetIndexMacroParams::Type> types = {})
880 Paragraph const & par = inset_index->paragraphs().front();
881 InsetList::const_iterator it = par.insetList().begin();
882 for (; it != par.insetList().end(); ++it) {
883 Inset & inset = *it->inset;
884 if (inset.lyxCode() == code) {
888 LASSERT(code == INDEXMACRO_CODE, return false);
889 InsetIndexMacro const & iim =
890 static_cast<InsetIndexMacro const &>(inset);
891 if (types.find(iim.params().type) != types.end())
901 bool InsetIndex::hasSubentries() const
903 return hasInsetWithCode(this, INDEXMACRO_CODE, {InsetIndexMacroParams::Subentry});
907 bool InsetIndex::hasSeeRef() const
909 return hasInsetWithCode(this, INDEXMACRO_CODE, {InsetIndexMacroParams::See, InsetIndexMacroParams::Seealso});
913 bool InsetIndex::hasSortKey() const
915 return hasInsetWithCode(this, INDEXMACRO_SORTKEY_CODE);
919 bool InsetIndex::macrosPossible(string const type) const
921 if (type != "see" && type != "seealso"
922 && type != "sortkey" && type != "subentry")
925 Paragraph const & par = paragraphs().front();
926 InsetList::const_iterator it = par.insetList().begin();
928 for (; it != par.insetList().end(); ++it) {
929 Inset & inset = *it->inset;
930 if (type == "sortkey" && inset.lyxCode() == INDEXMACRO_SORTKEY_CODE)
932 if (inset.lyxCode() == INDEXMACRO_CODE) {
933 InsetIndexMacro const & iim = static_cast<InsetIndexMacro const &>(inset);
934 if ((type == "see" || type == "seealso")
935 && (iim.params().type == InsetIndexMacroParams::See
936 || iim.params().type == InsetIndexMacroParams::Seealso))
938 if (type == "subentry"
939 && iim.params().type == InsetIndexMacroParams::Subentry) {
950 ColorCode InsetIndex::labelColor() const
952 if (params_.index.empty() || params_.index == from_ascii("idx"))
953 return InsetCollapsible::labelColor();
955 ColorCode c = lcolor.getFromLyXName(to_utf8(params_.index)
956 + "@" + buffer().fileName().absFileName());
958 c = InsetCollapsible::labelColor();
963 docstring InsetIndex::toolTip(BufferView const &, int, int) const
965 docstring tip = _("Index Entry");
966 if (buffer().params().use_indices && !params_.index.empty()) {
967 Buffer const & realbuffer = *buffer().masterBuffer();
968 IndicesList const & indiceslist = realbuffer.params().indiceslist();
970 Index const * index = indiceslist.findShortcut(params_.index);
972 tip += _("unknown type!");
974 tip += index->index();
978 docstring res = toolTipText(tip);
979 if (!insetindexpagerangetranslator_loc().find(params_.range).empty())
980 res += "\n" + insetindexpagerangetranslator_loc().find(params_.range);
981 if (!params_.pagefmt.empty() && params_.pagefmt != "default") {
982 res += "\n" + _("Pagination format:") + " ";
983 if (params_.pagefmt == "textbf")
985 else if (params_.pagefmt == "textit")
987 else if (params_.pagefmt == "emph")
988 res += _("emphasized");
990 res += from_utf8(params_.pagefmt);
996 docstring const InsetIndex::buttonLabel(BufferView const & bv) const
998 InsetLayout const & il = getLayout();
999 docstring label = translateIfPossible(il.labelstring());
1001 if (buffer().params().use_indices && !params_.index.empty()) {
1002 Buffer const & realbuffer = *buffer().masterBuffer();
1003 IndicesList const & indiceslist = realbuffer.params().indiceslist();
1005 Index const * index = indiceslist.findShortcut(params_.index);
1007 label += _("unknown type!");
1009 label += index->index();
1014 if (!il.contentaslabel() || geometry(bv) != ButtonOnly)
1017 res = getNewLabel(label);
1018 OutputParams const rp(0);
1019 vector<docstring> sublbls = getSubentriesAsText(rp, true);
1020 for (auto const & sublbl : sublbls) {
1021 res += " " + docstring(1, char_type(0x2023));// TRIANGULAR BULLET
1022 res += " " + sublbl;
1024 docstring see = getSeeAsText(rp, true);
1025 if (see.empty() && !getSeeAlsoesAsText(rp, true).empty())
1026 see = getSeeAlsoesAsText(rp, true).front();
1028 res += " " + docstring(1, char_type(0x261e));// WHITE RIGHT POINTING INDEX
1032 if (!insetindexpagerangetranslator_latex().find(params_.range).empty())
1033 res += " " + from_ascii(insetindexpagerangetranslator_latex().find(params_.range));
1038 void InsetIndex::write(ostream & os) const
1040 os << to_utf8(layoutName());
1042 InsetCollapsible::write(os);
1046 void InsetIndex::read(Lexer & lex)
1049 InsetCollapsible::read(lex);
1053 string InsetIndex::params2string(InsetIndexParams const & params)
1062 void InsetIndex::string2params(string const & in, InsetIndexParams & params)
1064 params = InsetIndexParams();
1068 istringstream data(in);
1070 lex.setStream(data);
1071 lex.setContext("InsetIndex::string2params");
1077 void InsetIndex::addToToc(DocIterator const & cpit, bool output_active,
1078 UpdateType utype, TocBackend & backend) const
1080 DocIterator pit = cpit;
1081 pit.push_back(CursorSlice(const_cast<InsetIndex &>(*this)));
1083 InsetLayout const & il = getLayout();
1084 docstring label = translateIfPossible(il.labelstring());
1085 if (!il.contentaslabel())
1088 str = getNewLabel(label);
1089 OutputParams const rp(0);
1090 vector<docstring> sublbls = getSubentriesAsText(rp, true);
1091 for (auto const & sublbl : sublbls) {
1092 str += " " + docstring(1, char_type(0x2023));// TRIANGULAR BULLET
1093 str += " " + sublbl;
1095 docstring see = getSeeAsText(rp, true);
1096 if (see.empty() && !getSeeAlsoesAsText(rp, true).empty())
1097 see = getSeeAlsoesAsText(rp, true).front();
1099 str += " " + docstring(1, char_type(0x261e));// WHITE RIGHT POINTING INDEX
1103 string type = "index";
1104 if (buffer().masterBuffer()->params().use_indices)
1105 type += ":" + to_utf8(params_.index);
1106 TocBuilder & b = backend.builder(type);
1107 b.pushItem(pit, str, output_active);
1108 // Proceed with the rest of the inset.
1109 InsetCollapsible::addToToc(cpit, output_active, utype, backend);
1114 void InsetIndex::validate(LaTeXFeatures & features) const
1116 if (buffer().masterBuffer()->params().use_indices
1117 && !params_.index.empty()
1118 && params_.index != "idx")
1119 features.require("splitidx");
1120 InsetCollapsible::validate(features);
1124 string InsetIndex::contextMenuName() const
1126 return "context-index";
1130 string InsetIndex::contextMenu(BufferView const & bv, int x, int y) const
1132 // We override the implementation of InsetCollapsible,
1133 // because we have eytra entries.
1134 string owncm = "context-edit-index;";
1135 return owncm + InsetCollapsible::contextMenu(bv, x, y);
1139 bool InsetIndex::hasSettings() const
1145 bool InsetIndex::insetAllowed(InsetCode code) const
1148 case INDEXMACRO_CODE:
1149 case INDEXMACRO_SORTKEY_CODE:
1154 return InsetCollapsible::insetAllowed(code);
1159 /////////////////////////////////////////////////////////////////////
1163 ///////////////////////////////////////////////////////////////////////
1166 void InsetIndexParams::write(ostream & os) const
1170 os << to_utf8(index);
1175 << insetindexpagerangetranslator().find(range)
1183 void InsetIndexParams::read(Lexer & lex)
1186 index = lex.getDocString();
1188 index = from_ascii("idx");
1189 if (lex.checkFor("range")) {
1190 string st = lex.getString();
1191 if (lex.eatLine()) {
1192 st = lex.getString();
1193 range = insetindexpagerangetranslator().find(lex.getString());
1196 if (lex.checkFor("pageformat") && lex.eatLine()) {
1197 pagefmt = lex.getString();
1202 /////////////////////////////////////////////////////////////////////
1206 ///////////////////////////////////////////////////////////////////////
1208 InsetPrintIndex::InsetPrintIndex(Buffer * buf, InsetCommandParams const & p)
1209 : InsetCommand(buf, p)
1213 ParamInfo const & InsetPrintIndex::findInfo(string const & /* cmdName */)
1215 static ParamInfo param_info_;
1216 if (param_info_.empty()) {
1217 param_info_.add("type", ParamInfo::LATEX_OPTIONAL,
1218 ParamInfo::HANDLING_ESCAPE);
1219 param_info_.add("name", ParamInfo::LATEX_OPTIONAL,
1220 ParamInfo::HANDLING_LATEXIFY);
1221 param_info_.add("literal", ParamInfo::LYX_INTERNAL);
1227 docstring InsetPrintIndex::screenLabel() const
1229 bool const printall = suffixIs(getCmdName(), '*');
1230 bool const multind = buffer().masterBuffer()->params().use_indices;
1232 && getParam("type") == from_ascii("idx"))
1233 || (getParam("type").empty() && !printall))
1235 Buffer const & realbuffer = *buffer().masterBuffer();
1236 IndicesList const & indiceslist = realbuffer.params().indiceslist();
1237 Index const * index = indiceslist.findShortcut(getParam("type"));
1238 if (!index && !printall)
1239 return _("Unknown index type!");
1240 docstring res = printall ? _("All indexes") : index->index();
1242 res += " (" + _("non-active") + ")";
1243 else if (contains(getCmdName(), "printsubindex"))
1244 res += " (" + _("subindex") + ")";
1249 bool InsetPrintIndex::isCompatibleCommand(string const & s)
1251 return s == "printindex" || s == "printsubindex"
1252 || s == "printindex*" || s == "printsubindex*";
1256 void InsetPrintIndex::doDispatch(Cursor & cur, FuncRequest & cmd)
1258 switch (cmd.action()) {
1260 case LFUN_INSET_MODIFY: {
1261 if (cmd.argument() == from_ascii("toggle-subindex")) {
1262 string scmd = getCmdName();
1263 if (contains(scmd, "printindex"))
1264 scmd = subst(scmd, "printindex", "printsubindex");
1266 scmd = subst(scmd, "printsubindex", "printindex");
1270 } else if (cmd.argument() == from_ascii("check-printindex*")) {
1271 string scmd = getCmdName();
1272 if (suffixIs(scmd, '*'))
1276 setParam("type", docstring());
1280 InsetCommandParams p(INDEX_PRINT_CODE);
1282 InsetCommand::string2params(to_utf8(cmd.argument()), p);
1283 if (p.getCmdName().empty()) {
1284 cur.noScreenUpdate();
1293 InsetCommand::doDispatch(cur, cmd);
1299 bool InsetPrintIndex::getStatus(Cursor & cur, FuncRequest const & cmd,
1300 FuncStatus & status) const
1302 switch (cmd.action()) {
1304 case LFUN_INSET_MODIFY: {
1305 if (cmd.argument() == from_ascii("toggle-subindex")) {
1306 status.setEnabled(buffer().masterBuffer()->params().use_indices);
1307 status.setOnOff(contains(getCmdName(), "printsubindex"));
1309 } else if (cmd.argument() == from_ascii("check-printindex*")) {
1310 status.setEnabled(buffer().masterBuffer()->params().use_indices);
1311 status.setOnOff(suffixIs(getCmdName(), '*'));
1313 } if (cmd.getArg(0) == "index_print"
1314 && cmd.getArg(1) == "CommandInset") {
1315 InsetCommandParams p(INDEX_PRINT_CODE);
1316 InsetCommand::string2params(to_utf8(cmd.argument()), p);
1317 if (suffixIs(p.getCmdName(), '*')) {
1318 status.setEnabled(true);
1319 status.setOnOff(false);
1322 Buffer const & realbuffer = *buffer().masterBuffer();
1323 IndicesList const & indiceslist =
1324 realbuffer.params().indiceslist();
1325 Index const * index = indiceslist.findShortcut(p["type"]);
1326 status.setEnabled(index != 0);
1327 status.setOnOff(p["type"] == getParam("type"));
1330 return InsetCommand::getStatus(cur, cmd, status);
1333 case LFUN_INSET_DIALOG_UPDATE: {
1334 status.setEnabled(buffer().masterBuffer()->params().use_indices);
1339 return InsetCommand::getStatus(cur, cmd, status);
1344 void InsetPrintIndex::updateBuffer(ParIterator const &, UpdateType, bool const /*deleted*/)
1346 Index const * index =
1347 buffer().masterParams().indiceslist().findShortcut(getParam("type"));
1349 setParam("name", index->index());
1353 void InsetPrintIndex::latex(otexstream & os, OutputParams const & runparams_in) const
1355 if (!buffer().masterBuffer()->params().use_indices) {
1356 if (getParam("type") == from_ascii("idx"))
1357 os << "\\printindex" << termcmd;
1360 OutputParams runparams = runparams_in;
1361 os << getCommand(runparams);
1365 void InsetPrintIndex::validate(LaTeXFeatures & features) const
1367 features.require("makeidx");
1368 if (buffer().masterBuffer()->params().use_indices)
1369 features.require("splitidx");
1370 InsetCommand::validate(features);
1374 string InsetPrintIndex::contextMenuName() const
1376 return buffer().masterBuffer()->params().use_indices ?
1377 "context-indexprint" : string();
1381 bool InsetPrintIndex::hasSettings() const
1383 return buffer().masterBuffer()->params().use_indices;
1390 /// Builds an entry for the index.
1391 IndexEntry(const InsetIndex * inset, OutputParams const * runparams) : inset_(inset), runparams_(runparams)
1393 LASSERT(runparams, return);
1395 // Convert the inset as text. The resulting text usually only contains an XHTML anchor (<a id='...'/>) and text.
1396 odocstringstream entry;
1397 OutputParams ours = *runparams;
1398 ours.for_toc = false;
1399 inset_->plaintext(entry, ours);
1400 entry_ = entry.str();
1402 // Determine in which index this entry belongs to.
1403 if (inset_->buffer().masterBuffer()->params().use_indices) {
1404 index_ = inset_->params_.index;
1407 // Attempt parsing the inset.
1414 /// When parsing this entry, some errors may be found; they are reported as a single string.
1415 // It is up to the caller to send this string to LYXERR and the output file, as needed.
1416 const docstring & output_error() const
1418 return output_error_;
1421 void output_error(XMLStream xs) const
1423 LYXERR0(output_error());
1424 xs << XMLStream::ESCAPE_NONE << (from_utf8("<!-- Output Error: ") + output_error() + from_utf8(" -->\n"));
1431 std::cout << to_utf8(entry_) << std::endl;
1433 // If a modern parameter is present, this is definitely a modern index inset. Similarly, if it contains the
1434 // usual LaTeX symbols (!|@), then it is definitely a legacy index inset. Otherwise, if it has features of
1435 // neither, it is both: consider this is a modern inset, to trigger the least complex code. Mixing both types
1436 // is not allowed (i.e. behaviour is undefined).
1437 const bool is_definitely_modern = inset_->hasSortKey() || inset_->hasSeeRef() || inset_->hasSubentries()
1438 || inset_->params_.range != InsetIndexParams::PageRange::None;
1439 const bool is_definitely_legacy = entry_.find('@') != std::string::npos
1440 || entry_.find('|') != std::string::npos || entry_.find('!') != std::string::npos;
1442 if (is_definitely_legacy && is_definitely_modern)
1443 output_error_ += from_utf8("Mix of index properties and raw LaTeX index commands is unsupported. ");
1446 // - is_definitely_modern == true:
1447 // - is_definitely_legacy == true: error (return whatever)
1448 // - is_definitely_legacy == false: return modern
1449 // - is_definitely_modern == false:
1450 // - is_definitely_legacy == true: return legacy
1451 // - is_definitely_legacy == false: return modern
1452 return !is_definitely_legacy;
1455 void parseAsModern()
1457 LASSERT(runparams_, return);
1459 if (inset_->hasSortKey()) {
1460 sort_as_ = inset_->getSortkeyAsText(*runparams_);
1463 terms_ = inset_->getSubentriesAsText(*runparams_);
1464 // The main term is not present in the vector, as it's not a subentry. The main index term is inserted raw in
1465 // the index inset. Considering that the user either uses the new or the legacy mechanism, the main term is the
1466 // full string within this inset (i.e. without the subinsets).
1467 terms_.insert(terms_.begin(), inset_->getMainSubentryAsText(*runparams_));
1469 has_start_range_ = inset_->params_.range == InsetIndexParams::PageRange::Start;
1470 has_end_range_ = inset_->params_.range == InsetIndexParams::PageRange::End;
1472 see_ = inset_->getSeeAsText(*runparams_);
1473 see_alsoes_ = inset_->getSeeAlsoesAsText(*runparams_);
1476 void parseAsLegacy() {
1477 // Determine if some features are known not to be supported. For now, this is only formatting like
1478 // \index{alpha@\textbf{alpha}} or \index{alpha@$\alpha$}.
1479 // @ is supported, but only for sorting, without specific formatting.
1480 if (entry_.find(from_utf8("@\\")) != lyx::docstring::npos) {
1481 output_error_ += from_utf8("Unsupported feature: an index entry contains an @\\. "
1482 "Complete entry: \"") + entry_ + from_utf8("\". ");
1484 if (entry_.find(from_utf8("@$")) != lyx::docstring::npos) {
1485 output_error_ += from_utf8("Unsupported feature: an index entry contains an @$. "
1486 "Complete entry: \"") + entry_ + from_utf8("\". ");
1489 // Split the string into its main constituents: terms, and command (see, see also, range).
1490 size_t positionVerticalBar = entry_.find(from_ascii("|")); // What comes before | is (sub)(sub)entries.
1491 docstring indexTerms = entry_.substr(0, positionVerticalBar);
1493 if (positionVerticalBar != lyx::docstring::npos) {
1494 command = entry_.substr(positionVerticalBar + 1);
1497 // Handle sorting issues, with @.
1498 vector<docstring> sortingElements = getVectorFromString(indexTerms, from_ascii("@"), false);
1499 if (sortingElements.size() == 2) {
1500 sort_as_ = sortingElements[0];
1501 indexTerms = sortingElements[1];
1504 // Handle entries, subentries, and subsubentries.
1505 terms_ = getVectorFromString(indexTerms, from_ascii("!"), false);
1507 // Handle ranges. Happily, (| and |) can only be at the end of the string!
1508 has_start_range_ = entry_.find(from_ascii("|(")) != lyx::docstring::npos;
1509 has_end_range_ = entry_.find(from_ascii("|)")) != lyx::docstring::npos;
1511 // - Remove the ranges from the command if they do not appear at the beginning.
1512 size_t range_index = 0;
1513 while ((range_index = command.find(from_utf8("|("), range_index)) != std::string::npos)
1514 command.erase(range_index, 1);
1516 while ((range_index = command.find(from_utf8("|)"), range_index)) != std::string::npos)
1517 command.erase(range_index, 1);
1519 // - Remove the ranges when they are the only vertical bar in the complete string.
1520 if (command[0] == '(' || command[0] == ')')
1521 command.erase(0, 1);
1523 // Handle see and seealso. As "see" is a prefix of "seealso", the order of the comparisons is important.
1524 // Both commands are mutually exclusive!
1525 if (command.substr(0, 3) == "see") {
1526 // Unescape brackets.
1527 size_t index_argument_begin = 0;
1528 while ((index_argument_begin = command.find(from_utf8("\\{"), index_argument_begin)) != std::string::npos)
1529 command.erase(index_argument_begin, 1);
1530 size_t index_argument_end = 0;
1531 while ((index_argument_end = command.find(from_utf8("\\}"), index_argument_end)) != std::string::npos)
1532 command.erase(index_argument_end, 1);
1534 // Retrieve the part between brackets, and remove the complete seealso.
1535 size_t position_opening_bracket = command.find(from_ascii("{"));
1536 size_t position_closing_bracket = command.find(from_ascii("}"));
1537 docstring argument = command.substr(position_opening_bracket + 1,
1538 position_closing_bracket - position_opening_bracket - 1);
1540 // Parse the argument of referenced entries (or a single one for see).
1541 if (command.substr(0, 7) == "seealso") {
1542 see_alsoes_ = getVectorFromString(argument, from_ascii(","), false);
1546 if (see_.find(from_ascii(",")) != std::string::npos) {
1547 output_error_ += from_utf8("Several index_argument_end terms found as \"see\"! Only one is "
1548 "acceptable. Complete entry: \"") + entry_ + from_utf8("\". ");
1552 // Remove the complete see/seealso from the commands, in case there is something else to parse.
1553 command = command.substr(position_closing_bracket + 1);
1556 // Some parts of the strings are not parsed, as they do not have anything matching in DocBook or XHTML:
1557 // things like formatting the entry or the page number, other strings for sorting.
1558 // https://wiki.lyx.org/Tips/Indexing
1559 // If there are such things in the index entry, then this code may miserably fail. For example, for
1560 // "Peter|(textbf", no range will be detected.
1561 if (!command.empty()) {
1562 output_error_ += from_utf8("Unsupported feature: an index entry contains a | with an unsupported command, ")
1563 + command + from_utf8(". Complete entry: \"") + entry_ + from_utf8("\". ");
1569 return terms_.size();
1572 const std::vector<docstring>& terms() const {
1576 std::vector<docstring>& terms() {
1580 const InsetIndex* inset() const {
1585 // Input inset. These should only be used when parsing the inset (either parseAsModern or parseAsLegacy, called in
1586 // the constructor).
1587 const InsetIndex * inset_;
1588 OutputParams const * runparams_;
1590 docstring index_; // Useful when there are multiple indices in the same document.
1592 // Errors, concatenated as a single string, available as soon as parsing is done, const afterwards (i.e. once
1593 // constructor is done).
1594 docstring output_error_;
1596 // Parsed index entry.
1597 std::vector<docstring> terms_; // Up to three entries, in general.
1600 bool has_start_range_;
1601 bool has_end_range_;
1603 vector<docstring> see_alsoes_;
1605 // Operators used for sorting entries (alphabetical order).
1606 friend bool operator<(IndexEntry const & lhs, IndexEntry const & rhs);
1609 bool operator<(IndexEntry const & lhs, IndexEntry const & rhs)
1611 if (lhs.terms_.empty())
1614 for (unsigned i = 0; i < min(rhs.terms_.size(), lhs.terms_.size()); ++i) {
1615 int comp = compare_no_case(lhs.terms_[i], rhs.terms_[i]);
1624 std::string generateCssClassAtDepth(unsigned depth) {
1625 std::string css_class = "entry";
1629 css_class.insert(0, "sub");
1636 std::vector<IndexEntry> entries;
1637 std::vector<IndexNode*> children;
1640 docstring termAtLevel(const IndexNode* node, unsigned depth)
1642 // 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
1643 // function could be made constant time by copying the term in each node, but that would make data duplication that
1644 // may fall out of sync; the performance benefit would probably be negligible.
1645 if (!node->entries.empty()) {
1646 LASSERT(node->entries.begin()->terms().size() >= depth + 1, return from_ascii(""));
1647 return node->entries.begin()->terms()[depth];
1650 if (!node->children.empty()) {
1651 return termAtLevel(*node->children.begin(), depth);
1654 LASSERT(false, return from_ascii(""));
1657 void insertIntoNode(const IndexEntry& entry, IndexNode* node, unsigned depth = 0)
1659 // depth == 0 is for the root, not yet the index, hence the increase when going to vector size.
1660 for (IndexNode* child : node->children) {
1661 if (entry.terms()[depth] == termAtLevel(child, depth)) {
1662 if (depth + 1 == entry.terms().size()) { // == child.entries.begin()->terms().size()
1663 // All term entries match: it's an entry.
1664 child->entries.emplace_back(entry);
1667 insertIntoNode(entry, child, depth + 1);
1673 // Out of the loop: no matching child found, create a new (possibly nested) child for this entry. Due to the
1674 // possibility of nestedness, only insert the current entry when the right level is reached. This is needed if the
1675 // first entry for a word has several levels that never appeared.
1676 // In particular, this case is called for the first entry.
1677 IndexNode* new_node = node;
1679 new_node->children.emplace_back(new IndexNode{{}, {}});
1680 new_node = new_node->children.back();
1682 } while (depth + 1 <= entry.terms().size()); // depth == 0: root node, no text associated.
1683 new_node->entries.emplace_back(entry);
1686 IndexNode* buildIndexTree(vector<IndexEntry>& entries)
1688 // Sort the entries, first on the main entry, then the subentry, then the subsubentry,
1689 // thanks to the implementation of operator<.
1690 // If this operation is not performed, the algorithm below is no more correct (and ensuring that it works with
1691 // unsorted entries would make its complexity blow up).
1692 stable_sort(entries.begin(), entries.end());
1694 // Cook the index into a nice tree data structure: entries at a given level in the index as a node, with subentries
1696 auto* index_root = new IndexNode{{}, {}};
1697 for (const IndexEntry& entry : entries) {
1698 insertIntoNode(entry, index_root);
1704 void outputIndexPage(XMLStream & xs, const IndexNode* root_node, unsigned depth = 0) // NOLINT(misc-no-recursion)
1706 LASSERT(root_node->entries.size() + root_node->children.size() > 0, return);
1708 xs << xml::StartTag("li", "class='" + generateCssClassAtDepth(depth) + "'");
1710 xs << XMLStream::ESCAPE_NONE << termAtLevel(root_node, depth);
1711 // By tree assumption, all the entries at this node have the same set of terms.
1713 if (!root_node->entries.empty()) {
1714 xs << XMLStream::ESCAPE_NONE << " — "; // Em dash, i.e. long (---).
1715 unsigned entry_number = 1;
1717 auto writeLinkToEntry = [&xs](const IndexEntry &entry, unsigned entry_number) {
1718 std::string const link_attr = "href='#" + entry.inset()->paragraphs()[0].magicLabel() + "'";
1719 xs << xml::StartTag("a", link_attr);
1720 xs << from_ascii(std::to_string(entry_number));
1721 xs << xml::EndTag("a");
1724 for (unsigned i = 0; i < root_node->entries.size(); ++i) {
1725 const IndexEntry &entry = root_node->entries[i];
1727 switch (entry.inset()->params().range) {
1728 case InsetIndexParams::PageRange::None:
1729 writeLinkToEntry(entry, entry_number);
1731 case InsetIndexParams::PageRange::Start: {
1732 // Try to find the end of the range, if it is just after. Otherwise, the output will be slightly
1733 // scrambled, but understandable. Doing better would mean implementing more of the indexing logic here
1734 // and more complex indexing here (skipping the end is not just incrementing i). Worst case output:
1736 const bool nextEntryIsEnd = i + 1 < root_node->entries.size() &&
1737 root_node->entries[i + 1].inset()->params().range ==
1738 InsetIndexParams::PageRange::End;
1739 // No need to check if both entries are for the same terms: they are in the same IndexNode.
1741 writeLinkToEntry(entry, entry_number);
1742 xs << XMLStream::ESCAPE_NONE << " – "; // En dash, i.e. semi-long (--).
1744 if (nextEntryIsEnd) {
1745 // Skip the next entry in the loop, write it right now, after the dash.
1748 writeLinkToEntry(root_node->entries[i], entry_number);
1752 case InsetIndexParams::PageRange::End:
1753 // This range end was not caught by the range start, do it now to avoid losing content.
1754 xs << XMLStream::ESCAPE_NONE << " – "; // En dash, i.e. semi-long (--).
1755 writeLinkToEntry(root_node->entries[i], entry_number);
1758 if (i < root_node->entries.size() - 1) {
1765 if (!root_node->entries.empty() && !root_node->children.empty()) {
1769 if (!root_node->children.empty()) {
1770 xs << xml::StartTag("ul", "class='" + generateCssClassAtDepth(depth) + "'");
1773 for (const IndexNode* child : root_node->children) {
1774 outputIndexPage(xs, child, depth + 1);
1777 xs << xml::EndTag("ul");
1781 xs << xml::EndTag("li");
1785 #ifdef LYX_INSET_INDEX_DEBUG
1786 void printTree(const IndexNode* root_node, unsigned depth = 0)
1788 static const std::string pattern = " ";
1790 for (unsigned i = 0; i < depth; ++i) {
1793 const std::string prefix_long = prefix + pattern + pattern;
1795 docstring term_at_level;
1797 // The root has no term.
1798 std::cout << "<ROOT>" << std::endl;
1800 LASSERT(depth - 1 <= 10, return); // Check for overflows.
1801 term_at_level = termAtLevel(root_node, depth - 1);
1802 std::cout << prefix << to_utf8(term_at_level) << " (x " << std::to_string(root_node->entries.size()) << ")"
1806 for (const IndexEntry& entry : root_node->entries) {
1807 if (entry.terms().size() != depth) {
1808 std::cout << prefix_long << "ERROR: an entry doesn't have the same number of terms" << std::endl;
1810 if (depth > 0 && entry.terms()[depth - 1] != term_at_level) {
1811 std::cout << prefix_long << "ERROR: an entry doesn't have the right term at depth " << std::to_string(depth)
1816 for (const IndexNode* node : root_node->children) {
1817 printTree(node, depth + 1);
1820 #endif // LYX_INSET_INDEX_DEBUG
1824 docstring InsetPrintIndex::xhtml(XMLStream &, OutputParams const & op) const
1826 BufferParams const & bp = buffer().masterBuffer()->params();
1828 shared_ptr<Toc const> toc = buffer().tocBackend().toc("index");
1832 // Collect the index entries in a form we can use them.
1833 vector<IndexEntry> entries;
1834 const docstring & indexType = params().getParamOr("type", from_ascii("idx"));
1835 for (const TocItem& item : *toc) {
1836 const auto* inset = static_cast<const InsetIndex*>(&(item.dit().inset()));
1837 if (item.isOutput() && inset->params().index == indexType)
1838 entries.emplace_back(IndexEntry{inset, &op});
1841 // If all the index entries are in notes or not displayed, get out sooner.
1842 if (entries.empty())
1845 const IndexNode* index_root = buildIndexTree(entries);
1846 #ifdef LYX_INSET_INDEX_DEBUG
1847 printTree(index_root);
1850 // Start generating the XHTML index.
1851 Layout const & lay = bp.documentClass().htmlTOCLayout();
1852 string const & tocclass = lay.defaultCSSClass();
1853 string const tocattr = "class='index " + tocclass + "'";
1854 docstring const indexName = params().getParamOr("name", from_ascii("Index"));
1856 // we'll use our own stream, because we are going to defer everything.
1857 // that's how we deal with the fact that we're probably inside a standard
1858 // paragraph, and we don't want to be.
1859 odocstringstream ods;
1862 xs << xml::StartTag("div", tocattr);
1864 xs << xml::StartTag(lay.htmltag(), lay.htmlattr());
1865 xs << translateIfPossible(indexName, op.local_font->language()->lang());
1866 xs << xml::EndTag(lay.htmltag());
1868 xs << xml::StartTag("ul", "class='main'");
1871 LASSERT(index_root->entries.empty(), return docstring()); // No index entry should have zero terms.
1872 for (const IndexNode* node : index_root->children) {
1873 outputIndexPage(xs, node);
1876 xs << xml::EndTag("ul");
1878 xs << xml::EndTag("div");