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 if (const vector<docstring> potential_terms = getSubentriesAsText(runparams); !potential_terms.empty()) {
377 terms = potential_terms;
378 // The main term is not present in the vector, as it's not a subentry. The main index term is inserted raw in
379 // the index inset. Considering that the user either uses the new or the legacy mechanism, the main term is the
380 // full string within this inset (i.e. without the subinsets).
381 terms.insert(terms.begin(), latexString);
383 terms = getVectorFromString(indexTerms, from_ascii("!"), false);
386 // Handle ranges. Happily, in the raw LaTeX mode, (| and |) can only be at the end of the string!
387 const bool hasInsetRange = params_.range != InsetIndexParams::PageRange::None;
388 const bool hasStartRange = params_.range == InsetIndexParams::PageRange::Start ||
389 latexString.find(from_ascii("|(")) != lyx::docstring::npos;
390 const bool hasEndRange = params_.range == InsetIndexParams::PageRange::End ||
391 latexString.find(from_ascii("|)")) != lyx::docstring::npos;
394 // Remove the ranges from the command if they do not appear at the beginning.
396 while ((index = command.find(from_utf8("|("), index)) != std::string::npos)
397 command.erase(index, 1);
399 while ((index = command.find(from_utf8("|)"), index)) != std::string::npos)
400 command.erase(index, 1);
402 // Remove the ranges when they are the only vertical bar in the complete string.
403 if (command[0] == '(' || command[0] == ')')
407 // Handle see and seealso. As "see" is a prefix of "seealso", the order of the comparisons is important.
408 // Both commands are mutually exclusive!
409 docstring see = getSeeAsText(runparams);
410 vector<docstring> seeAlsoes = getSeeAlsoesAsText(runparams);
412 if (see.empty() && seeAlsoes.empty() && command.substr(0, 3) == "see") {
413 // Unescape brackets.
415 while ((index = command.find(from_utf8("\\{"), index)) != std::string::npos)
416 command.erase(index, 1);
418 while ((index = command.find(from_utf8("\\}"), index)) != std::string::npos)
419 command.erase(index, 1);
421 // Retrieve the part between brackets, and remove the complete seealso.
422 size_t positionOpeningBracket = command.find(from_ascii("{"));
423 size_t positionClosingBracket = command.find(from_ascii("}"));
424 docstring list = command.substr(positionOpeningBracket + 1, positionClosingBracket - positionOpeningBracket - 1);
426 // Parse the list of referenced entries (or a single one for see).
427 if (command.substr(0, 7) == "seealso") {
428 seeAlsoes = getVectorFromString(list, from_ascii(","), false);
432 if (see.find(from_ascii(",")) != std::string::npos) {
433 docstring error = from_utf8("Several index terms found as \"see\"! Only one is acceptable. "
434 "Complete entry: \"") + latexString + from_utf8("\"");
436 xs << XMLStream::ESCAPE_NONE << (from_utf8("<!-- Output Error: ") + error + from_utf8(" -->\n"));
440 // Remove the complete see/seealso from the commands, in case there is something else to parse.
441 command = command.substr(positionClosingBracket + 1);
444 // Some parts of the strings are not parsed, as they do not have anything matching in DocBook: things like
445 // formatting the entry or the page number, other strings for sorting. https://wiki.lyx.org/Tips/Indexing
446 // If there are such things in the index entry, then this code may miserably fail. For example, for "Peter|(textbf",
447 // no range will be detected.
448 // TODO: Could handle formatting as significance="preferred"?
449 if (!command.empty()) {
450 docstring error = from_utf8("Unsupported feature: an index entry contains a | with an unsupported command, ")
451 + command + from_utf8(". ") + from_utf8("Complete entry: \"") + latexString + from_utf8("\"");
453 xs << XMLStream::ESCAPE_NONE << (from_utf8("<!-- Output Error: ") + error + from_utf8(" -->\n"));
456 // Write all of this down.
457 if (terms.empty() && !hasEndRange) {
458 docstring error = from_utf8("No index term found! Complete entry: \"") + latexString + from_utf8("\"");
460 xs << XMLStream::ESCAPE_NONE << (from_utf8("<!-- Output Error: ") + error + from_utf8(" -->\n"));
462 // Generate the attributes for ranges. It is based on the terms that are indexed, but the ID must be unique
463 // to this indexing area (xml::cleanID does not guarantee this: for each call with the same arguments,
464 // the same legal ID is produced; here, as the input would be the same, the output must be, by design).
465 // Hence the thread-local storage, as the numbers must strictly be unique, and thus cannot be shared across
466 // a paragraph (making the solution used for HTML worthless). This solution is very similar to the one used in
468 // indexType can only be used for singular and startofrange types!
470 if (!hasStartRange && !hasEndRange) {
473 // Append an ID if uniqueness is not guaranteed across the document.
474 static QThreadStorage<set<docstring>> tKnownTermLists;
475 static QThreadStorage<int> tID;
477 set<docstring> &knownTermLists = tKnownTermLists.localData();
478 int &ID = tID.localData();
480 if (!tID.hasLocalData()) {
484 // Modify the index terms to add the unique ID if needed.
485 docstring newIndexTerms = indexTerms;
486 if (knownTermLists.find(indexTerms) != knownTermLists.end()) {
487 newIndexTerms += from_ascii(string("-") + to_string(ID));
489 // Only increment for the end of range, so that the same number is used for the start of range.
495 // Term list not yet known: add it to the set AFTER the end of range. After
496 if (knownTermLists.find(indexTerms) == knownTermLists.end() && hasEndRange) {
497 knownTermLists.insert(indexTerms);
500 // Generate the attributes.
501 docstring id = xml::cleanID(newIndexTerms);
503 attrs = indexType + " class=\"startofrange\" xml:id=\"" + id + "\"";
505 attrs = " class=\"endofrange\" startref=\"" + id + "\"";
509 // Handle the index terms (including the specific index for this entry).
511 xs << xml::CompTag("indexterm", attrs);
513 xs << xml::StartTag("indexterm", attrs);
514 if (!terms.empty()) { // hasEndRange has no content.
516 if (!sortAs.empty()) {
517 attr = from_utf8("sortas='") + sortAs + from_utf8("'");
520 xs << xml::StartTag("primary", attr);
522 xs << xml::EndTag("primary");
524 if (terms.size() > 1) {
525 xs << xml::StartTag("secondary");
527 xs << xml::EndTag("secondary");
529 if (terms.size() > 2) {
530 xs << xml::StartTag("tertiary");
532 xs << xml::EndTag("tertiary");
535 // Handle see and see also.
537 xs << xml::StartTag("see");
539 xs << xml::EndTag("see");
542 if (!seeAlsoes.empty()) {
543 for (auto &entry : seeAlsoes) {
544 xs << xml::StartTag("seealso");
546 xs << xml::EndTag("seealso");
551 xs << xml::EndTag("indexterm");
557 docstring InsetIndex::xhtml(XMLStream & xs, OutputParams const &) const
559 // we just print an anchor, taking the paragraph ID from
560 // our own interior paragraph, which doesn't get printed
561 std::string const magic = paragraphs().front().magicLabel();
562 std::string const attr = "id='" + magic + "'";
563 xs << xml::CompTag("a", attr);
568 bool InsetIndex::showInsetDialog(BufferView * bv) const
570 bv->showDialog("index", params2string(params_),
571 const_cast<InsetIndex *>(this));
576 void InsetIndex::doDispatch(Cursor & cur, FuncRequest & cmd)
578 switch (cmd.action()) {
580 case LFUN_INSET_MODIFY: {
581 if (cmd.getArg(0) == "changetype") {
582 cur.recordUndoInset(this);
583 params_.index = from_utf8(cmd.getArg(1));
586 if (cmd.getArg(0) == "changeparam") {
587 string const p = cmd.getArg(1);
588 string const v = cmd.getArg(2);
589 cur.recordUndoInset(this);
591 params_.range = insetindexpagerangetranslator().find(v);
592 if (p == "pagefmt") {
593 if (v == "default" || v == "textbf"
594 || v == "textit" || v == "emph")
597 lyx::dispatch(FuncRequest(LFUN_INSET_SETTINGS, "index"));
601 InsetIndexParams params;
602 InsetIndex::string2params(to_utf8(cmd.argument()), params);
603 cur.recordUndoInset(this);
604 params_.index = params.index;
605 params_.range = params.range;
606 params_.pagefmt = params.pagefmt;
607 // what we really want here is a TOC update, but that means
608 // a full buffer update
609 cur.forceBufferUpdate();
613 case LFUN_INSET_DIALOG_UPDATE:
614 cur.bv().updateDialog("index", params2string(params_));
617 case LFUN_PARAGRAPH_BREAK: {
618 // Since this inset in single-par anyway, let's use
619 // return to enter subentries
620 FuncRequest fr(LFUN_INDEXMACRO_INSERT, "subentry");
625 case LFUN_INSET_INSERT_COPY: {
626 Cursor & bvcur = cur.bv().cursor();
627 if (cmd.origin() == FuncRequest::TOC && bvcur.inTexted()) {
628 cap::copyInsetToTemp(cur, clone());
629 cap::pasteFromTemp(bvcur, bvcur.buffer()->errorList("Paste"));
636 InsetCollapsible::doDispatch(cur, cmd);
642 bool InsetIndex::getStatus(Cursor & cur, FuncRequest const & cmd,
643 FuncStatus & flag) const
645 switch (cmd.action()) {
647 case LFUN_INSET_MODIFY:
648 if (cmd.getArg(0) == "changetype") {
649 docstring const newtype = from_utf8(cmd.getArg(1));
650 Buffer const & realbuffer = *buffer().masterBuffer();
651 IndicesList const & indiceslist = realbuffer.params().indiceslist();
652 Index const * index = indiceslist.findShortcut(newtype);
653 flag.setEnabled(index != 0);
655 from_utf8(cmd.getArg(1)) == params_.index);
658 if (cmd.getArg(0) == "changeparam") {
659 string const p = cmd.getArg(1);
660 string const v = cmd.getArg(2);
662 flag.setEnabled(v == "none" || v == "start" || v == "end");
663 flag.setOnOff(params_.range == insetindexpagerangetranslator().find(v));
665 if (p == "pagefmt") {
666 flag.setEnabled(!v.empty());
667 if (params_.pagefmt == "default" || params_.pagefmt == "textbf"
668 || params_.pagefmt == "textit" || params_.pagefmt == "emph")
669 flag.setOnOff(params_.pagefmt == v);
671 flag.setOnOff(v == "custom");
675 return InsetCollapsible::getStatus(cur, cmd, flag);
677 case LFUN_INSET_DIALOG_UPDATE: {
678 Buffer const & realbuffer = *buffer().masterBuffer();
679 flag.setEnabled(realbuffer.params().use_indices);
683 case LFUN_INSET_INSERT_COPY:
684 // This can only be invoked by ToC widget
685 flag.setEnabled(cmd.origin() == FuncRequest::TOC
686 && cur.bv().cursor().inset().insetAllowed(lyxCode()));
689 case LFUN_PARAGRAPH_BREAK:
690 return macrosPossible("subentry");
692 case LFUN_INDEXMACRO_INSERT:
693 return macrosPossible(cmd.getArg(0));
695 case LFUN_INDEX_TAG_ALL:
699 return InsetCollapsible::getStatus(cur, cmd, flag);
704 void InsetIndex::getSortkey(otexstream & os, OutputParams const & runparams) const
706 Paragraph const & par = paragraphs().front();
707 InsetList::const_iterator it = par.insetList().begin();
708 for (; it != par.insetList().end(); ++it) {
709 Inset & inset = *it->inset;
710 if (inset.lyxCode() == INDEXMACRO_SORTKEY_CODE) {
711 InsetIndexMacro const & iim =
712 static_cast<InsetIndexMacro const &>(inset);
713 iim.getLatex(os, runparams);
720 docstring InsetIndex::getSortkeyAsText(OutputParams const & runparams) const
722 Paragraph const & par = paragraphs().front();
723 InsetList::const_iterator it = par.insetList().begin();
724 for (; it != par.insetList().end(); ++it) {
725 Inset & inset = *it->inset;
726 if (inset.lyxCode() == INDEXMACRO_SORTKEY_CODE) {
728 InsetIndexMacro const & iim =
729 static_cast<InsetIndexMacro const &>(inset);
730 iim.getLatex(os, runparams);
734 return from_ascii("");
738 void InsetIndex::emptySubentriesWarning(docstring const & mainentry) const
740 // Empty subentries crash makeindex. So warn and ignore this.
742 ErrorList & errorList = buffer().errorList("Export");
743 docstring const s = bformat(_("There is an empty index subentry in the entry '%1$s'.\n"
744 "It will be ignored in the output."), mainentry);
745 Paragraph const & par = buffer().paragraphs().front();
746 errorList.push_back(ErrorItem(_("Empty index subentry!"), s,
747 {par.id(), 0}, {par.id(), -1}));
748 buffer().bufferErrors(terr, errorList);
752 void InsetIndex::getSubentries(otexstream & os, OutputParams const & runparams,
753 docstring const & mainentry) const
755 Paragraph const & par = paragraphs().front();
756 InsetList::const_iterator it = par.insetList().begin();
758 for (; it != par.insetList().end(); ++it) {
759 Inset & inset = *it->inset;
760 if (inset.lyxCode() == INDEXMACRO_CODE) {
761 InsetIndexMacro const & iim =
762 static_cast<InsetIndexMacro const &>(inset);
763 if (iim.params().type == InsetIndexMacroParams::Subentry) {
764 if (iim.hasNoContent()) {
765 emptySubentriesWarning(mainentry);
772 iim.getLatex(os, runparams);
779 std::vector<docstring> InsetIndex::getSubentriesAsText(OutputParams const & runparams,
780 bool const asLabel) const
782 std::vector<docstring> subentries;
784 Paragraph const & par = paragraphs().front();
785 InsetList::const_iterator it = par.insetList().begin();
787 for (; it != par.insetList().end(); ++it) {
788 Inset & inset = *it->inset;
789 if (inset.lyxCode() == INDEXMACRO_CODE) {
790 InsetIndexMacro const & iim =
791 static_cast<InsetIndexMacro const &>(inset);
792 if (iim.params().type == InsetIndexMacroParams::Subentry) {
798 docstring const sl = iim.getNewLabel(l);
799 subentries.emplace_back(sl);
802 iim.getLatex(os, runparams);
803 subentries.emplace_back(os.str());
813 docstring InsetIndex::getMainSubentryAsText(OutputParams const & runparams) const
816 InsetText::latex(os, runparams);
821 void InsetIndex::getSeeRefs(otexstream & os, OutputParams const & runparams) 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
831 || iim.params().type == InsetIndexMacroParams::Seealso) {
832 iim.getLatex(os, runparams);
840 docstring InsetIndex::getSeeAsText(OutputParams const & runparams,
841 bool const asLabel) const
843 Paragraph const & par = paragraphs().front();
844 InsetList::const_iterator it = par.insetList().begin();
845 for (; it != par.insetList().end(); ++it) {
846 Inset & inset = *it->inset;
847 if (inset.lyxCode() == INDEXMACRO_CODE) {
848 InsetIndexMacro const & iim =
849 static_cast<InsetIndexMacro const &>(inset);
850 if (iim.params().type == InsetIndexMacroParams::See) {
853 return iim.getNewLabel(l);
856 iim.getLatex(os, runparams);
862 return from_ascii("");
866 std::vector<docstring> InsetIndex::getSeeAlsoesAsText(OutputParams const & runparams,
867 bool const asLabel) const
869 std::vector<docstring> seeAlsoes;
871 Paragraph const & par = paragraphs().front();
872 InsetList::const_iterator it = par.insetList().begin();
873 for (; it != par.insetList().end(); ++it) {
874 Inset & inset = *it->inset;
875 if (inset.lyxCode() == INDEXMACRO_CODE) {
876 InsetIndexMacro const & iim =
877 static_cast<InsetIndexMacro const &>(inset);
878 if (iim.params().type == InsetIndexMacroParams::Seealso) {
881 seeAlsoes.emplace_back(iim.getNewLabel(l));
884 iim.getLatex(os, runparams);
885 seeAlsoes.emplace_back(os.str());
897 bool hasInsetWithCode(const InsetIndex * const inset_index, const InsetCode code,
898 const std::set<InsetIndexMacroParams::Type> types = {})
900 Paragraph const & par = inset_index->paragraphs().front();
901 InsetList::const_iterator it = par.insetList().begin();
902 for (; it != par.insetList().end(); ++it) {
903 Inset & inset = *it->inset;
904 if (inset.lyxCode() == code) {
908 LASSERT(code == INDEXMACRO_CODE, return false);
909 InsetIndexMacro const & iim =
910 static_cast<InsetIndexMacro const &>(inset);
911 if (types.find(iim.params().type) != types.end())
921 bool InsetIndex::hasSubentries() const
923 return hasInsetWithCode(this, INDEXMACRO_CODE, {InsetIndexMacroParams::Subentry});
927 bool InsetIndex::hasSeeRef() const
929 return hasInsetWithCode(this, INDEXMACRO_CODE, {InsetIndexMacroParams::See, InsetIndexMacroParams::Seealso});
933 bool InsetIndex::hasSortKey() const
935 return hasInsetWithCode(this, INDEXMACRO_SORTKEY_CODE);
939 bool InsetIndex::macrosPossible(string const type) const
941 if (type != "see" && type != "seealso"
942 && type != "sortkey" && type != "subentry")
945 Paragraph const & par = paragraphs().front();
946 InsetList::const_iterator it = par.insetList().begin();
948 for (; it != par.insetList().end(); ++it) {
949 Inset & inset = *it->inset;
950 if (type == "sortkey" && inset.lyxCode() == INDEXMACRO_SORTKEY_CODE)
952 if (inset.lyxCode() == INDEXMACRO_CODE) {
953 InsetIndexMacro const & iim = static_cast<InsetIndexMacro const &>(inset);
954 if ((type == "see" || type == "seealso")
955 && (iim.params().type == InsetIndexMacroParams::See
956 || iim.params().type == InsetIndexMacroParams::Seealso))
958 if (type == "subentry"
959 && iim.params().type == InsetIndexMacroParams::Subentry) {
970 ColorCode InsetIndex::labelColor() const
972 if (params_.index.empty() || params_.index == from_ascii("idx"))
973 return InsetCollapsible::labelColor();
975 ColorCode c = lcolor.getFromLyXName(to_utf8(params_.index)
976 + "@" + buffer().fileName().absFileName());
978 c = InsetCollapsible::labelColor();
983 docstring InsetIndex::toolTip(BufferView const &, int, int) const
985 docstring tip = _("Index Entry");
986 if (buffer().params().use_indices && !params_.index.empty()) {
987 Buffer const & realbuffer = *buffer().masterBuffer();
988 IndicesList const & indiceslist = realbuffer.params().indiceslist();
990 Index const * index = indiceslist.findShortcut(params_.index);
992 tip += _("unknown type!");
994 tip += index->index();
998 docstring res = toolTipText(tip);
999 if (!insetindexpagerangetranslator_loc().find(params_.range).empty())
1000 res += "\n" + insetindexpagerangetranslator_loc().find(params_.range);
1001 if (!params_.pagefmt.empty() && params_.pagefmt != "default") {
1002 res += "\n" + _("Pagination format:") + " ";
1003 if (params_.pagefmt == "textbf")
1005 else if (params_.pagefmt == "textit")
1007 else if (params_.pagefmt == "emph")
1008 res += _("emphasized");
1010 res += from_utf8(params_.pagefmt);
1016 docstring const InsetIndex::buttonLabel(BufferView const & bv) const
1018 InsetLayout const & il = getLayout();
1019 docstring label = translateIfPossible(il.labelstring());
1021 if (buffer().params().use_indices && !params_.index.empty()) {
1022 Buffer const & realbuffer = *buffer().masterBuffer();
1023 IndicesList const & indiceslist = realbuffer.params().indiceslist();
1025 Index const * index = indiceslist.findShortcut(params_.index);
1027 label += _("unknown type!");
1029 label += index->index();
1034 if (!il.contentaslabel() || geometry(bv) != ButtonOnly)
1037 res = getNewLabel(label);
1038 OutputParams const rp(0);
1039 vector<docstring> sublbls = getSubentriesAsText(rp, true);
1040 for (auto const & sublbl : sublbls) {
1041 res += " " + docstring(1, char_type(0x2023));// TRIANGULAR BULLET
1042 res += " " + sublbl;
1044 docstring see = getSeeAsText(rp, true);
1045 if (see.empty() && !getSeeAlsoesAsText(rp, true).empty())
1046 see = getSeeAlsoesAsText(rp, true).front();
1048 res += " " + docstring(1, char_type(0x261e));// WHITE RIGHT POINTING INDEX
1052 if (!insetindexpagerangetranslator_latex().find(params_.range).empty())
1053 res += " " + from_ascii(insetindexpagerangetranslator_latex().find(params_.range));
1058 void InsetIndex::write(ostream & os) const
1060 os << to_utf8(layoutName());
1062 InsetCollapsible::write(os);
1066 void InsetIndex::read(Lexer & lex)
1069 InsetCollapsible::read(lex);
1073 string InsetIndex::params2string(InsetIndexParams const & params)
1082 void InsetIndex::string2params(string const & in, InsetIndexParams & params)
1084 params = InsetIndexParams();
1088 istringstream data(in);
1090 lex.setStream(data);
1091 lex.setContext("InsetIndex::string2params");
1097 void InsetIndex::addToToc(DocIterator const & cpit, bool output_active,
1098 UpdateType utype, TocBackend & backend) const
1100 DocIterator pit = cpit;
1101 pit.push_back(CursorSlice(const_cast<InsetIndex &>(*this)));
1103 InsetLayout const & il = getLayout();
1104 docstring label = translateIfPossible(il.labelstring());
1105 if (!il.contentaslabel())
1108 str = getNewLabel(label);
1109 OutputParams const rp(0);
1110 vector<docstring> sublbls = getSubentriesAsText(rp, true);
1111 for (auto const & sublbl : sublbls) {
1112 str += " " + docstring(1, char_type(0x2023));// TRIANGULAR BULLET
1113 str += " " + sublbl;
1115 docstring see = getSeeAsText(rp, true);
1116 if (see.empty() && !getSeeAlsoesAsText(rp, true).empty())
1117 see = getSeeAlsoesAsText(rp, true).front();
1119 str += " " + docstring(1, char_type(0x261e));// WHITE RIGHT POINTING INDEX
1123 string type = "index";
1124 if (buffer().masterBuffer()->params().use_indices)
1125 type += ":" + to_utf8(params_.index);
1126 TocBuilder & b = backend.builder(type);
1127 b.pushItem(pit, str, output_active);
1128 // Proceed with the rest of the inset.
1129 InsetCollapsible::addToToc(cpit, output_active, utype, backend);
1134 void InsetIndex::validate(LaTeXFeatures & features) const
1136 if (buffer().masterBuffer()->params().use_indices
1137 && !params_.index.empty()
1138 && params_.index != "idx")
1139 features.require("splitidx");
1140 InsetCollapsible::validate(features);
1144 string InsetIndex::contextMenuName() const
1146 return "context-index";
1150 string InsetIndex::contextMenu(BufferView const & bv, int x, int y) const
1152 // We override the implementation of InsetCollapsible,
1153 // because we have eytra entries.
1154 string owncm = "context-edit-index;";
1155 return owncm + InsetCollapsible::contextMenu(bv, x, y);
1159 bool InsetIndex::hasSettings() const
1165 bool InsetIndex::insetAllowed(InsetCode code) const
1168 case INDEXMACRO_CODE:
1169 case INDEXMACRO_SORTKEY_CODE:
1174 return InsetCollapsible::insetAllowed(code);
1179 /////////////////////////////////////////////////////////////////////
1183 ///////////////////////////////////////////////////////////////////////
1186 void InsetIndexParams::write(ostream & os) const
1190 os << to_utf8(index);
1195 << insetindexpagerangetranslator().find(range)
1203 void InsetIndexParams::read(Lexer & lex)
1206 index = lex.getDocString();
1208 index = from_ascii("idx");
1209 if (lex.checkFor("range")) {
1210 string st = lex.getString();
1211 if (lex.eatLine()) {
1212 st = lex.getString();
1213 range = insetindexpagerangetranslator().find(lex.getString());
1216 if (lex.checkFor("pageformat") && lex.eatLine()) {
1217 pagefmt = lex.getString();
1222 /////////////////////////////////////////////////////////////////////
1226 ///////////////////////////////////////////////////////////////////////
1228 InsetPrintIndex::InsetPrintIndex(Buffer * buf, InsetCommandParams const & p)
1229 : InsetCommand(buf, p)
1233 ParamInfo const & InsetPrintIndex::findInfo(string const & /* cmdName */)
1235 static ParamInfo param_info_;
1236 if (param_info_.empty()) {
1237 param_info_.add("type", ParamInfo::LATEX_OPTIONAL,
1238 ParamInfo::HANDLING_ESCAPE);
1239 param_info_.add("name", ParamInfo::LATEX_OPTIONAL,
1240 ParamInfo::HANDLING_LATEXIFY);
1241 param_info_.add("literal", ParamInfo::LYX_INTERNAL);
1247 docstring InsetPrintIndex::screenLabel() const
1249 bool const printall = suffixIs(getCmdName(), '*');
1250 bool const multind = buffer().masterBuffer()->params().use_indices;
1252 && getParam("type") == from_ascii("idx"))
1253 || (getParam("type").empty() && !printall))
1255 Buffer const & realbuffer = *buffer().masterBuffer();
1256 IndicesList const & indiceslist = realbuffer.params().indiceslist();
1257 Index const * index = indiceslist.findShortcut(getParam("type"));
1258 if (!index && !printall)
1259 return _("Unknown index type!");
1260 docstring res = printall ? _("All indexes") : index->index();
1262 res += " (" + _("non-active") + ")";
1263 else if (contains(getCmdName(), "printsubindex"))
1264 res += " (" + _("subindex") + ")";
1269 bool InsetPrintIndex::isCompatibleCommand(string const & s)
1271 return s == "printindex" || s == "printsubindex"
1272 || s == "printindex*" || s == "printsubindex*";
1276 void InsetPrintIndex::doDispatch(Cursor & cur, FuncRequest & cmd)
1278 switch (cmd.action()) {
1280 case LFUN_INSET_MODIFY: {
1281 if (cmd.argument() == from_ascii("toggle-subindex")) {
1282 string scmd = getCmdName();
1283 if (contains(scmd, "printindex"))
1284 scmd = subst(scmd, "printindex", "printsubindex");
1286 scmd = subst(scmd, "printsubindex", "printindex");
1290 } else if (cmd.argument() == from_ascii("check-printindex*")) {
1291 string scmd = getCmdName();
1292 if (suffixIs(scmd, '*'))
1296 setParam("type", docstring());
1300 InsetCommandParams p(INDEX_PRINT_CODE);
1302 InsetCommand::string2params(to_utf8(cmd.argument()), p);
1303 if (p.getCmdName().empty()) {
1304 cur.noScreenUpdate();
1313 InsetCommand::doDispatch(cur, cmd);
1319 bool InsetPrintIndex::getStatus(Cursor & cur, FuncRequest const & cmd,
1320 FuncStatus & status) const
1322 switch (cmd.action()) {
1324 case LFUN_INSET_MODIFY: {
1325 if (cmd.argument() == from_ascii("toggle-subindex")) {
1326 status.setEnabled(buffer().masterBuffer()->params().use_indices);
1327 status.setOnOff(contains(getCmdName(), "printsubindex"));
1329 } else if (cmd.argument() == from_ascii("check-printindex*")) {
1330 status.setEnabled(buffer().masterBuffer()->params().use_indices);
1331 status.setOnOff(suffixIs(getCmdName(), '*'));
1333 } if (cmd.getArg(0) == "index_print"
1334 && cmd.getArg(1) == "CommandInset") {
1335 InsetCommandParams p(INDEX_PRINT_CODE);
1336 InsetCommand::string2params(to_utf8(cmd.argument()), p);
1337 if (suffixIs(p.getCmdName(), '*')) {
1338 status.setEnabled(true);
1339 status.setOnOff(false);
1342 Buffer const & realbuffer = *buffer().masterBuffer();
1343 IndicesList const & indiceslist =
1344 realbuffer.params().indiceslist();
1345 Index const * index = indiceslist.findShortcut(p["type"]);
1346 status.setEnabled(index != 0);
1347 status.setOnOff(p["type"] == getParam("type"));
1350 return InsetCommand::getStatus(cur, cmd, status);
1353 case LFUN_INSET_DIALOG_UPDATE: {
1354 status.setEnabled(buffer().masterBuffer()->params().use_indices);
1359 return InsetCommand::getStatus(cur, cmd, status);
1364 void InsetPrintIndex::updateBuffer(ParIterator const &, UpdateType, bool const /*deleted*/)
1366 Index const * index =
1367 buffer().masterParams().indiceslist().findShortcut(getParam("type"));
1369 setParam("name", index->index());
1373 void InsetPrintIndex::latex(otexstream & os, OutputParams const & runparams_in) const
1375 if (!buffer().masterBuffer()->params().use_indices) {
1376 if (getParam("type") == from_ascii("idx"))
1377 os << "\\printindex" << termcmd;
1380 OutputParams runparams = runparams_in;
1381 os << getCommand(runparams);
1385 void InsetPrintIndex::validate(LaTeXFeatures & features) const
1387 features.require("makeidx");
1388 if (buffer().masterBuffer()->params().use_indices)
1389 features.require("splitidx");
1390 InsetCommand::validate(features);
1394 string InsetPrintIndex::contextMenuName() const
1396 return buffer().masterBuffer()->params().use_indices ?
1397 "context-indexprint" : string();
1401 bool InsetPrintIndex::hasSettings() const
1403 return buffer().masterBuffer()->params().use_indices;
1410 /// Builds an entry for the index.
1411 IndexEntry(const InsetIndex * inset, OutputParams const * runparams) : inset_(inset), runparams_(runparams)
1413 LASSERT(runparams, return);
1415 // Convert the inset as text. The resulting text usually only contains an XHTML anchor (<a id='...'/>) and text.
1416 odocstringstream entry;
1417 OutputParams ours = *runparams;
1418 ours.for_toc = false;
1419 inset_->plaintext(entry, ours);
1420 entry_ = entry.str();
1422 // Determine in which index this entry belongs to.
1423 if (inset_->buffer().masterBuffer()->params().use_indices) {
1424 index_ = inset_->params_.index;
1427 // Attempt parsing the inset.
1434 /// When parsing this entry, some errors may be found; they are reported as a single string.
1435 // It is up to the caller to send this string to LYXERR and the output file, as needed.
1436 const docstring & output_error() const
1438 return output_error_;
1441 void output_error(XMLStream xs) const
1443 LYXERR0(output_error());
1444 xs << XMLStream::ESCAPE_NONE << (from_utf8("<!-- Output Error: ") + output_error() + from_utf8(" -->\n"));
1451 #ifdef LYX_INSET_INDEX_DEBUG
1452 std::cout << to_utf8(entry_) << std::endl;
1453 #endif // LYX_INSET_INDEX_DEBUG
1455 // If a modern parameter is present, this is definitely a modern index inset. Similarly, if it contains the
1456 // usual LaTeX symbols (!|@), then it is definitely a legacy index inset. Otherwise, if it has features of
1457 // neither, it is both: consider this is a modern inset, to trigger the least complex code. Mixing both types
1458 // is not allowed (i.e. behaviour is undefined).
1459 const bool is_definitely_modern = inset_->hasSortKey() || inset_->hasSeeRef() || inset_->hasSubentries()
1460 || inset_->params_.range != InsetIndexParams::PageRange::None;
1461 const bool is_definitely_legacy = entry_.find('@') != std::string::npos
1462 || entry_.find('|') != std::string::npos || entry_.find('!') != std::string::npos;
1464 if (is_definitely_legacy && is_definitely_modern)
1465 output_error_ += from_utf8("Mix of index properties and raw LaTeX index commands is unsupported. ");
1468 // - is_definitely_modern == true:
1469 // - is_definitely_legacy == true: error (return whatever)
1470 // - is_definitely_legacy == false: return modern
1471 // - is_definitely_modern == false:
1472 // - is_definitely_legacy == true: return legacy
1473 // - is_definitely_legacy == false: return modern
1474 return !is_definitely_legacy;
1477 void parseAsModern()
1479 LASSERT(runparams_, return);
1481 if (inset_->hasSortKey()) {
1482 sort_as_ = inset_->getSortkeyAsText(*runparams_);
1485 terms_ = inset_->getSubentriesAsText(*runparams_);
1486 // The main term is not present in the vector, as it's not a subentry. The main index term is inserted raw in
1487 // the index inset. Considering that the user either uses the new or the legacy mechanism, the main term is the
1488 // full string within this inset (i.e. without the subinsets).
1489 terms_.insert(terms_.begin(), inset_->getMainSubentryAsText(*runparams_));
1491 has_start_range_ = inset_->params_.range == InsetIndexParams::PageRange::Start;
1492 has_end_range_ = inset_->params_.range == InsetIndexParams::PageRange::End;
1494 see_ = inset_->getSeeAsText(*runparams_);
1495 see_alsoes_ = inset_->getSeeAlsoesAsText(*runparams_);
1498 void parseAsLegacy() {
1499 // Determine if some features are known not to be supported. For now, this is only formatting like
1500 // \index{alpha@\textbf{alpha}} or \index{alpha@$\alpha$}.
1501 // @ is supported, but only for sorting, without specific formatting.
1502 if (entry_.find(from_utf8("@\\")) != lyx::docstring::npos) {
1503 output_error_ += from_utf8("Unsupported feature: an index entry contains an @\\. "
1504 "Complete entry: \"") + entry_ + from_utf8("\". ");
1506 if (entry_.find(from_utf8("@$")) != lyx::docstring::npos) {
1507 output_error_ += from_utf8("Unsupported feature: an index entry contains an @$. "
1508 "Complete entry: \"") + entry_ + from_utf8("\". ");
1511 // Split the string into its main constituents: terms, and command (see, see also, range).
1512 size_t positionVerticalBar = entry_.find(from_ascii("|")); // What comes before | is (sub)(sub)entries.
1513 docstring indexTerms = entry_.substr(0, positionVerticalBar);
1515 if (positionVerticalBar != lyx::docstring::npos) {
1516 command = entry_.substr(positionVerticalBar + 1);
1519 // Handle sorting issues, with @.
1520 vector<docstring> sortingElements = getVectorFromString(indexTerms, from_ascii("@"), false);
1521 if (sortingElements.size() == 2) {
1522 sort_as_ = sortingElements[0];
1523 indexTerms = sortingElements[1];
1526 // Handle entries, subentries, and subsubentries.
1527 terms_ = getVectorFromString(indexTerms, from_ascii("!"), false);
1529 // Handle ranges. Happily, (| and |) can only be at the end of the string!
1530 has_start_range_ = entry_.find(from_ascii("|(")) != lyx::docstring::npos;
1531 has_end_range_ = entry_.find(from_ascii("|)")) != lyx::docstring::npos;
1533 // - Remove the ranges from the command if they do not appear at the beginning.
1534 size_t range_index = 0;
1535 while ((range_index = command.find(from_utf8("|("), range_index)) != std::string::npos)
1536 command.erase(range_index, 1);
1538 while ((range_index = command.find(from_utf8("|)"), range_index)) != std::string::npos)
1539 command.erase(range_index, 1);
1541 // - Remove the ranges when they are the only vertical bar in the complete string.
1542 if (command[0] == '(' || command[0] == ')')
1543 command.erase(0, 1);
1545 // Handle see and seealso. As "see" is a prefix of "seealso", the order of the comparisons is important.
1546 // Both commands are mutually exclusive!
1547 if (command.substr(0, 3) == "see") {
1548 // Unescape brackets.
1549 size_t index_argument_begin = 0;
1550 while ((index_argument_begin = command.find(from_utf8("\\{"), index_argument_begin)) != std::string::npos)
1551 command.erase(index_argument_begin, 1);
1552 size_t index_argument_end = 0;
1553 while ((index_argument_end = command.find(from_utf8("\\}"), index_argument_end)) != std::string::npos)
1554 command.erase(index_argument_end, 1);
1556 // Retrieve the part between brackets, and remove the complete seealso.
1557 size_t position_opening_bracket = command.find(from_ascii("{"));
1558 size_t position_closing_bracket = command.find(from_ascii("}"));
1559 docstring argument = command.substr(position_opening_bracket + 1,
1560 position_closing_bracket - position_opening_bracket - 1);
1562 // Parse the argument of referenced entries (or a single one for see).
1563 if (command.substr(0, 7) == "seealso") {
1564 see_alsoes_ = getVectorFromString(argument, from_ascii(","), false);
1568 if (see_.find(from_ascii(",")) != std::string::npos) {
1569 output_error_ += from_utf8("Several index_argument_end terms found as \"see\"! Only one is "
1570 "acceptable. Complete entry: \"") + entry_ + from_utf8("\". ");
1574 // Remove the complete see/seealso from the commands, in case there is something else to parse.
1575 command = command.substr(position_closing_bracket + 1);
1578 // Some parts of the strings are not parsed, as they do not have anything matching in DocBook or XHTML:
1579 // things like formatting the entry or the page number, other strings for sorting.
1580 // https://wiki.lyx.org/Tips/Indexing
1581 // If there are such things in the index entry, then this code may miserably fail. For example, for
1582 // "Peter|(textbf", no range will be detected.
1583 if (!command.empty()) {
1584 output_error_ += from_utf8("Unsupported feature: an index entry contains a | with an unsupported command, ")
1585 + command + from_utf8(". Complete entry: \"") + entry_ + from_utf8("\". ");
1591 return terms_.size();
1594 const std::vector<docstring>& terms() const {
1598 std::vector<docstring>& terms() {
1602 const InsetIndex* inset() const {
1607 // Input inset. These should only be used when parsing the inset (either parseAsModern or parseAsLegacy, called in
1608 // the constructor).
1609 const InsetIndex * inset_;
1610 OutputParams const * runparams_;
1612 docstring index_; // Useful when there are multiple indices in the same document.
1614 // Errors, concatenated as a single string, available as soon as parsing is done, const afterwards (i.e. once
1615 // constructor is done).
1616 docstring output_error_;
1618 // Parsed index entry.
1619 std::vector<docstring> terms_; // Up to three entries, in general.
1622 bool has_start_range_;
1623 bool has_end_range_;
1625 vector<docstring> see_alsoes_;
1627 // Operators used for sorting entries (alphabetical order).
1628 friend bool operator<(IndexEntry const & lhs, IndexEntry const & rhs);
1631 bool operator<(IndexEntry const & lhs, IndexEntry const & rhs)
1633 if (lhs.terms_.empty())
1636 for (unsigned i = 0; i < min(rhs.terms_.size(), lhs.terms_.size()); ++i) {
1637 int comp = compare_no_case(lhs.terms_[i], rhs.terms_[i]);
1646 std::string generateCssClassAtDepth(unsigned depth) {
1647 std::string css_class = "entry";
1651 css_class.insert(0, "sub");
1658 std::vector<IndexEntry> entries;
1659 std::vector<IndexNode*> children;
1662 docstring termAtLevel(const IndexNode* node, unsigned depth)
1664 // 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
1665 // function could be made constant time by copying the term in each node, but that would make data duplication that
1666 // may fall out of sync; the performance benefit would probably be negligible.
1667 if (!node->entries.empty()) {
1668 LASSERT(node->entries.begin()->terms().size() >= depth + 1, return from_ascii(""));
1669 return node->entries.begin()->terms()[depth];
1672 if (!node->children.empty()) {
1673 return termAtLevel(*node->children.begin(), depth);
1676 LASSERT(false, return from_ascii(""));
1679 void insertIntoNode(const IndexEntry& entry, IndexNode* node, unsigned depth = 0)
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 child->entries.emplace_back(entry);
1689 insertIntoNode(entry, child, depth + 1);
1695 // Out of the loop: no matching child found, create a new (possibly nested) child for this entry. Due to the
1696 // possibility of nestedness, only insert the current entry when the right level is reached. This is needed if the
1697 // first entry for a word has several levels that never appeared.
1698 // In particular, this case is called for the first entry.
1699 IndexNode* new_node = node;
1701 new_node->children.emplace_back(new IndexNode{{}, {}});
1702 new_node = new_node->children.back();
1704 } while (depth + 1 <= entry.terms().size()); // depth == 0: root node, no text associated.
1705 new_node->entries.emplace_back(entry);
1708 IndexNode* buildIndexTree(vector<IndexEntry>& entries)
1710 // Sort the entries, first on the main entry, then the subentry, then the subsubentry,
1711 // thanks to the implementation of operator<.
1712 // If this operation is not performed, the algorithm below is no more correct (and ensuring that it works with
1713 // unsorted entries would make its complexity blow up).
1714 stable_sort(entries.begin(), entries.end());
1716 // Cook the index into a nice tree data structure: entries at a given level in the index as a node, with subentries
1718 auto* index_root = new IndexNode{{}, {}};
1719 for (const IndexEntry& entry : entries) {
1720 insertIntoNode(entry, index_root);
1726 void outputIndexPage(XMLStream & xs, const IndexNode* root_node, unsigned depth = 0) // NOLINT(misc-no-recursion)
1728 LASSERT(root_node->entries.size() + root_node->children.size() > 0, return);
1730 xs << xml::StartTag("li", "class='" + generateCssClassAtDepth(depth) + "'");
1732 xs << XMLStream::ESCAPE_NONE << termAtLevel(root_node, depth);
1733 // By tree assumption, all the entries at this node have the same set of terms.
1735 if (!root_node->entries.empty()) {
1736 xs << XMLStream::ESCAPE_NONE << " — "; // Em dash, i.e. long (---).
1737 unsigned entry_number = 1;
1739 auto writeLinkToEntry = [&xs](const IndexEntry &entry, unsigned entry_number) {
1740 std::string const link_attr = "href='#" + entry.inset()->paragraphs()[0].magicLabel() + "'";
1741 xs << xml::StartTag("a", link_attr);
1742 xs << from_ascii(std::to_string(entry_number));
1743 xs << xml::EndTag("a");
1746 for (unsigned i = 0; i < root_node->entries.size(); ++i) {
1747 const IndexEntry &entry = root_node->entries[i];
1749 switch (entry.inset()->params().range) {
1750 case InsetIndexParams::PageRange::None:
1751 writeLinkToEntry(entry, entry_number);
1753 case InsetIndexParams::PageRange::Start: {
1754 // Try to find the end of the range, if it is just after. Otherwise, the output will be slightly
1755 // scrambled, but understandable. Doing better would mean implementing more of the indexing logic here
1756 // and more complex indexing here (skipping the end is not just incrementing i). Worst case output:
1758 const bool nextEntryIsEnd = i + 1 < root_node->entries.size() &&
1759 root_node->entries[i + 1].inset()->params().range ==
1760 InsetIndexParams::PageRange::End;
1761 // No need to check if both entries are for the same terms: they are in the same IndexNode.
1763 writeLinkToEntry(entry, entry_number);
1764 xs << XMLStream::ESCAPE_NONE << " – "; // En dash, i.e. semi-long (--).
1766 if (nextEntryIsEnd) {
1767 // Skip the next entry in the loop, write it right now, after the dash.
1770 writeLinkToEntry(root_node->entries[i], entry_number);
1774 case InsetIndexParams::PageRange::End:
1775 // This range end was not caught by the range start, do it now to avoid losing content.
1776 xs << XMLStream::ESCAPE_NONE << " – "; // En dash, i.e. semi-long (--).
1777 writeLinkToEntry(root_node->entries[i], entry_number);
1780 if (i < root_node->entries.size() - 1) {
1787 if (!root_node->entries.empty() && !root_node->children.empty()) {
1791 if (!root_node->children.empty()) {
1792 xs << xml::StartTag("ul", "class='" + generateCssClassAtDepth(depth) + "'");
1795 for (const IndexNode* child : root_node->children) {
1796 outputIndexPage(xs, child, depth + 1);
1799 xs << xml::EndTag("ul");
1803 xs << xml::EndTag("li");
1807 #ifdef LYX_INSET_INDEX_DEBUG
1808 void printTree(const IndexNode* root_node, unsigned depth = 0)
1810 static const std::string pattern = " ";
1812 for (unsigned i = 0; i < depth; ++i) {
1815 const std::string prefix_long = prefix + pattern + pattern;
1817 docstring term_at_level;
1819 // The root has no term.
1820 std::cout << "<ROOT>" << std::endl;
1822 LASSERT(depth - 1 <= 10, return); // Check for overflows.
1823 term_at_level = termAtLevel(root_node, depth - 1);
1824 std::cout << prefix << to_utf8(term_at_level) << " (x " << std::to_string(root_node->entries.size()) << ")"
1828 for (const IndexEntry& entry : root_node->entries) {
1829 if (entry.terms().size() != depth) {
1830 std::cout << prefix_long << "ERROR: an entry doesn't have the same number of terms" << std::endl;
1832 if (depth > 0 && entry.terms()[depth - 1] != term_at_level) {
1833 std::cout << prefix_long << "ERROR: an entry doesn't have the right term at depth " << std::to_string(depth)
1838 for (const IndexNode* node : root_node->children) {
1839 printTree(node, depth + 1);
1842 #endif // LYX_INSET_INDEX_DEBUG
1846 docstring InsetPrintIndex::xhtml(XMLStream &, OutputParams const & op) const
1848 BufferParams const & bp = buffer().masterBuffer()->params();
1850 shared_ptr<Toc const> toc = buffer().tocBackend().toc("index");
1854 // Collect the index entries in a form we can use them.
1855 vector<IndexEntry> entries;
1856 const docstring & indexType = params().getParamOr("type", from_ascii("idx"));
1857 for (const TocItem& item : *toc) {
1858 const auto* inset = static_cast<const InsetIndex*>(&(item.dit().inset()));
1859 if (item.isOutput() && inset->params().index == indexType)
1860 entries.emplace_back(IndexEntry{inset, &op});
1863 // If all the index entries are in notes or not displayed, get out sooner.
1864 if (entries.empty())
1867 const IndexNode* index_root = buildIndexTree(entries);
1868 #ifdef LYX_INSET_INDEX_DEBUG
1869 printTree(index_root);
1872 // Start generating the XHTML index.
1873 Layout const & lay = bp.documentClass().htmlTOCLayout();
1874 string const & tocclass = lay.defaultCSSClass();
1875 string const tocattr = "class='index " + tocclass + "'";
1876 docstring const indexName = params().getParamOr("name", from_ascii("Index"));
1878 // we'll use our own stream, because we are going to defer everything.
1879 // that's how we deal with the fact that we're probably inside a standard
1880 // paragraph, and we don't want to be.
1881 odocstringstream ods;
1884 xs << xml::StartTag("div", tocattr);
1886 xs << xml::StartTag(lay.htmltag(), lay.htmlattr());
1887 xs << translateIfPossible(indexName, op.local_font->language()->lang());
1888 xs << xml::EndTag(lay.htmltag());
1890 xs << xml::StartTag("ul", "class='main'");
1893 LASSERT(index_root->entries.empty(), return docstring()); // No index entry should have zero terms.
1894 for (const IndexNode* node : index_root->children) {
1895 outputIndexPage(xs, node);
1898 xs << xml::EndTag("ul");
1900 xs << xml::EndTag("div");