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 "CutAndPaste.h"
22 #include "DispatchResult.h"
24 #include "ErrorList.h"
25 #include "FuncRequest.h"
26 #include "FuncStatus.h"
27 #include "IndicesList.h"
28 #include "InsetList.h"
31 #include "LaTeXFeatures.h"
34 #include "output_latex.h"
35 #include "output_xhtml.h"
37 #include "texstream.h"
38 #include "TextClass.h"
39 #include "TocBackend.h"
41 #include "support/debug.h"
42 #include "support/docstream.h"
43 #include "support/FileName.h"
44 #include "support/gettext.h"
45 #include "support/lstrings.h"
46 #include "support/Translator.h"
48 #include "frontends/alert.h"
54 #include <QThreadStorage>
57 using namespace lyx::support;
59 // Uncomment to enable InsetIndex-specific debugging mode: the tree for the index will be printed to std::cout.
60 // #define LYX_INSET_INDEX_DEBUG
66 typedef Translator<string, InsetIndexParams::PageRange> PageRangeTranslator;
67 typedef Translator<docstring, InsetIndexParams::PageRange> PageRangeTranslatorLoc;
69 PageRangeTranslator const init_insetindexpagerangetranslator()
71 PageRangeTranslator translator("none", InsetIndexParams::None);
72 translator.addPair("start", InsetIndexParams::Start);
73 translator.addPair("end", InsetIndexParams::End);
77 PageRangeTranslator const init_insetindexpagerangetranslator_latex()
79 PageRangeTranslator translator("", InsetIndexParams::None);
80 translator.addPair("(", InsetIndexParams::Start);
81 translator.addPair(")", InsetIndexParams::End);
86 PageRangeTranslatorLoc const init_insetindexpagerangetranslator_loc()
88 PageRangeTranslatorLoc translator(docstring(), InsetIndexParams::None);
89 translator.addPair(_("Starts page range"), InsetIndexParams::Start);
90 translator.addPair(_("Ends page range"), InsetIndexParams::End);
95 PageRangeTranslator const & insetindexpagerangetranslator()
97 static PageRangeTranslator const prtranslator =
98 init_insetindexpagerangetranslator();
103 PageRangeTranslatorLoc const & insetindexpagerangetranslator_loc()
105 static PageRangeTranslatorLoc const translator =
106 init_insetindexpagerangetranslator_loc();
111 PageRangeTranslator const & insetindexpagerangetranslator_latex()
113 static PageRangeTranslator const lttranslator =
114 init_insetindexpagerangetranslator_latex();
120 /////////////////////////////////////////////////////////////////////
124 ///////////////////////////////////////////////////////////////////////
127 InsetIndex::InsetIndex(Buffer * buf, InsetIndexParams const & params)
128 : InsetCollapsible(buf), params_(params)
132 void InsetIndex::latex(otexstream & ios, OutputParams const & runparams_in) const
134 OutputParams runparams(runparams_in);
135 runparams.inIndexEntry = true;
136 if (runparams_in.postpone_fragile_stuff)
137 // This is not needed and would impact sorting
138 runparams.moving_arg = false;
142 if (buffer().masterBuffer()->params().use_indices && !params_.index.empty()
143 && params_.index != "idx") {
145 os << escape(params_.index);
152 // Get the LaTeX output from InsetText. We need to deconstruct this later
153 // in order to check if we need to generate a sorting key
154 odocstringstream ourlatex;
155 otexstream ots(ourlatex);
156 InsetText::latex(ots, runparams);
157 if (runparams.find_effective()) {
158 // No need for special handling, if we are only searching for some patterns
159 os << ourlatex.str() << "}";
164 getSortkey(os, runparams);
166 os << ourlatex.str();
167 getSubentries(os, runparams, ourlatex.str());
170 os << insetindexpagerangetranslator_latex().find(params_.range);
171 getSeeRefs(os, runparams);
172 } else if (!params_.pagefmt.empty() && params_.pagefmt != "default") {
174 os << insetindexpagerangetranslator_latex().find(params_.range);
175 os << from_utf8(params_.pagefmt);
176 } else if (params_.range != InsetIndexParams::PageRange::None) {
178 os << insetindexpagerangetranslator_latex().find(params_.range);
181 // We check whether we need a sort key.
182 // If so, we use the plaintext version
183 odocstringstream ourplain;
184 InsetText::plaintext(ourplain, runparams);
186 // These are the LaTeX and plaintext representations
187 docstring latexstr = ourlatex.str();
188 docstring plainstr = ourplain.str();
190 // This will get what follows | if anything does,
191 // the command (e.g., see, textbf) for pagination
196 odocstringstream seeref;
197 otexstream otsee(seeref);
198 getSeeRefs(otsee, runparams);
200 } else if (!params_.pagefmt.empty() && params_.pagefmt != "default") {
201 cmd = from_utf8(params_.pagefmt);
203 // Check for the | separator to strip the cmd.
204 // This goes wrong on an escaped "|", but as the escape
205 // character can be changed in style files, we cannot
207 size_t pos = latexstr.find(from_ascii("|"));
208 if (pos != docstring::npos) {
209 // Put the bit after "|" into cmd...
210 cmd = latexstr.substr(pos + 1);
211 // ...and erase that stuff from latexstr
212 latexstr = latexstr.erase(pos);
213 // ...as well as from plainstr
214 size_t ppos = plainstr.find(from_ascii("|"));
215 if (ppos < plainstr.size())
216 plainstr.erase(ppos);
218 LYXERR0("The `|' separator was not found in the plaintext version!");
222 odocstringstream subentries;
223 otexstream otsub(subentries);
224 getSubentries(otsub, runparams, ourlatex.str());
225 if (subentries.str().empty()) {
226 // Separate the entries and subentries, i.e., split on "!".
227 // This goes wrong on an escaped "!", but as the escape
228 // character can be changed in style files, we cannot
230 std::vector<docstring> const levels =
231 getVectorFromString(latexstr, from_ascii("!"), true);
232 std::vector<docstring> const levels_plain =
233 getVectorFromString(plainstr, from_ascii("!"), true);
235 vector<docstring>::const_iterator it = levels.begin();
236 vector<docstring>::const_iterator end = levels.end();
237 vector<docstring>::const_iterator it2 = levels_plain.begin();
239 for (; it != end; ++it) {
241 emptySubentriesWarning(ourlatex.str());
242 if (it2 < levels_plain.end())
246 // The separator needs to be put back when
247 // writing the levels, except for the first level
253 // Now here comes the reason for this whole procedure:
254 // We try to correctly sort macros and formatted strings.
255 // If we find a command, prepend a plain text
256 // version of the content to get sorting right,
257 // e.g. \index{LyX@\LyX}, \index{text@\textbf{text}}.
258 // We do this on all levels.
259 // We don't do it if the level already contains a '@', though.
260 // Plaintext might return nothing (e.g. for ERTs).
261 // In that case, we use LaTeX.
262 docstring const spart = (levels_plain.empty() || (*it2).empty()) ? *it : *it2;
263 processLatexSorting(os, runparams, *it, spart);
264 if (it2 < levels_plain.end())
268 processLatexSorting(os, runparams, latexstr, plainstr);
269 os << subentries.str();
272 // At last, re-insert the command, separated by "|"
275 << insetindexpagerangetranslator_latex().find(params_.range)
277 } else if (params_.range != InsetIndexParams::PageRange::None) {
279 os << insetindexpagerangetranslator_latex().find(params_.range);
284 // In macros with moving arguments, such as \section,
285 // we store the index and output it after the macro (#2154)
286 if (runparams_in.postpone_fragile_stuff)
287 runparams_in.post_macro += os.str();
293 void InsetIndex::processLatexSorting(otexstream & os, OutputParams const & runparams,
294 docstring const latex, docstring const spart) const
296 if (contains(latex, '\\') && !contains(latex, '@')) {
297 // Now we need to validate that all characters in
298 // the sorting part are representable in the current
299 // encoding. If not try the LaTeX macro which might
300 // or might not be a good choice, and issue a warning.
301 pair<docstring, docstring> spart_latexed =
302 runparams.encoding->latexString(spart, runparams.dryrun);
303 if (!spart_latexed.second.empty())
304 LYXERR0("Uncodable character in index entry. Sorting might be wrong!");
305 if (spart != spart_latexed.first && !runparams.dryrun) {
307 ErrorList & errorList = buffer().errorList("Export");
308 docstring const s = bformat(_("LyX's automatic index sorting algorithm faced "
309 "problems with the entry '%1$s'.\n"
310 "Please specify the sorting of this entry manually, as "
311 "explained in the User Guide."), spart);
312 Paragraph const & par = buffer().paragraphs().front();
313 errorList.push_back(ErrorItem(_("Index sorting failed"), s,
314 {par.id(), 0}, {par.id(), -1}));
315 buffer().bufferErrors(terr, errorList);
317 // Remove remaining \'s from the sort key
318 docstring ppart = subst(spart_latexed.first, from_ascii("\\"), docstring());
319 // Plain quotes need to be escaped, however (#10649), as this
320 // is the default escape character
321 ppart = subst(ppart, from_ascii("\""), from_ascii("\\\""));
323 // Now insert the sortkey, separated by '@'.
327 // Insert the actual level text
332 void InsetIndex::docbook(XMLStream & xs, OutputParams const & runparams) const
334 // Two ways of processing this inset are implemented:
335 // - the legacy one, based on parsing the raw LaTeX (before LyX 2.4) -- unlikely to be deprecated
336 // - the modern one, based on precise insets for indexing features
337 // Like the LaTeX implementation, consider the user chooses either of those options.
339 // Get the content of the inset as LaTeX, as some things may be encoded as ERT (like {}).
340 // TODO: if there is an ERT within the index term, its conversion should be tried, in case it becomes useful;
341 // otherwise, ERTs should become comments. For now, they are just copied as-is, which is barely satisfactory.
342 odocstringstream odss;
343 otexstream ots(odss);
344 InsetText::latex(ots, runparams);
345 docstring latexString = trim(odss.str());
347 // Handle several indices (indicated in the inset instead of the raw latexString).
348 docstring indexType = from_utf8("");
349 if (buffer().masterBuffer()->params().use_indices) {
350 indexType += " type=\"" + params_.index + "\"";
353 // Split the string into its main constituents: terms, and command (see, see also, range).
354 size_t positionVerticalBar = latexString.find(from_ascii("|")); // What comes before | is (sub)(sub)entries.
355 docstring indexTerms = latexString.substr(0, positionVerticalBar);
357 if (positionVerticalBar != lyx::docstring::npos) {
358 command = latexString.substr(positionVerticalBar + 1);
361 // Handle sorting issues, with @.
364 sortAs = getSortkeyAsText(runparams);
365 // indexTerms may contain a sort key if the user has both the inset and the manual key.
367 vector<docstring> sortingElements = getVectorFromString(indexTerms, from_ascii("@"), false);
368 if (sortingElements.size() == 2) {
369 sortAs = sortingElements[0];
370 indexTerms = sortingElements[1];
374 // Handle primary, secondary, and tertiary terms (entries, subentries, and subsubentries, for LaTeX).
375 vector<docstring> terms;
376 const vector<docstring> potential_terms = getSubentriesAsText(runparams);
377 if (!potential_terms.empty()) {
378 terms = potential_terms;
379 // The main term is not present in the vector, as it's not a subentry. The main index term is inserted raw in
380 // the index inset. Considering that the user either uses the new or the legacy mechanism, the main term is the
381 // full string within this inset (i.e. without the subinsets).
382 terms.insert(terms.begin(), latexString);
384 terms = getVectorFromString(indexTerms, from_ascii("!"), false);
387 // Handle ranges. Happily, in the raw LaTeX mode, (| and |) can only be at the end of the string!
388 const bool hasInsetRange = params_.range != InsetIndexParams::PageRange::None;
389 const bool hasStartRange = params_.range == InsetIndexParams::PageRange::Start ||
390 latexString.find(from_ascii("|(")) != lyx::docstring::npos;
391 const bool hasEndRange = params_.range == InsetIndexParams::PageRange::End ||
392 latexString.find(from_ascii("|)")) != lyx::docstring::npos;
395 // Remove the ranges from the command if they do not appear at the beginning.
397 while ((index = command.find(from_utf8("|("), index)) != std::string::npos)
398 command.erase(index, 1);
400 while ((index = command.find(from_utf8("|)"), index)) != std::string::npos)
401 command.erase(index, 1);
403 // Remove the ranges when they are the only vertical bar in the complete string.
404 if (command[0] == '(' || command[0] == ')')
408 // Handle see and seealso. As "see" is a prefix of "seealso", the order of the comparisons is important.
409 // Both commands are mutually exclusive!
410 docstring see = getSeeAsText(runparams);
411 vector<docstring> seeAlsoes = getSeeAlsoesAsText(runparams);
413 if (see.empty() && seeAlsoes.empty() && command.substr(0, 3) == "see") {
414 // Unescape brackets.
416 while ((index = command.find(from_utf8("\\{"), index)) != std::string::npos)
417 command.erase(index, 1);
419 while ((index = command.find(from_utf8("\\}"), index)) != std::string::npos)
420 command.erase(index, 1);
422 // Retrieve the part between brackets, and remove the complete seealso.
423 size_t positionOpeningBracket = command.find(from_ascii("{"));
424 size_t positionClosingBracket = command.find(from_ascii("}"));
425 docstring list = command.substr(positionOpeningBracket + 1, positionClosingBracket - positionOpeningBracket - 1);
427 // Parse the list of referenced entries (or a single one for see).
428 if (command.substr(0, 7) == "seealso") {
429 seeAlsoes = getVectorFromString(list, from_ascii(","), false);
433 if (see.find(from_ascii(",")) != std::string::npos) {
434 docstring error = from_utf8("Several index terms found as \"see\"! Only one is acceptable. "
435 "Complete entry: \"") + latexString + from_utf8("\"");
437 xs << XMLStream::ESCAPE_NONE << (from_utf8("<!-- Output Error: ") + error + from_utf8(" -->\n"));
441 // Remove the complete see/seealso from the commands, in case there is something else to parse.
442 command = command.substr(positionClosingBracket + 1);
445 // Some parts of the strings are not parsed, as they do not have anything matching in DocBook: things like
446 // formatting the entry or the page number, other strings for sorting. https://wiki.lyx.org/Tips/Indexing
447 // If there are such things in the index entry, then this code may miserably fail. For example, for "Peter|(textbf",
448 // no range will be detected.
449 // TODO: Could handle formatting as significance="preferred"?
450 if (!command.empty()) {
451 docstring error = from_utf8("Unsupported feature: an index entry contains a | with an unsupported command, ")
452 + command + from_utf8(". ") + from_utf8("Complete entry: \"") + latexString + from_utf8("\"");
454 xs << XMLStream::ESCAPE_NONE << (from_utf8("<!-- Output Error: ") + error + from_utf8(" -->\n"));
457 // Write all of this down.
458 if (terms.empty() && !hasEndRange) {
459 docstring error = from_utf8("No index term found! Complete entry: \"") + latexString + from_utf8("\"");
461 xs << XMLStream::ESCAPE_NONE << (from_utf8("<!-- Output Error: ") + error + from_utf8(" -->\n"));
463 // Generate the attributes for ranges. It is based on the terms that are indexed, but the ID must be unique
464 // to this indexing area (xml::cleanID does not guarantee this: for each call with the same arguments,
465 // the same legal ID is produced; here, as the input would be the same, the output must be, by design).
466 // Hence the thread-local storage, as the numbers must strictly be unique, and thus cannot be shared across
467 // a paragraph (making the solution used for HTML worthless). This solution is very similar to the one used in
469 // indexType can only be used for singular and startofrange types!
471 if (!hasStartRange && !hasEndRange) {
474 // Append an ID if uniqueness is not guaranteed across the document.
475 static QThreadStorage<set<docstring>> tKnownTermLists;
476 static QThreadStorage<int> tID;
478 set<docstring> &knownTermLists = tKnownTermLists.localData();
479 int &ID = tID.localData();
481 if (!tID.hasLocalData()) {
485 // Modify the index terms to add the unique ID if needed.
486 docstring newIndexTerms = indexTerms;
487 if (knownTermLists.find(indexTerms) != knownTermLists.end()) {
488 newIndexTerms += from_ascii(string("-") + to_string(ID));
490 // Only increment for the end of range, so that the same number is used for the start of range.
496 // Term list not yet known: add it to the set AFTER the end of range. After
497 if (knownTermLists.find(indexTerms) == knownTermLists.end() && hasEndRange) {
498 knownTermLists.insert(indexTerms);
501 // Generate the attributes.
502 docstring id = xml::cleanID(newIndexTerms);
504 attrs = indexType + " class=\"startofrange\" xml:id=\"" + id + "\"";
506 attrs = " class=\"endofrange\" startref=\"" + id + "\"";
510 // Handle the index terms (including the specific index for this entry).
512 xs << xml::CompTag("indexterm", attrs);
514 xs << xml::StartTag("indexterm", attrs);
515 if (!terms.empty()) { // hasEndRange has no content.
517 if (!sortAs.empty()) {
518 attr = from_utf8("sortas='") + sortAs + from_utf8("'");
521 xs << xml::StartTag("primary", attr);
523 xs << xml::EndTag("primary");
525 if (terms.size() > 1) {
526 xs << xml::StartTag("secondary");
528 xs << xml::EndTag("secondary");
530 if (terms.size() > 2) {
531 xs << xml::StartTag("tertiary");
533 xs << xml::EndTag("tertiary");
536 // Handle see and see also.
538 xs << xml::StartTag("see");
540 xs << xml::EndTag("see");
543 if (!seeAlsoes.empty()) {
544 for (auto &entry : seeAlsoes) {
545 xs << xml::StartTag("seealso");
547 xs << xml::EndTag("seealso");
552 xs << xml::EndTag("indexterm");
558 docstring InsetIndex::xhtml(XMLStream & xs, OutputParams const &) const
560 // we just print an anchor, taking the paragraph ID from
561 // our own interior paragraph, which doesn't get printed
562 std::string const magic = paragraphs().front().magicLabel();
563 std::string const attr = "id='" + magic + "'";
564 xs << xml::CompTag("a", attr);
569 bool InsetIndex::showInsetDialog(BufferView * bv) const
571 bv->showDialog("index", params2string(params_),
572 const_cast<InsetIndex *>(this));
577 void InsetIndex::doDispatch(Cursor & cur, FuncRequest & cmd)
579 switch (cmd.action()) {
581 case LFUN_INSET_MODIFY: {
582 if (cmd.getArg(0) == "changetype") {
583 cur.recordUndoInset(this);
584 params_.index = from_utf8(cmd.getArg(1));
587 if (cmd.getArg(0) == "changeparam") {
588 string const p = cmd.getArg(1);
589 string const v = cmd.getArg(2);
590 cur.recordUndoInset(this);
592 params_.range = insetindexpagerangetranslator().find(v);
593 if (p == "pagefmt") {
594 if (v == "default" || v == "textbf"
595 || v == "textit" || v == "emph")
598 lyx::dispatch(FuncRequest(LFUN_INSET_SETTINGS, "index"));
602 InsetIndexParams params;
603 InsetIndex::string2params(to_utf8(cmd.argument()), params);
604 cur.recordUndoInset(this);
605 params_.index = params.index;
606 params_.range = params.range;
607 params_.pagefmt = params.pagefmt;
608 // what we really want here is a TOC update, but that means
609 // a full buffer update
610 cur.forceBufferUpdate();
614 case LFUN_INSET_DIALOG_UPDATE:
615 cur.bv().updateDialog("index", params2string(params_));
618 case LFUN_PARAGRAPH_BREAK: {
619 // Since this inset in single-par anyway, let's use
620 // return to enter subentries
621 FuncRequest fr(LFUN_INDEXMACRO_INSERT, "subentry");
626 case LFUN_INSET_INSERT_COPY: {
627 Cursor & bvcur = cur.bv().cursor();
628 if (cmd.origin() == FuncRequest::TOC && bvcur.inTexted()) {
629 cap::copyInsetToTemp(cur, clone());
630 cap::pasteFromTemp(bvcur, bvcur.buffer()->errorList("Paste"));
637 InsetCollapsible::doDispatch(cur, cmd);
643 bool InsetIndex::getStatus(Cursor & cur, FuncRequest const & cmd,
644 FuncStatus & flag) const
646 switch (cmd.action()) {
648 case LFUN_INSET_MODIFY:
649 if (cmd.getArg(0) == "changetype") {
650 docstring const newtype = from_utf8(cmd.getArg(1));
651 Buffer const & realbuffer = *buffer().masterBuffer();
652 IndicesList const & indiceslist = realbuffer.params().indiceslist();
653 Index const * index = indiceslist.findShortcut(newtype);
654 flag.setEnabled(index != 0);
656 from_utf8(cmd.getArg(1)) == params_.index);
659 if (cmd.getArg(0) == "changeparam") {
660 string const p = cmd.getArg(1);
661 string const v = cmd.getArg(2);
663 flag.setEnabled(v == "none" || v == "start" || v == "end");
664 flag.setOnOff(params_.range == insetindexpagerangetranslator().find(v));
666 if (p == "pagefmt") {
667 flag.setEnabled(!v.empty());
668 if (params_.pagefmt == "default" || params_.pagefmt == "textbf"
669 || params_.pagefmt == "textit" || params_.pagefmt == "emph")
670 flag.setOnOff(params_.pagefmt == v);
672 flag.setOnOff(v == "custom");
676 return InsetCollapsible::getStatus(cur, cmd, flag);
678 case LFUN_INSET_DIALOG_UPDATE: {
679 Buffer const & realbuffer = *buffer().masterBuffer();
680 flag.setEnabled(realbuffer.params().use_indices);
684 case LFUN_INSET_INSERT_COPY:
685 // This can only be invoked by ToC widget
686 flag.setEnabled(cmd.origin() == FuncRequest::TOC
687 && cur.bv().cursor().inset().insetAllowed(lyxCode()));
690 case LFUN_PARAGRAPH_BREAK:
691 return macrosPossible("subentry");
693 case LFUN_INDEXMACRO_INSERT:
694 return macrosPossible(cmd.getArg(0));
696 case LFUN_INDEX_TAG_ALL:
700 return InsetCollapsible::getStatus(cur, cmd, flag);
705 void InsetIndex::getSortkey(otexstream & os, OutputParams const & runparams) const
707 Paragraph const & par = paragraphs().front();
708 InsetList::const_iterator it = par.insetList().begin();
709 for (; it != par.insetList().end(); ++it) {
710 Inset & inset = *it->inset;
711 if (inset.lyxCode() == INDEXMACRO_SORTKEY_CODE) {
712 InsetIndexMacro const & iim =
713 static_cast<InsetIndexMacro const &>(inset);
714 iim.getLatex(os, runparams);
721 docstring InsetIndex::getSortkeyAsText(OutputParams const & runparams) const
723 Paragraph const & par = paragraphs().front();
724 InsetList::const_iterator it = par.insetList().begin();
725 for (; it != par.insetList().end(); ++it) {
726 Inset & inset = *it->inset;
727 if (inset.lyxCode() == INDEXMACRO_SORTKEY_CODE) {
729 InsetIndexMacro const & iim =
730 static_cast<InsetIndexMacro const &>(inset);
731 iim.getLatex(os, runparams);
735 return from_ascii("");
739 void InsetIndex::emptySubentriesWarning(docstring const & mainentry) const
741 // Empty subentries crash makeindex. So warn and ignore this.
743 ErrorList & errorList = buffer().errorList("Export");
744 docstring const s = bformat(_("There is an empty index subentry in the entry '%1$s'.\n"
745 "It will be ignored in the output."), mainentry);
746 Paragraph const & par = buffer().paragraphs().front();
747 errorList.push_back(ErrorItem(_("Empty index subentry!"), s,
748 {par.id(), 0}, {par.id(), -1}));
749 buffer().bufferErrors(terr, errorList);
753 void InsetIndex::getSubentries(otexstream & os, OutputParams const & runparams,
754 docstring const & mainentry) const
756 Paragraph const & par = paragraphs().front();
757 InsetList::const_iterator it = par.insetList().begin();
759 for (; it != par.insetList().end(); ++it) {
760 Inset & inset = *it->inset;
761 if (inset.lyxCode() == INDEXMACRO_CODE) {
762 InsetIndexMacro const & iim =
763 static_cast<InsetIndexMacro const &>(inset);
764 if (iim.params().type == InsetIndexMacroParams::Subentry) {
765 if (iim.hasNoContent()) {
766 emptySubentriesWarning(mainentry);
773 iim.getLatex(os, runparams);
780 std::vector<docstring> InsetIndex::getSubentriesAsText(OutputParams const & runparams,
781 bool const asLabel) const
783 std::vector<docstring> subentries;
785 Paragraph const & par = paragraphs().front();
786 InsetList::const_iterator it = par.insetList().begin();
788 for (; it != par.insetList().end(); ++it) {
789 Inset & inset = *it->inset;
790 if (inset.lyxCode() == INDEXMACRO_CODE) {
791 InsetIndexMacro const & iim =
792 static_cast<InsetIndexMacro const &>(inset);
793 if (iim.params().type == InsetIndexMacroParams::Subentry) {
799 docstring const sl = iim.getNewLabel(l);
800 subentries.emplace_back(sl);
803 iim.getLatex(os, runparams);
804 subentries.emplace_back(os.str());
814 docstring InsetIndex::getMainSubentryAsText(OutputParams const & runparams) const
817 InsetText::latex(os, runparams);
822 void InsetIndex::getSeeRefs(otexstream & os, OutputParams const & runparams) const
824 Paragraph const & par = paragraphs().front();
825 InsetList::const_iterator it = par.insetList().begin();
826 for (; it != par.insetList().end(); ++it) {
827 Inset & inset = *it->inset;
828 if (inset.lyxCode() == INDEXMACRO_CODE) {
829 InsetIndexMacro const & iim =
830 static_cast<InsetIndexMacro const &>(inset);
831 if (iim.params().type == InsetIndexMacroParams::See
832 || iim.params().type == InsetIndexMacroParams::Seealso) {
833 iim.getLatex(os, runparams);
841 docstring InsetIndex::getSeeAsText(OutputParams const & runparams,
842 bool const asLabel) const
844 Paragraph const & par = paragraphs().front();
845 InsetList::const_iterator it = par.insetList().begin();
846 for (; it != par.insetList().end(); ++it) {
847 Inset & inset = *it->inset;
848 if (inset.lyxCode() == INDEXMACRO_CODE) {
849 InsetIndexMacro const & iim =
850 static_cast<InsetIndexMacro const &>(inset);
851 if (iim.params().type == InsetIndexMacroParams::See) {
854 return iim.getNewLabel(l);
857 iim.getLatex(os, runparams);
863 return from_ascii("");
867 std::vector<docstring> InsetIndex::getSeeAlsoesAsText(OutputParams const & runparams,
868 bool const asLabel) const
870 std::vector<docstring> seeAlsoes;
872 Paragraph const & par = paragraphs().front();
873 InsetList::const_iterator it = par.insetList().begin();
874 for (; it != par.insetList().end(); ++it) {
875 Inset & inset = *it->inset;
876 if (inset.lyxCode() == INDEXMACRO_CODE) {
877 InsetIndexMacro const & iim =
878 static_cast<InsetIndexMacro const &>(inset);
879 if (iim.params().type == InsetIndexMacroParams::Seealso) {
882 seeAlsoes.emplace_back(iim.getNewLabel(l));
885 iim.getLatex(os, runparams);
886 seeAlsoes.emplace_back(os.str());
898 bool hasInsetWithCode(const InsetIndex * const inset_index, const InsetCode code,
899 const std::set<InsetIndexMacroParams::Type> types = {})
901 Paragraph const & par = inset_index->paragraphs().front();
902 InsetList::const_iterator it = par.insetList().begin();
903 for (; it != par.insetList().end(); ++it) {
904 Inset & inset = *it->inset;
905 if (inset.lyxCode() == code) {
909 LASSERT(code == INDEXMACRO_CODE, return false);
910 InsetIndexMacro const & iim =
911 static_cast<InsetIndexMacro const &>(inset);
912 if (types.find(iim.params().type) != types.end())
922 bool InsetIndex::hasSubentries() const
924 return hasInsetWithCode(this, INDEXMACRO_CODE, {InsetIndexMacroParams::Subentry});
928 bool InsetIndex::hasSeeRef() const
930 return hasInsetWithCode(this, INDEXMACRO_CODE, {InsetIndexMacroParams::See, InsetIndexMacroParams::Seealso});
934 bool InsetIndex::hasSortKey() const
936 return hasInsetWithCode(this, INDEXMACRO_SORTKEY_CODE);
940 bool InsetIndex::macrosPossible(string const type) const
942 if (type != "see" && type != "seealso"
943 && type != "sortkey" && type != "subentry")
946 Paragraph const & par = paragraphs().front();
947 InsetList::const_iterator it = par.insetList().begin();
949 for (; it != par.insetList().end(); ++it) {
950 Inset & inset = *it->inset;
951 if (type == "sortkey" && inset.lyxCode() == INDEXMACRO_SORTKEY_CODE)
953 if (inset.lyxCode() == INDEXMACRO_CODE) {
954 InsetIndexMacro const & iim = static_cast<InsetIndexMacro const &>(inset);
955 if ((type == "see" || type == "seealso")
956 && (iim.params().type == InsetIndexMacroParams::See
957 || iim.params().type == InsetIndexMacroParams::Seealso))
959 if (type == "subentry"
960 && iim.params().type == InsetIndexMacroParams::Subentry) {
971 ColorCode InsetIndex::labelColor() const
973 if (params_.index.empty() || params_.index == from_ascii("idx"))
974 return InsetCollapsible::labelColor();
976 ColorCode c = lcolor.getFromLyXName(to_utf8(params_.index)
977 + "@" + buffer().fileName().absFileName());
979 c = InsetCollapsible::labelColor();
984 docstring InsetIndex::toolTip(BufferView const &, int, int) const
986 docstring tip = _("Index Entry");
987 if (buffer().params().use_indices && !params_.index.empty()) {
988 Buffer const & realbuffer = *buffer().masterBuffer();
989 IndicesList const & indiceslist = realbuffer.params().indiceslist();
991 Index const * index = indiceslist.findShortcut(params_.index);
993 tip += _("unknown type!");
995 tip += index->index();
999 docstring res = toolTipText(tip);
1000 if (!insetindexpagerangetranslator_loc().find(params_.range).empty())
1001 res += "\n" + insetindexpagerangetranslator_loc().find(params_.range);
1002 if (!params_.pagefmt.empty() && params_.pagefmt != "default") {
1003 res += "\n" + _("Pagination format:") + " ";
1004 if (params_.pagefmt == "textbf")
1006 else if (params_.pagefmt == "textit")
1008 else if (params_.pagefmt == "emph")
1009 res += _("emphasized");
1011 res += from_utf8(params_.pagefmt);
1017 docstring const InsetIndex::buttonLabel(BufferView const & bv) const
1019 InsetLayout const & il = getLayout();
1020 docstring label = translateIfPossible(il.labelstring());
1022 if (buffer().params().use_indices && !params_.index.empty()) {
1023 Buffer const & realbuffer = *buffer().masterBuffer();
1024 IndicesList const & indiceslist = realbuffer.params().indiceslist();
1026 Index const * index = indiceslist.findShortcut(params_.index);
1028 label += _("unknown type!");
1030 label += index->index();
1035 if (!il.contentaslabel() || geometry(bv) != ButtonOnly)
1038 res = getNewLabel(label);
1039 OutputParams const rp(0);
1040 vector<docstring> sublbls = getSubentriesAsText(rp, true);
1041 for (auto const & sublbl : sublbls) {
1042 res += " " + docstring(1, char_type(0x2023));// TRIANGULAR BULLET
1043 res += " " + sublbl;
1045 docstring see = getSeeAsText(rp, true);
1046 if (see.empty() && !getSeeAlsoesAsText(rp, true).empty())
1047 see = getSeeAlsoesAsText(rp, true).front();
1049 res += " " + docstring(1, char_type(0x261e));// WHITE RIGHT POINTING INDEX
1053 if (!insetindexpagerangetranslator_latex().find(params_.range).empty())
1054 res += " " + from_ascii(insetindexpagerangetranslator_latex().find(params_.range));
1059 void InsetIndex::write(ostream & os) const
1061 os << to_utf8(layoutName());
1063 InsetCollapsible::write(os);
1067 void InsetIndex::read(Lexer & lex)
1070 InsetCollapsible::read(lex);
1074 string InsetIndex::params2string(InsetIndexParams const & params)
1083 void InsetIndex::string2params(string const & in, InsetIndexParams & params)
1085 params = InsetIndexParams();
1089 istringstream data(in);
1091 lex.setStream(data);
1092 lex.setContext("InsetIndex::string2params");
1098 void InsetIndex::addToToc(DocIterator const & cpit, bool output_active,
1099 UpdateType utype, TocBackend & backend) const
1101 DocIterator pit = cpit;
1102 pit.push_back(CursorSlice(const_cast<InsetIndex &>(*this)));
1104 InsetLayout const & il = getLayout();
1105 docstring label = translateIfPossible(il.labelstring());
1106 if (!il.contentaslabel())
1109 str = getNewLabel(label);
1110 OutputParams const rp(0);
1111 vector<docstring> sublbls = getSubentriesAsText(rp, true);
1112 for (auto const & sublbl : sublbls) {
1113 str += " " + docstring(1, char_type(0x2023));// TRIANGULAR BULLET
1114 str += " " + sublbl;
1116 docstring see = getSeeAsText(rp, true);
1117 if (see.empty() && !getSeeAlsoesAsText(rp, true).empty())
1118 see = getSeeAlsoesAsText(rp, true).front();
1120 str += " " + docstring(1, char_type(0x261e));// WHITE RIGHT POINTING INDEX
1124 string type = "index";
1125 if (buffer().masterBuffer()->params().use_indices)
1126 type += ":" + to_utf8(params_.index);
1127 TocBuilder & b = backend.builder(type);
1128 b.pushItem(pit, str, output_active);
1129 // Proceed with the rest of the inset.
1130 InsetCollapsible::addToToc(cpit, output_active, utype, backend);
1135 void InsetIndex::validate(LaTeXFeatures & features) const
1137 if (buffer().masterBuffer()->params().use_indices
1138 && !params_.index.empty()
1139 && params_.index != "idx")
1140 features.require("splitidx");
1141 InsetCollapsible::validate(features);
1145 string InsetIndex::contextMenuName() const
1147 return "context-index";
1151 string InsetIndex::contextMenu(BufferView const & bv, int x, int y) const
1153 // We override the implementation of InsetCollapsible,
1154 // because we have eytra entries.
1155 string owncm = "context-edit-index;";
1156 return owncm + InsetCollapsible::contextMenu(bv, x, y);
1160 bool InsetIndex::hasSettings() const
1166 bool InsetIndex::insetAllowed(InsetCode code) const
1169 case INDEXMACRO_CODE:
1170 case INDEXMACRO_SORTKEY_CODE:
1175 return InsetCollapsible::insetAllowed(code);
1180 /////////////////////////////////////////////////////////////////////
1184 ///////////////////////////////////////////////////////////////////////
1187 void InsetIndexParams::write(ostream & os) const
1191 os << to_utf8(index);
1196 << insetindexpagerangetranslator().find(range)
1204 void InsetIndexParams::read(Lexer & lex)
1207 index = lex.getDocString();
1209 index = from_ascii("idx");
1210 if (lex.checkFor("range")) {
1211 string st = lex.getString();
1212 if (lex.eatLine()) {
1213 st = lex.getString();
1214 range = insetindexpagerangetranslator().find(lex.getString());
1217 if (lex.checkFor("pageformat") && lex.eatLine()) {
1218 pagefmt = lex.getString();
1223 /////////////////////////////////////////////////////////////////////
1227 ///////////////////////////////////////////////////////////////////////
1229 InsetPrintIndex::InsetPrintIndex(Buffer * buf, InsetCommandParams const & p)
1230 : InsetCommand(buf, p)
1234 ParamInfo const & InsetPrintIndex::findInfo(string const & /* cmdName */)
1236 static ParamInfo param_info_;
1237 if (param_info_.empty()) {
1238 param_info_.add("type", ParamInfo::LATEX_OPTIONAL,
1239 ParamInfo::HANDLING_ESCAPE);
1240 param_info_.add("name", ParamInfo::LATEX_OPTIONAL,
1241 ParamInfo::HANDLING_LATEXIFY);
1242 param_info_.add("literal", ParamInfo::LYX_INTERNAL);
1248 docstring InsetPrintIndex::screenLabel() const
1250 bool const printall = suffixIs(getCmdName(), '*');
1251 bool const multind = buffer().masterBuffer()->params().use_indices;
1253 && getParam("type") == from_ascii("idx"))
1254 || (getParam("type").empty() && !printall))
1256 Buffer const & realbuffer = *buffer().masterBuffer();
1257 IndicesList const & indiceslist = realbuffer.params().indiceslist();
1258 Index const * index = indiceslist.findShortcut(getParam("type"));
1259 if (!index && !printall)
1260 return _("Unknown index type!");
1261 docstring res = printall ? _("All indexes") : index->index();
1263 res += " (" + _("non-active") + ")";
1264 else if (contains(getCmdName(), "printsubindex"))
1265 res += " (" + _("subindex") + ")";
1270 bool InsetPrintIndex::isCompatibleCommand(string const & s)
1272 return s == "printindex" || s == "printsubindex"
1273 || s == "printindex*" || s == "printsubindex*";
1277 void InsetPrintIndex::doDispatch(Cursor & cur, FuncRequest & cmd)
1279 switch (cmd.action()) {
1281 case LFUN_INSET_MODIFY: {
1282 if (cmd.argument() == from_ascii("toggle-subindex")) {
1283 string scmd = getCmdName();
1284 if (contains(scmd, "printindex"))
1285 scmd = subst(scmd, "printindex", "printsubindex");
1287 scmd = subst(scmd, "printsubindex", "printindex");
1291 } else if (cmd.argument() == from_ascii("check-printindex*")) {
1292 string scmd = getCmdName();
1293 if (suffixIs(scmd, '*'))
1297 setParam("type", docstring());
1301 InsetCommandParams p(INDEX_PRINT_CODE);
1303 InsetCommand::string2params(to_utf8(cmd.argument()), p);
1304 if (p.getCmdName().empty()) {
1305 cur.noScreenUpdate();
1314 InsetCommand::doDispatch(cur, cmd);
1320 bool InsetPrintIndex::getStatus(Cursor & cur, FuncRequest const & cmd,
1321 FuncStatus & status) const
1323 switch (cmd.action()) {
1325 case LFUN_INSET_MODIFY: {
1326 if (cmd.argument() == from_ascii("toggle-subindex")) {
1327 status.setEnabled(buffer().masterBuffer()->params().use_indices);
1328 status.setOnOff(contains(getCmdName(), "printsubindex"));
1330 } else if (cmd.argument() == from_ascii("check-printindex*")) {
1331 status.setEnabled(buffer().masterBuffer()->params().use_indices);
1332 status.setOnOff(suffixIs(getCmdName(), '*'));
1334 } if (cmd.getArg(0) == "index_print"
1335 && cmd.getArg(1) == "CommandInset") {
1336 InsetCommandParams p(INDEX_PRINT_CODE);
1337 InsetCommand::string2params(to_utf8(cmd.argument()), p);
1338 if (suffixIs(p.getCmdName(), '*')) {
1339 status.setEnabled(true);
1340 status.setOnOff(false);
1343 Buffer const & realbuffer = *buffer().masterBuffer();
1344 IndicesList const & indiceslist =
1345 realbuffer.params().indiceslist();
1346 Index const * index = indiceslist.findShortcut(p["type"]);
1347 status.setEnabled(index != 0);
1348 status.setOnOff(p["type"] == getParam("type"));
1351 return InsetCommand::getStatus(cur, cmd, status);
1354 case LFUN_INSET_DIALOG_UPDATE: {
1355 status.setEnabled(buffer().masterBuffer()->params().use_indices);
1360 return InsetCommand::getStatus(cur, cmd, status);
1365 void InsetPrintIndex::updateBuffer(ParIterator const &, UpdateType, bool const /*deleted*/)
1367 Index const * index =
1368 buffer().masterParams().indiceslist().findShortcut(getParam("type"));
1370 setParam("name", index->index());
1374 void InsetPrintIndex::latex(otexstream & os, OutputParams const & runparams_in) const
1376 if (!buffer().masterBuffer()->params().use_indices) {
1377 if (getParam("type") == from_ascii("idx"))
1378 os << "\\printindex" << termcmd;
1381 OutputParams runparams = runparams_in;
1382 os << getCommand(runparams);
1386 void InsetPrintIndex::validate(LaTeXFeatures & features) const
1388 features.require("makeidx");
1389 if (buffer().masterBuffer()->params().use_indices)
1390 features.require("splitidx");
1391 InsetCommand::validate(features);
1395 string InsetPrintIndex::contextMenuName() const
1397 return buffer().masterBuffer()->params().use_indices ?
1398 "context-indexprint" : string();
1402 bool InsetPrintIndex::hasSettings() const
1404 return buffer().masterBuffer()->params().use_indices;
1411 /// Builds an entry for the index.
1412 IndexEntry(const InsetIndex * inset, OutputParams const * runparams) : inset_(inset), runparams_(runparams)
1414 LASSERT(runparams, return);
1416 // Convert the inset as text. The resulting text usually only contains an XHTML anchor (<a id='...'/>) and text.
1417 odocstringstream entry;
1418 OutputParams ours = *runparams;
1419 ours.for_toc = false;
1420 inset_->plaintext(entry, ours);
1421 entry_ = entry.str();
1423 // Determine in which index this entry belongs to.
1424 if (inset_->buffer().masterBuffer()->params().use_indices) {
1425 index_ = inset_->params_.index;
1428 // Attempt parsing the inset.
1439 #ifdef LYX_INSET_INDEX_DEBUG
1440 std::cout << to_utf8(entry_) << std::endl;
1441 #endif // LYX_INSET_INDEX_DEBUG
1443 // If a modern parameter is present, this is definitely a modern index inset. Similarly, if it contains the
1444 // usual LaTeX symbols (!|@), then it is definitely a legacy index inset. Otherwise, if it has features of
1445 // neither, it is both: consider this is a modern inset, to trigger the least complex code. Mixing both types
1446 // is not allowed (i.e. behaviour is undefined).
1447 const bool is_definitely_modern = inset_->hasSortKey() || inset_->hasSeeRef() || inset_->hasSubentries()
1448 || inset_->params_.range != InsetIndexParams::PageRange::None;
1449 const bool is_definitely_legacy = entry_.find('@') != std::string::npos
1450 || entry_.find('|') != std::string::npos || entry_.find('!') != std::string::npos;
1452 if (is_definitely_legacy && is_definitely_modern)
1453 output_error_ += from_utf8("Mix of index properties and raw LaTeX index commands is unsupported. ");
1456 // - is_definitely_modern == true:
1457 // - is_definitely_legacy == true: error (return whatever)
1458 // - is_definitely_legacy == false: return modern
1459 // - is_definitely_modern == false:
1460 // - is_definitely_legacy == true: return legacy
1461 // - is_definitely_legacy == false: return modern
1462 return !is_definitely_legacy;
1465 void parseAsModern()
1467 LASSERT(runparams_, return);
1469 if (inset_->hasSortKey()) {
1470 sort_as_ = inset_->getSortkeyAsText(*runparams_);
1473 terms_ = inset_->getSubentriesAsText(*runparams_);
1474 // The main term is not present in the vector, as it's not a subentry. The main index term is inserted raw in
1475 // the index inset. Considering that the user either uses the new or the legacy mechanism, the main term is the
1476 // full string within this inset (i.e. without the subinsets).
1477 terms_.insert(terms_.begin(), inset_->getMainSubentryAsText(*runparams_));
1479 has_start_range_ = inset_->params_.range == InsetIndexParams::PageRange::Start;
1480 has_end_range_ = inset_->params_.range == InsetIndexParams::PageRange::End;
1482 see_ = inset_->getSeeAsText(*runparams_);
1483 see_alsoes_ = inset_->getSeeAlsoesAsText(*runparams_);
1486 void parseAsLegacy() {
1487 // Determine if some features are known not to be supported. For now, this is only formatting like
1488 // \index{alpha@\textbf{alpha}} or \index{alpha@$\alpha$}.
1489 // @ is supported, but only for sorting, without specific formatting.
1490 if (entry_.find(from_utf8("@\\")) != lyx::docstring::npos) {
1491 output_error_ += from_utf8("Unsupported feature: an index entry contains an @\\. "
1492 "Complete entry: \"") + entry_ + from_utf8("\". ");
1494 if (entry_.find(from_utf8("@$")) != lyx::docstring::npos) {
1495 output_error_ += from_utf8("Unsupported feature: an index entry contains an @$. "
1496 "Complete entry: \"") + entry_ + from_utf8("\". ");
1499 // Split the string into its main constituents: terms, and command (see, see also, range).
1500 size_t positionVerticalBar = entry_.find(from_ascii("|")); // What comes before | is (sub)(sub)entries.
1501 docstring indexTerms = entry_.substr(0, positionVerticalBar);
1503 if (positionVerticalBar != lyx::docstring::npos) {
1504 command = entry_.substr(positionVerticalBar + 1);
1507 // Handle sorting issues, with @.
1508 vector<docstring> sortingElements = getVectorFromString(indexTerms, from_ascii("@"), false);
1509 if (sortingElements.size() == 2) {
1510 sort_as_ = sortingElements[0];
1511 indexTerms = sortingElements[1];
1514 // Handle entries, subentries, and subsubentries.
1515 terms_ = getVectorFromString(indexTerms, from_ascii("!"), false);
1517 // Handle ranges. Happily, (| and |) can only be at the end of the string!
1518 has_start_range_ = entry_.find(from_ascii("|(")) != lyx::docstring::npos;
1519 has_end_range_ = entry_.find(from_ascii("|)")) != lyx::docstring::npos;
1521 // - Remove the ranges from the command if they do not appear at the beginning.
1522 size_t range_index = 0;
1523 while ((range_index = command.find(from_utf8("|("), range_index)) != std::string::npos)
1524 command.erase(range_index, 1);
1526 while ((range_index = command.find(from_utf8("|)"), range_index)) != std::string::npos)
1527 command.erase(range_index, 1);
1529 // - Remove the ranges when they are the only vertical bar in the complete string.
1530 if (command[0] == '(' || command[0] == ')')
1531 command.erase(0, 1);
1533 // Handle see and seealso. As "see" is a prefix of "seealso", the order of the comparisons is important.
1534 // Both commands are mutually exclusive!
1535 if (command.substr(0, 3) == "see") {
1536 // Unescape brackets.
1537 size_t index_argument_begin = 0;
1538 while ((index_argument_begin = command.find(from_utf8("\\{"), index_argument_begin)) != std::string::npos)
1539 command.erase(index_argument_begin, 1);
1540 size_t index_argument_end = 0;
1541 while ((index_argument_end = command.find(from_utf8("\\}"), index_argument_end)) != std::string::npos)
1542 command.erase(index_argument_end, 1);
1544 // Retrieve the part between brackets, and remove the complete seealso.
1545 size_t position_opening_bracket = command.find(from_ascii("{"));
1546 size_t position_closing_bracket = command.find(from_ascii("}"));
1547 docstring argument = command.substr(position_opening_bracket + 1,
1548 position_closing_bracket - position_opening_bracket - 1);
1550 // Parse the argument of referenced entries (or a single one for see).
1551 if (command.substr(0, 7) == "seealso") {
1552 see_alsoes_ = getVectorFromString(argument, from_ascii(","), false);
1556 if (see_.find(from_ascii(",")) != std::string::npos) {
1557 output_error_ += from_utf8("Several index_argument_end terms found as \"see\"! Only one is "
1558 "acceptable. Complete entry: \"") + entry_ + from_utf8("\". ");
1562 // Remove the complete see/seealso from the commands, in case there is something else to parse.
1563 command = command.substr(position_closing_bracket + 1);
1566 // Some parts of the strings are not parsed, as they do not have anything matching in DocBook or XHTML:
1567 // things like formatting the entry or the page number, other strings for sorting.
1568 // https://wiki.lyx.org/Tips/Indexing
1569 // If there are such things in the index entry, then this code may miserably fail. For example, for
1570 // "Peter|(textbf", no range will be detected.
1571 if (!command.empty()) {
1572 output_error_ += from_utf8("Unsupported feature: an index entry contains a | with an unsupported command, ")
1573 + command + from_utf8(". Complete entry: \"") + entry_ + from_utf8("\". ");
1579 return terms_.size();
1582 const std::vector<docstring>& terms() const {
1586 std::vector<docstring>& terms() {
1590 const InsetIndex* inset() const {
1595 // Input inset. These should only be used when parsing the inset (either parseAsModern or parseAsLegacy, called in
1596 // the constructor).
1597 const InsetIndex * inset_;
1598 OutputParams const * runparams_;
1600 docstring index_; // Useful when there are multiple indices in the same document.
1602 // Errors, concatenated as a single string, available as soon as parsing is done, const afterwards (i.e. once
1603 // constructor is done).
1604 docstring output_error_;
1606 // Parsed index entry.
1607 std::vector<docstring> terms_; // Up to three entries, in general.
1610 bool has_start_range_;
1611 bool has_end_range_;
1613 vector<docstring> see_alsoes_;
1615 // Operators used for sorting entries (alphabetical order).
1616 friend bool operator<(IndexEntry const & lhs, IndexEntry const & rhs);
1619 bool operator<(IndexEntry const & lhs, IndexEntry const & rhs)
1621 if (lhs.terms_.empty())
1624 for (unsigned i = 0; i < min(rhs.terms_.size(), lhs.terms_.size()); ++i) {
1625 int comp = compare_no_case(lhs.terms_[i], rhs.terms_[i]);
1634 std::string generateCssClassAtDepth(unsigned depth) {
1635 std::string css_class = "entry";
1639 css_class.insert(0, "sub");
1646 std::vector<IndexEntry> entries;
1647 std::vector<IndexNode*> children;
1650 for (IndexNode * child : children) {
1658 docstring termAtLevel(const IndexNode* node, unsigned depth)
1660 // 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
1661 // function could be made constant time by copying the term in each node, but that would make data duplication that
1662 // may fall out of sync; the performance benefit would probably be negligible.
1663 if (!node->entries.empty()) {
1664 LASSERT(node->entries.begin()->terms().size() >= depth + 1, return from_ascii(""));
1665 return node->entries.begin()->terms()[depth];
1668 if (!node->children.empty()) {
1669 return termAtLevel(*node->children.begin(), depth);
1672 LASSERT(false, return from_ascii(""));
1675 void insertIntoNode(const IndexEntry& entry, IndexNode* node, unsigned depth = 0)
1677 // Do not insert empty entries.
1678 if (entry.terms().empty())
1681 // depth == 0 is for the root, not yet the index, hence the increase when going to vector size.
1682 for (IndexNode* child : node->children) {
1683 if (entry.terms()[depth] == termAtLevel(child, depth)) {
1684 if (depth + 1 == entry.terms().size()) { // == child.entries.begin()->terms().size()
1685 // All term entries match: it's an entry.
1686 if (!entry.terms()[depth].empty())
1687 child->entries.emplace_back(entry);
1690 insertIntoNode(entry, child, depth + 1);
1696 // Out of the loop: no matching child found, create a new (possibly nested) child for this entry. Due to the
1697 // possibility of nestedness, only insert the current entry when the right level is reached. This is needed if the
1698 // first entry for a word has several levels that never appeared.
1699 // In particular, this case is called for the first entry.
1700 IndexNode* new_node = node;
1702 new_node->children.emplace_back(new IndexNode{{}, {}});
1703 new_node = new_node->children.back();
1705 } while (depth + 1 <= entry.terms().size()); // depth == 0: root node, no text associated.
1706 new_node->entries.emplace_back(entry);
1709 IndexNode* buildIndexTree(vector<IndexEntry>& entries)
1711 // Sort the entries, first on the main entry, then the subentry, then the subsubentry,
1712 // thanks to the implementation of operator<.
1713 // If this operation is not performed, the algorithm below is no more correct (and ensuring that it works with
1714 // unsorted entries would make its complexity blow up).
1715 stable_sort(entries.begin(), entries.end());
1717 // Cook the index into a nice tree data structure: entries at a given level in the index as a node, with subentries
1719 auto* index_root = new IndexNode{{}, {}};
1720 for (const IndexEntry& entry : entries) {
1721 insertIntoNode(entry, index_root);
1727 void outputIndexPage(XMLStream & xs, const IndexNode* root_node, unsigned depth = 0) // NOLINT(misc-no-recursion)
1729 LASSERT(root_node->entries.size() + root_node->children.size() > 0, return);
1731 xs << xml::StartTag("li", "class='" + generateCssClassAtDepth(depth) + "'");
1733 xs << termAtLevel(root_node, depth);
1734 // By tree assumption, all the entries at this node have the same set of terms.
1736 if (!root_node->entries.empty()) {
1737 xs << XMLStream::ESCAPE_NONE << " — "; // Em dash, i.e. long (---).
1738 unsigned entry_number = 1;
1740 auto writeLinkToEntry = [&xs](const IndexEntry &entry, unsigned entry_number) {
1741 std::string const link_attr = "href='#" + entry.inset()->paragraphs()[0].magicLabel() + "'";
1742 xs << xml::StartTag("a", link_attr);
1743 xs << from_ascii(std::to_string(entry_number));
1744 xs << xml::EndTag("a");
1747 for (unsigned i = 0; i < root_node->entries.size(); ++i) {
1748 const IndexEntry &entry = root_node->entries[i];
1750 switch (entry.inset()->params().range) {
1751 case InsetIndexParams::PageRange::None:
1752 writeLinkToEntry(entry, entry_number);
1754 case InsetIndexParams::PageRange::Start: {
1755 // Try to find the end of the range, if it is just after. Otherwise, the output will be slightly
1756 // scrambled, but understandable. Doing better would mean implementing more of the indexing logic here
1757 // and more complex indexing here (skipping the end is not just incrementing i). Worst case output:
1759 const bool nextEntryIsEnd = i + 1 < root_node->entries.size() &&
1760 root_node->entries[i + 1].inset()->params().range ==
1761 InsetIndexParams::PageRange::End;
1762 // No need to check if both entries are for the same terms: they are in the same IndexNode.
1764 writeLinkToEntry(entry, entry_number);
1765 xs << XMLStream::ESCAPE_NONE << " – "; // En dash, i.e. semi-long (--).
1767 if (nextEntryIsEnd) {
1768 // Skip the next entry in the loop, write it right now, after the dash.
1771 writeLinkToEntry(root_node->entries[i], entry_number);
1775 case InsetIndexParams::PageRange::End:
1776 // This range end was not caught by the range start, do it now to avoid losing content.
1777 xs << XMLStream::ESCAPE_NONE << " – "; // En dash, i.e. semi-long (--).
1778 writeLinkToEntry(root_node->entries[i], entry_number);
1781 if (i < root_node->entries.size() - 1) {
1789 if (!root_node->entries.empty() && !root_node->children.empty()) {
1793 if (!root_node->children.empty()) {
1794 xs << xml::StartTag("ul", "class='" + generateCssClassAtDepth(depth) + "'");
1797 for (const IndexNode* child : root_node->children) {
1798 outputIndexPage(xs, child, depth + 1);
1801 xs << xml::EndTag("ul");
1805 xs << xml::EndTag("li");
1809 #ifdef LYX_INSET_INDEX_DEBUG
1810 void printTree(const IndexNode* root_node, unsigned depth = 0)
1812 static const std::string pattern = " ";
1814 for (unsigned i = 0; i < depth; ++i) {
1817 const std::string prefix_long = prefix + pattern + pattern;
1819 docstring term_at_level;
1821 // The root has no term.
1822 std::cout << "<ROOT>" << std::endl;
1824 LASSERT(depth - 1 <= 10, return); // Check for overflows.
1825 term_at_level = termAtLevel(root_node, depth - 1);
1826 std::cout << prefix << to_utf8(term_at_level) << " (x " << std::to_string(root_node->entries.size()) << ")"
1830 for (const IndexEntry& entry : root_node->entries) {
1831 if (entry.terms().size() != depth) {
1832 std::cout << prefix_long << "ERROR: an entry doesn't have the same number of terms" << std::endl;
1834 if (depth > 0 && entry.terms()[depth - 1] != term_at_level) {
1835 std::cout << prefix_long << "ERROR: an entry doesn't have the right term at depth " << std::to_string(depth)
1840 for (const IndexNode* node : root_node->children) {
1841 printTree(node, depth + 1);
1844 #endif // LYX_INSET_INDEX_DEBUG
1848 docstring InsetPrintIndex::xhtml(XMLStream &, OutputParams const & op) const
1850 BufferParams const & bp = buffer().masterBuffer()->params();
1852 shared_ptr<Toc const> toc = buffer().tocBackend().toc("index");
1856 // Collect the index entries in a form we can use them.
1857 vector<IndexEntry> entries;
1858 const docstring defaultIndexType = from_ascii("idx");
1859 const docstring & indexType = params().getParamOr("type", defaultIndexType);
1860 for (const TocItem& item : *toc) {
1861 const auto* inset = static_cast<const InsetIndex*>(&(item.dit().inset()));
1862 if (item.isOutput() && inset && inset->params().index == indexType)
1863 entries.emplace_back(IndexEntry{inset, &op});
1866 // If all the index entries are in notes or not displayed, get out sooner.
1867 if (entries.empty())
1870 const IndexNode* index_root = buildIndexTree(entries);
1871 #ifdef LYX_INSET_INDEX_DEBUG
1872 printTree(index_root);
1875 // Start generating the XHTML index.
1876 Layout const & lay = bp.documentClass().htmlTOCLayout();
1877 string const & tocclass = lay.defaultCSSClass();
1878 string const tocattr = "class='index " + tocclass + "'";
1879 docstring const indexName = params().getParamOr("name", from_ascii("Index"));
1881 // we'll use our own stream, because we are going to defer everything.
1882 // that's how we deal with the fact that we're probably inside a standard
1883 // paragraph, and we don't want to be.
1884 odocstringstream ods;
1887 xs << xml::StartTag("div", tocattr);
1889 xs << xml::StartTag(lay.htmltag(), lay.htmlGetAttrString());
1890 xs << translateIfPossible(indexName, op.local_font->language()->lang());
1891 xs << xml::EndTag(lay.htmltag());
1893 xs << xml::StartTag("ul", "class='main'");
1896 LASSERT(index_root->entries.empty(), return docstring()); // No index entry should have zero terms.
1897 for (const IndexNode* node : index_root->children) {
1898 outputIndexPage(xs, node);
1902 xs << xml::EndTag("ul");
1904 xs << xml::EndTag("div");