3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
7 * \author Jürgen Spitzmüller
9 * Full author contact details are available in file CREDITS.
13 #include "InsetIndex.h"
14 #include "InsetIndexMacro.h"
17 #include "BufferParams.h"
18 #include "BufferView.h"
21 #include "DispatchResult.h"
23 #include "ErrorList.h"
24 #include "FuncRequest.h"
25 #include "FuncStatus.h"
26 #include "IndicesList.h"
27 #include "InsetList.h"
30 #include "LaTeXFeatures.h"
33 #include "output_latex.h"
34 #include "output_xhtml.h"
36 #include "texstream.h"
37 #include "TextClass.h"
38 #include "TocBackend.h"
40 #include "support/debug.h"
41 #include "support/docstream.h"
42 #include "support/FileName.h"
43 #include "support/gettext.h"
44 #include "support/lstrings.h"
45 #include "support/Translator.h"
47 #include "frontends/alert.h"
53 #include <QThreadStorage>
56 using namespace lyx::support;
58 // Uncomment to enable InsetIndex-specific debugging mode: the tree for the index will be printed to std::cout.
59 // #define LYX_INSET_INDEX_DEBUG
65 typedef Translator<string, InsetIndexParams::PageRange> PageRangeTranslator;
66 typedef Translator<docstring, InsetIndexParams::PageRange> PageRangeTranslatorLoc;
68 PageRangeTranslator const init_insetindexpagerangetranslator()
70 PageRangeTranslator translator("none", InsetIndexParams::None);
71 translator.addPair("start", InsetIndexParams::Start);
72 translator.addPair("end", InsetIndexParams::End);
76 PageRangeTranslator const init_insetindexpagerangetranslator_latex()
78 PageRangeTranslator translator("", InsetIndexParams::None);
79 translator.addPair("(", InsetIndexParams::Start);
80 translator.addPair(")", InsetIndexParams::End);
85 PageRangeTranslatorLoc const init_insetindexpagerangetranslator_loc()
87 PageRangeTranslatorLoc translator(docstring(), InsetIndexParams::None);
88 translator.addPair(_("Starts page range"), InsetIndexParams::Start);
89 translator.addPair(_("Ends page range"), InsetIndexParams::End);
94 PageRangeTranslator const & insetindexpagerangetranslator()
96 static PageRangeTranslator const prtranslator =
97 init_insetindexpagerangetranslator();
102 PageRangeTranslatorLoc const & insetindexpagerangetranslator_loc()
104 static PageRangeTranslatorLoc const translator =
105 init_insetindexpagerangetranslator_loc();
110 PageRangeTranslator const & insetindexpagerangetranslator_latex()
112 static PageRangeTranslator const lttranslator =
113 init_insetindexpagerangetranslator_latex();
119 /////////////////////////////////////////////////////////////////////
123 ///////////////////////////////////////////////////////////////////////
126 InsetIndex::InsetIndex(Buffer * buf, InsetIndexParams const & params)
127 : InsetCollapsible(buf), params_(params)
131 void InsetIndex::latex(otexstream & ios, OutputParams const & runparams_in) const
133 OutputParams runparams(runparams_in);
134 runparams.inIndexEntry = true;
138 if (buffer().masterBuffer()->params().use_indices && !params_.index.empty()
139 && params_.index != "idx") {
141 os << escape(params_.index);
148 // Get the LaTeX output from InsetText. We need to deconstruct this later
149 // in order to check if we need to generate a sorting key
150 odocstringstream ourlatex;
151 otexstream ots(ourlatex);
152 InsetText::latex(ots, runparams);
153 if (runparams.find_effective()) {
154 // No need for special handling, if we are only searching for some patterns
155 os << ourlatex.str() << "}";
160 getSortkey(os, runparams);
162 os << ourlatex.str();
163 getSubentries(os, runparams);
166 os << insetindexpagerangetranslator_latex().find(params_.range);
167 getSeeRefs(os, runparams);
168 } else if (!params_.pagefmt.empty() && params_.pagefmt != "default") {
170 os << insetindexpagerangetranslator_latex().find(params_.range);
171 os << from_utf8(params_.pagefmt);
174 // We check whether we need a sort key.
175 // If so, we use the plaintext version
176 odocstringstream ourplain;
177 InsetText::plaintext(ourplain, runparams);
179 // These are the LaTeX and plaintext representations
180 docstring latexstr = ourlatex.str();
181 docstring plainstr = ourplain.str();
183 // This will get what follows | if anything does,
184 // the command (e.g., see, textbf) for pagination
189 odocstringstream seeref;
190 otexstream otsee(seeref);
191 getSeeRefs(otsee, runparams);
193 } else if (!params_.pagefmt.empty() && params_.pagefmt != "default") {
194 cmd = from_utf8(params_.pagefmt);
196 // Check for the | separator to strip the cmd.
197 // This goes wrong on an escaped "|", but as the escape
198 // character can be changed in style files, we cannot
200 size_t pos = latexstr.find(from_ascii("|"));
201 if (pos != docstring::npos) {
202 // Put the bit after "|" into cmd...
203 cmd = latexstr.substr(pos + 1);
204 // ...and erase that stuff from latexstr
205 latexstr = latexstr.erase(pos);
206 // ...as well as from plainstr
207 size_t ppos = plainstr.find(from_ascii("|"));
208 if (ppos < plainstr.size())
209 plainstr.erase(ppos);
211 LYXERR0("The `|' separator was not found in the plaintext version!");
215 odocstringstream subentries;
216 otexstream otsub(subentries);
217 getSubentries(otsub, runparams);
218 if (subentries.str().empty()) {
219 // Separate the entries and subentries, i.e., split on "!".
220 // This goes wrong on an escaped "!", but as the escape
221 // character can be changed in style files, we cannot
223 std::vector<docstring> const levels =
224 getVectorFromString(latexstr, from_ascii("!"), true);
225 std::vector<docstring> const levels_plain =
226 getVectorFromString(plainstr, from_ascii("!"), true);
228 vector<docstring>::const_iterator it = levels.begin();
229 vector<docstring>::const_iterator end = levels.end();
230 vector<docstring>::const_iterator it2 = levels_plain.begin();
232 for (; it != end; ++it) {
233 // The separator needs to be put back when
234 // writing the levels, except for the first level
240 // Now here comes the reason for this whole procedure:
241 // We try to correctly sort macros and formatted strings.
242 // If we find a command, prepend a plain text
243 // version of the content to get sorting right,
244 // e.g. \index{LyX@\LyX}, \index{text@\textbf{text}}.
245 // We do this on all levels.
246 // We don't do it if the level already contains a '@', though.
247 // Plaintext might return nothing (e.g. for ERTs).
248 // In that case, we use LaTeX.
249 docstring const spart = (levels_plain.empty() || (*it2).empty()) ? *it : *it2;
250 processLatexSorting(os, runparams, *it, spart);
251 if (it2 < levels_plain.end())
255 processLatexSorting(os, runparams, latexstr, plainstr);
256 os << subentries.str();
259 // At last, re-insert the command, separated by "|"
262 << insetindexpagerangetranslator_latex().find(params_.range)
268 // In macros with moving arguments, such as \section,
269 // we store the index and output it after the macro (#2154)
270 if (runparams_in.postpone_fragile_stuff)
271 runparams_in.post_macro += os.str();
277 void InsetIndex::processLatexSorting(otexstream & os, OutputParams const & runparams,
278 docstring const latex, docstring const spart) const
280 if (contains(latex, '\\') && !contains(latex, '@')) {
281 // Now we need to validate that all characters in
282 // the sorting part are representable in the current
283 // encoding. If not try the LaTeX macro which might
284 // or might not be a good choice, and issue a warning.
285 pair<docstring, docstring> spart_latexed =
286 runparams.encoding->latexString(spart, runparams.dryrun);
287 if (!spart_latexed.second.empty())
288 LYXERR0("Uncodable character in index entry. Sorting might be wrong!");
289 if (spart != spart_latexed.first && !runparams.dryrun) {
291 ErrorList & errorList = buffer().errorList("Export");
292 docstring const s = bformat(_("LyX's automatic index sorting algorithm faced "
293 "problems with the entry '%1$s'.\n"
294 "Please specify the sorting of this entry manually, as "
295 "explained in the User Guide."), spart);
296 Paragraph const & par = buffer().paragraphs().front();
297 errorList.push_back(ErrorItem(_("Index sorting failed"), s,
298 {par.id(), 0}, {par.id(), -1}));
299 buffer().bufferErrors(terr, errorList);
301 // Remove remaining \'s from the sort key
302 docstring ppart = subst(spart_latexed.first, from_ascii("\\"), docstring());
303 // Plain quotes need to be escaped, however (#10649), as this
304 // is the default escape character
305 ppart = subst(ppart, from_ascii("\""), from_ascii("\\\""));
307 // Now insert the sortkey, separated by '@'.
311 // Insert the actual level text
316 void InsetIndex::docbook(XMLStream & xs, OutputParams const & runparams) const
318 // Two ways of processing this inset are implemented:
319 // - the legacy one, based on parsing the raw LaTeX (before LyX 2.4) -- unlikely to be deprecated
320 // - the modern one, based on precise insets for indexing features
321 // Like the LaTeX implementation, consider the user chooses either of those options.
323 // Get the content of the inset as LaTeX, as some things may be encoded as ERT (like {}).
324 // TODO: if there is an ERT within the index term, its conversion should be tried, in case it becomes useful;
325 // otherwise, ERTs should become comments. For now, they are just copied as-is, which is barely satisfactory.
326 odocstringstream odss;
327 otexstream ots(odss);
328 InsetText::latex(ots, runparams);
329 docstring latexString = trim(odss.str());
331 // Handle several indices (indicated in the inset instead of the raw latexString).
332 docstring indexType = from_utf8("");
333 if (buffer().masterBuffer()->params().use_indices) {
334 indexType += " type=\"" + params_.index + "\"";
337 // Split the string into its main constituents: terms, and command (see, see also, range).
338 size_t positionVerticalBar = latexString.find(from_ascii("|")); // What comes before | is (sub)(sub)entries.
339 docstring indexTerms = latexString.substr(0, positionVerticalBar);
341 if (positionVerticalBar != lyx::docstring::npos) {
342 command = latexString.substr(positionVerticalBar + 1);
345 // Handle sorting issues, with @.
348 sortAs = getSortkeyAsText(runparams);
349 // indexTerms may contain a sort key if the user has both the inset and the manual key.
351 vector<docstring> sortingElements = getVectorFromString(indexTerms, from_ascii("@"), false);
352 if (sortingElements.size() == 2) {
353 sortAs = sortingElements[0];
354 indexTerms = sortingElements[1];
358 // Handle primary, secondary, and tertiary terms (entries, subentries, and subsubentries, for LaTeX).
359 vector<docstring> terms;
360 if (const vector<docstring> potential_terms = getSubentriesAsText(runparams); !potential_terms.empty()) {
361 terms = potential_terms;
362 // The main term is not present in the vector, as it's not a subentry. The main index term is inserted raw in
363 // the index inset. Considering that the user either uses the new or the legacy mechanism, the main term is the
364 // full string within this inset (i.e. without the subinsets).
365 terms.insert(terms.begin(), latexString);
367 terms = getVectorFromString(indexTerms, from_ascii("!"), false);
370 // Handle ranges. Happily, in the raw LaTeX mode, (| and |) can only be at the end of the string!
371 const bool hasInsetRange = params_.range != InsetIndexParams::PageRange::None;
372 const bool hasStartRange = params_.range == InsetIndexParams::PageRange::Start ||
373 latexString.find(from_ascii("|(")) != lyx::docstring::npos;
374 const bool hasEndRange = params_.range == InsetIndexParams::PageRange::End ||
375 latexString.find(from_ascii("|)")) != lyx::docstring::npos;
378 // Remove the ranges from the command if they do not appear at the beginning.
380 while ((index = command.find(from_utf8("|("), index)) != std::string::npos)
381 command.erase(index, 1);
383 while ((index = command.find(from_utf8("|)"), index)) != std::string::npos)
384 command.erase(index, 1);
386 // Remove the ranges when they are the only vertical bar in the complete string.
387 if (command[0] == '(' || command[0] == ')')
391 // Handle see and seealso. As "see" is a prefix of "seealso", the order of the comparisons is important.
392 // Both commands are mutually exclusive!
393 docstring see = getSeeAsText(runparams);
394 vector<docstring> seeAlsoes = getSeeAlsoesAsText(runparams);
396 if (see.empty() && seeAlsoes.empty() && command.substr(0, 3) == "see") {
397 // Unescape brackets.
399 while ((index = command.find(from_utf8("\\{"), index)) != std::string::npos)
400 command.erase(index, 1);
402 while ((index = command.find(from_utf8("\\}"), index)) != std::string::npos)
403 command.erase(index, 1);
405 // Retrieve the part between brackets, and remove the complete seealso.
406 size_t positionOpeningBracket = command.find(from_ascii("{"));
407 size_t positionClosingBracket = command.find(from_ascii("}"));
408 docstring list = command.substr(positionOpeningBracket + 1, positionClosingBracket - positionOpeningBracket - 1);
410 // Parse the list of referenced entries (or a single one for see).
411 if (command.substr(0, 7) == "seealso") {
412 seeAlsoes = getVectorFromString(list, from_ascii(","), false);
416 if (see.find(from_ascii(",")) != std::string::npos) {
417 docstring error = from_utf8("Several index terms found as \"see\"! Only one is acceptable. "
418 "Complete entry: \"") + latexString + from_utf8("\"");
420 xs << XMLStream::ESCAPE_NONE << (from_utf8("<!-- Output Error: ") + error + from_utf8(" -->\n"));
424 // Remove the complete see/seealso from the commands, in case there is something else to parse.
425 command = command.substr(positionClosingBracket + 1);
428 // Some parts of the strings are not parsed, as they do not have anything matching in DocBook: things like
429 // formatting the entry or the page number, other strings for sorting. https://wiki.lyx.org/Tips/Indexing
430 // If there are such things in the index entry, then this code may miserably fail. For example, for "Peter|(textbf",
431 // no range will be detected.
432 // TODO: Could handle formatting as significance="preferred"?
433 if (!command.empty()) {
434 docstring error = from_utf8("Unsupported feature: an index entry contains a | with an unsupported command, ")
435 + command + from_utf8(". ") + from_utf8("Complete entry: \"") + latexString + from_utf8("\"");
437 xs << XMLStream::ESCAPE_NONE << (from_utf8("<!-- Output Error: ") + error + from_utf8(" -->\n"));
440 // Write all of this down.
441 if (terms.empty() && !hasEndRange) {
442 docstring error = from_utf8("No index term found! Complete entry: \"") + latexString + from_utf8("\"");
444 xs << XMLStream::ESCAPE_NONE << (from_utf8("<!-- Output Error: ") + error + from_utf8(" -->\n"));
446 // Generate the attributes for ranges. It is based on the terms that are indexed, but the ID must be unique
447 // to this indexing area (xml::cleanID does not guarantee this: for each call with the same arguments,
448 // the same legal ID is produced; here, as the input would be the same, the output must be, by design).
449 // Hence the thread-local storage, as the numbers must strictly be unique, and thus cannot be shared across
450 // a paragraph (making the solution used for HTML worthless). This solution is very similar to the one used in
452 // indexType can only be used for singular and startofrange types!
454 if (!hasStartRange && !hasEndRange) {
457 // Append an ID if uniqueness is not guaranteed across the document.
458 static QThreadStorage<set<docstring>> tKnownTermLists;
459 static QThreadStorage<int> tID;
461 set<docstring> &knownTermLists = tKnownTermLists.localData();
462 int &ID = tID.localData();
464 if (!tID.hasLocalData()) {
468 // Modify the index terms to add the unique ID if needed.
469 docstring newIndexTerms = indexTerms;
470 if (knownTermLists.find(indexTerms) != knownTermLists.end()) {
471 newIndexTerms += from_ascii(string("-") + to_string(ID));
473 // Only increment for the end of range, so that the same number is used for the start of range.
479 // Term list not yet known: add it to the set AFTER the end of range. After
480 if (knownTermLists.find(indexTerms) == knownTermLists.end() && hasEndRange) {
481 knownTermLists.insert(indexTerms);
484 // Generate the attributes.
485 docstring id = xml::cleanID(newIndexTerms);
487 attrs = indexType + " class=\"startofrange\" xml:id=\"" + id + "\"";
489 attrs = " class=\"endofrange\" startref=\"" + id + "\"";
493 // Handle the index terms (including the specific index for this entry).
495 xs << xml::CompTag("indexterm", attrs);
497 xs << xml::StartTag("indexterm", attrs);
498 if (!terms.empty()) { // hasEndRange has no content.
500 if (!sortAs.empty()) {
501 attr = from_utf8("sortas='") + sortAs + from_utf8("'");
504 xs << xml::StartTag("primary", attr);
506 xs << xml::EndTag("primary");
508 if (terms.size() > 1) {
509 xs << xml::StartTag("secondary");
511 xs << xml::EndTag("secondary");
513 if (terms.size() > 2) {
514 xs << xml::StartTag("tertiary");
516 xs << xml::EndTag("tertiary");
519 // Handle see and see also.
521 xs << xml::StartTag("see");
523 xs << xml::EndTag("see");
526 if (!seeAlsoes.empty()) {
527 for (auto &entry : seeAlsoes) {
528 xs << xml::StartTag("seealso");
530 xs << xml::EndTag("seealso");
535 xs << xml::EndTag("indexterm");
541 docstring InsetIndex::xhtml(XMLStream & xs, OutputParams const &) const
543 // we just print an anchor, taking the paragraph ID from
544 // our own interior paragraph, which doesn't get printed
545 std::string const magic = paragraphs().front().magicLabel();
546 std::string const attr = "id='" + magic + "'";
547 xs << xml::CompTag("a", attr);
552 bool InsetIndex::showInsetDialog(BufferView * bv) const
554 bv->showDialog("index", params2string(params_),
555 const_cast<InsetIndex *>(this));
560 void InsetIndex::doDispatch(Cursor & cur, FuncRequest & cmd)
562 switch (cmd.action()) {
564 case LFUN_INSET_MODIFY: {
565 if (cmd.getArg(0) == "changetype") {
566 cur.recordUndoInset(this);
567 params_.index = from_utf8(cmd.getArg(1));
570 InsetIndexParams params;
571 InsetIndex::string2params(to_utf8(cmd.argument()), params);
572 cur.recordUndoInset(this);
573 params_.index = params.index;
574 params_.range = params.range;
575 params_.pagefmt = params.pagefmt;
576 // what we really want here is a TOC update, but that means
577 // a full buffer update
578 cur.forceBufferUpdate();
582 case LFUN_INSET_DIALOG_UPDATE:
583 cur.bv().updateDialog("index", params2string(params_));
586 case LFUN_PARAGRAPH_BREAK: {
587 // Since this inset in single-par anyway, let's use
588 // return to enter subentries
589 FuncRequest fr(LFUN_INDEXMACRO_INSERT, "subentry");
595 InsetCollapsible::doDispatch(cur, cmd);
601 bool InsetIndex::getStatus(Cursor & cur, FuncRequest const & cmd,
602 FuncStatus & flag) const
604 switch (cmd.action()) {
606 case LFUN_INSET_MODIFY:
607 if (cmd.getArg(0) == "changetype") {
608 docstring const newtype = from_utf8(cmd.getArg(1));
609 Buffer const & realbuffer = *buffer().masterBuffer();
610 IndicesList const & indiceslist = realbuffer.params().indiceslist();
611 Index const * index = indiceslist.findShortcut(newtype);
612 flag.setEnabled(index != 0);
614 from_utf8(cmd.getArg(1)) == params_.index);
617 return InsetCollapsible::getStatus(cur, cmd, flag);
619 case LFUN_INSET_DIALOG_UPDATE: {
620 Buffer const & realbuffer = *buffer().masterBuffer();
621 flag.setEnabled(realbuffer.params().use_indices);
625 case LFUN_PARAGRAPH_BREAK:
626 return macrosPossible("subentry");
628 case LFUN_INDEXMACRO_INSERT:
629 return macrosPossible(cmd.getArg(0));
632 return InsetCollapsible::getStatus(cur, cmd, flag);
637 void InsetIndex::getSortkey(otexstream & os, OutputParams const & runparams) const
639 Paragraph const & par = paragraphs().front();
640 InsetList::const_iterator it = par.insetList().begin();
641 for (; it != par.insetList().end(); ++it) {
642 Inset & inset = *it->inset;
643 if (inset.lyxCode() == INDEXMACRO_SORTKEY_CODE) {
644 InsetIndexMacro const & iim =
645 static_cast<InsetIndexMacro const &>(inset);
646 iim.getLatex(os, runparams);
653 docstring InsetIndex::getSortkeyAsText(OutputParams const & runparams) const
655 Paragraph const & par = paragraphs().front();
656 InsetList::const_iterator it = par.insetList().begin();
657 for (; it != par.insetList().end(); ++it) {
658 Inset & inset = *it->inset;
659 if (inset.lyxCode() == INDEXMACRO_SORTKEY_CODE) {
661 InsetIndexMacro const & iim =
662 static_cast<InsetIndexMacro const &>(inset);
663 iim.getLatex(os, runparams);
667 return from_ascii("");
671 void InsetIndex::getSubentries(otexstream & os, OutputParams const & runparams) const
673 Paragraph const & par = paragraphs().front();
674 InsetList::const_iterator it = par.insetList().begin();
676 for (; it != par.insetList().end(); ++it) {
677 Inset & inset = *it->inset;
678 if (inset.lyxCode() == INDEXMACRO_CODE) {
679 InsetIndexMacro const & iim =
680 static_cast<InsetIndexMacro const &>(inset);
681 if (iim.params().type == InsetIndexMacroParams::Subentry) {
686 iim.getLatex(os, runparams);
693 std::vector<docstring> InsetIndex::getSubentriesAsText(OutputParams const & runparams,
694 bool const asLabel) const
696 std::vector<docstring> subentries;
698 Paragraph const & par = paragraphs().front();
699 InsetList::const_iterator it = par.insetList().begin();
701 for (; it != par.insetList().end(); ++it) {
702 Inset & inset = *it->inset;
703 if (inset.lyxCode() == INDEXMACRO_CODE) {
704 InsetIndexMacro const & iim =
705 static_cast<InsetIndexMacro const &>(inset);
706 if (iim.params().type == InsetIndexMacroParams::Subentry) {
712 docstring const sl = iim.getNewLabel(l);
713 subentries.emplace_back(sl);
716 iim.getLatex(os, runparams);
717 subentries.emplace_back(os.str());
727 docstring InsetIndex::getMainSubentryAsText(OutputParams const & runparams) const
730 InsetText::latex(os, runparams);
735 void InsetIndex::getSeeRefs(otexstream & os, OutputParams const & runparams) const
737 Paragraph const & par = paragraphs().front();
738 InsetList::const_iterator it = par.insetList().begin();
739 for (; it != par.insetList().end(); ++it) {
740 Inset & inset = *it->inset;
741 if (inset.lyxCode() == INDEXMACRO_CODE) {
742 InsetIndexMacro const & iim =
743 static_cast<InsetIndexMacro const &>(inset);
744 if (iim.params().type == InsetIndexMacroParams::See
745 || iim.params().type == InsetIndexMacroParams::Seealso) {
746 iim.getLatex(os, runparams);
754 docstring InsetIndex::getSeeAsText(OutputParams const & runparams) const
756 Paragraph const & par = paragraphs().front();
757 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::See) {
765 iim.getLatex(os, runparams);
770 return from_ascii("");
774 std::vector<docstring> InsetIndex::getSeeAlsoesAsText(OutputParams const & runparams) const
776 std::vector<docstring> seeAlsoes;
778 Paragraph const & par = paragraphs().front();
779 InsetList::const_iterator it = par.insetList().begin();
780 for (; it != par.insetList().end(); ++it) {
781 Inset & inset = *it->inset;
782 if (inset.lyxCode() == INDEXMACRO_CODE) {
783 InsetIndexMacro const & iim =
784 static_cast<InsetIndexMacro const &>(inset);
785 if (iim.params().type == InsetIndexMacroParams::Seealso) {
787 iim.getLatex(os, runparams);
788 seeAlsoes.emplace_back(os.str());
799 bool hasInsetWithCode(const InsetIndex * const inset_index, const InsetCode code,
800 const std::set<InsetIndexMacroParams::Type> types = {})
802 Paragraph const & par = inset_index->paragraphs().front();
803 InsetList::const_iterator it = par.insetList().begin();
804 for (; it != par.insetList().end(); ++it) {
805 Inset & inset = *it->inset;
806 if (inset.lyxCode() == code) {
810 LASSERT(code == INDEXMACRO_CODE, return false);
811 InsetIndexMacro const & iim =
812 static_cast<InsetIndexMacro const &>(inset);
813 if (types.find(iim.params().type) != types.end())
823 bool InsetIndex::hasSubentries() const
825 return hasInsetWithCode(this, INDEXMACRO_CODE, {InsetIndexMacroParams::Subentry});
829 bool InsetIndex::hasSeeRef() const
831 return hasInsetWithCode(this, INDEXMACRO_CODE, {InsetIndexMacroParams::See, InsetIndexMacroParams::Seealso});
835 bool InsetIndex::hasSortKey() const
837 return hasInsetWithCode(this, INDEXMACRO_SORTKEY_CODE);
841 bool InsetIndex::macrosPossible(string const type) const
843 if (type != "see" && type != "seealso"
844 && type != "sortkey" && type != "subentry")
847 Paragraph const & par = paragraphs().front();
848 InsetList::const_iterator it = par.insetList().begin();
850 for (; it != par.insetList().end(); ++it) {
851 Inset & inset = *it->inset;
852 if (type == "sortkey" && inset.lyxCode() == INDEXMACRO_SORTKEY_CODE)
854 if (inset.lyxCode() == INDEXMACRO_CODE) {
855 InsetIndexMacro const & iim = static_cast<InsetIndexMacro const &>(inset);
856 if ((type == "see" || type == "seealso")
857 && (iim.params().type == InsetIndexMacroParams::See
858 || iim.params().type == InsetIndexMacroParams::Seealso))
860 if (type == "subentry"
861 && iim.params().type == InsetIndexMacroParams::Subentry) {
872 ColorCode InsetIndex::labelColor() const
874 if (params_.index.empty() || params_.index == from_ascii("idx"))
875 return InsetCollapsible::labelColor();
877 ColorCode c = lcolor.getFromLyXName(to_utf8(params_.index)
878 + "@" + buffer().fileName().absFileName());
880 c = InsetCollapsible::labelColor();
885 docstring InsetIndex::toolTip(BufferView const &, int, int) const
887 docstring tip = _("Index Entry");
888 if (buffer().params().use_indices && !params_.index.empty()) {
889 Buffer const & realbuffer = *buffer().masterBuffer();
890 IndicesList const & indiceslist = realbuffer.params().indiceslist();
892 Index const * index = indiceslist.findShortcut(params_.index);
894 tip += _("unknown type!");
896 tip += index->index();
900 docstring res = toolTipText(tip);
901 if (!insetindexpagerangetranslator_loc().find(params_.range).empty())
902 res += "\n" + insetindexpagerangetranslator_loc().find(params_.range);
903 if (!params_.pagefmt.empty() && params_.pagefmt != "default") {
904 res += "\n" + _("Pagination format:") + " ";
905 if (params_.pagefmt == "textbf")
907 else if (params_.pagefmt == "textit")
909 else if (params_.pagefmt == "emph")
910 res += _("emphasized");
912 res += from_utf8(params_.pagefmt);
918 docstring const InsetIndex::buttonLabel(BufferView const & bv) const
920 InsetLayout const & il = getLayout();
921 docstring label = translateIfPossible(il.labelstring());
923 if (buffer().params().use_indices && !params_.index.empty()) {
924 Buffer const & realbuffer = *buffer().masterBuffer();
925 IndicesList const & indiceslist = realbuffer.params().indiceslist();
927 Index const * index = indiceslist.findShortcut(params_.index);
929 label += _("unknown type!");
931 label += index->index();
936 if (!il.contentaslabel() || geometry(bv) != ButtonOnly)
939 res = getNewLabel(label);
940 OutputParams const rp(0);
941 vector<docstring> sublbls = getSubentriesAsText(rp, true);
942 for (auto const & sublbl : sublbls) {
943 res += " " + docstring(1, char_type(0x2023));// TRIANGULAR BULLET
947 if (!insetindexpagerangetranslator_latex().find(params_.range).empty())
948 res += " " + from_ascii(insetindexpagerangetranslator_latex().find(params_.range));
953 void InsetIndex::write(ostream & os) const
955 os << to_utf8(layoutName());
957 InsetCollapsible::write(os);
961 void InsetIndex::read(Lexer & lex)
964 InsetCollapsible::read(lex);
968 string InsetIndex::params2string(InsetIndexParams const & params)
977 void InsetIndex::string2params(string const & in, InsetIndexParams & params)
979 params = InsetIndexParams();
983 istringstream data(in);
986 lex.setContext("InsetIndex::string2params");
992 void InsetIndex::addToToc(DocIterator const & cpit, bool output_active,
993 UpdateType utype, TocBackend & backend) const
995 DocIterator pit = cpit;
996 pit.push_back(CursorSlice(const_cast<InsetIndex &>(*this)));
998 InsetLayout const & il = getLayout();
999 docstring label = translateIfPossible(il.labelstring());
1000 if (!il.contentaslabel())
1003 str = getNewLabel(label);
1004 OutputParams const rp(0);
1005 vector<docstring> sublbls = getSubentriesAsText(rp, true);
1006 for (auto const & sublbl : sublbls) {
1007 str += " " + docstring(1, char_type(0x2023));// TRIANGULAR BULLET
1008 str += " " + sublbl;
1011 string type = "index";
1012 if (buffer().masterBuffer()->params().use_indices)
1013 type += ":" + to_utf8(params_.index);
1014 TocBuilder & b = backend.builder(type);
1015 b.pushItem(pit, str, output_active);
1016 // Proceed with the rest of the inset.
1017 InsetCollapsible::addToToc(cpit, output_active, utype, backend);
1022 void InsetIndex::validate(LaTeXFeatures & features) const
1024 if (buffer().masterBuffer()->params().use_indices
1025 && !params_.index.empty()
1026 && params_.index != "idx")
1027 features.require("splitidx");
1028 InsetCollapsible::validate(features);
1032 string InsetIndex::contextMenuName() const
1034 return "context-index";
1038 string InsetIndex::contextMenu(BufferView const & bv, int x, int y) const
1040 // We override the implementation of InsetCollapsible,
1041 // because we have eytra entries.
1042 string owncm = "context-edit-index;";
1043 return owncm + InsetCollapsible::contextMenu(bv, x, y);
1047 bool InsetIndex::hasSettings() const
1053 bool InsetIndex::insetAllowed(InsetCode code) const
1056 case INDEXMACRO_CODE:
1057 case INDEXMACRO_SORTKEY_CODE:
1062 return InsetCollapsible::insetAllowed(code);
1067 /////////////////////////////////////////////////////////////////////
1071 ///////////////////////////////////////////////////////////////////////
1074 void InsetIndexParams::write(ostream & os) const
1078 os << to_utf8(index);
1083 << insetindexpagerangetranslator().find(range)
1091 void InsetIndexParams::read(Lexer & lex)
1094 index = lex.getDocString();
1096 index = from_ascii("idx");
1097 if (lex.checkFor("range")) {
1098 string st = lex.getString();
1099 if (lex.eatLine()) {
1100 st = lex.getString();
1101 range = insetindexpagerangetranslator().find(lex.getString());
1104 if (lex.checkFor("pageformat") && lex.eatLine()) {
1105 pagefmt = lex.getString();
1110 /////////////////////////////////////////////////////////////////////
1114 ///////////////////////////////////////////////////////////////////////
1116 InsetPrintIndex::InsetPrintIndex(Buffer * buf, InsetCommandParams const & p)
1117 : InsetCommand(buf, p)
1121 ParamInfo const & InsetPrintIndex::findInfo(string const & /* cmdName */)
1123 static ParamInfo param_info_;
1124 if (param_info_.empty()) {
1125 param_info_.add("type", ParamInfo::LATEX_OPTIONAL,
1126 ParamInfo::HANDLING_ESCAPE);
1127 param_info_.add("name", ParamInfo::LATEX_OPTIONAL,
1128 ParamInfo::HANDLING_LATEXIFY);
1129 param_info_.add("literal", ParamInfo::LYX_INTERNAL);
1135 docstring InsetPrintIndex::screenLabel() const
1137 bool const printall = suffixIs(getCmdName(), '*');
1138 bool const multind = buffer().masterBuffer()->params().use_indices;
1140 && getParam("type") == from_ascii("idx"))
1141 || (getParam("type").empty() && !printall))
1143 Buffer const & realbuffer = *buffer().masterBuffer();
1144 IndicesList const & indiceslist = realbuffer.params().indiceslist();
1145 Index const * index = indiceslist.findShortcut(getParam("type"));
1146 if (!index && !printall)
1147 return _("Unknown index type!");
1148 docstring res = printall ? _("All indexes") : index->index();
1150 res += " (" + _("non-active") + ")";
1151 else if (contains(getCmdName(), "printsubindex"))
1152 res += " (" + _("subindex") + ")";
1157 bool InsetPrintIndex::isCompatibleCommand(string const & s)
1159 return s == "printindex" || s == "printsubindex"
1160 || s == "printindex*" || s == "printsubindex*";
1164 void InsetPrintIndex::doDispatch(Cursor & cur, FuncRequest & cmd)
1166 switch (cmd.action()) {
1168 case LFUN_INSET_MODIFY: {
1169 if (cmd.argument() == from_ascii("toggle-subindex")) {
1170 string scmd = getCmdName();
1171 if (contains(scmd, "printindex"))
1172 scmd = subst(scmd, "printindex", "printsubindex");
1174 scmd = subst(scmd, "printsubindex", "printindex");
1178 } else if (cmd.argument() == from_ascii("check-printindex*")) {
1179 string scmd = getCmdName();
1180 if (suffixIs(scmd, '*'))
1184 setParam("type", docstring());
1188 InsetCommandParams p(INDEX_PRINT_CODE);
1190 InsetCommand::string2params(to_utf8(cmd.argument()), p);
1191 if (p.getCmdName().empty()) {
1192 cur.noScreenUpdate();
1201 InsetCommand::doDispatch(cur, cmd);
1207 bool InsetPrintIndex::getStatus(Cursor & cur, FuncRequest const & cmd,
1208 FuncStatus & status) const
1210 switch (cmd.action()) {
1212 case LFUN_INSET_MODIFY: {
1213 if (cmd.argument() == from_ascii("toggle-subindex")) {
1214 status.setEnabled(buffer().masterBuffer()->params().use_indices);
1215 status.setOnOff(contains(getCmdName(), "printsubindex"));
1217 } else if (cmd.argument() == from_ascii("check-printindex*")) {
1218 status.setEnabled(buffer().masterBuffer()->params().use_indices);
1219 status.setOnOff(suffixIs(getCmdName(), '*'));
1221 } if (cmd.getArg(0) == "index_print"
1222 && cmd.getArg(1) == "CommandInset") {
1223 InsetCommandParams p(INDEX_PRINT_CODE);
1224 InsetCommand::string2params(to_utf8(cmd.argument()), p);
1225 if (suffixIs(p.getCmdName(), '*')) {
1226 status.setEnabled(true);
1227 status.setOnOff(false);
1230 Buffer const & realbuffer = *buffer().masterBuffer();
1231 IndicesList const & indiceslist =
1232 realbuffer.params().indiceslist();
1233 Index const * index = indiceslist.findShortcut(p["type"]);
1234 status.setEnabled(index != 0);
1235 status.setOnOff(p["type"] == getParam("type"));
1238 return InsetCommand::getStatus(cur, cmd, status);
1241 case LFUN_INSET_DIALOG_UPDATE: {
1242 status.setEnabled(buffer().masterBuffer()->params().use_indices);
1247 return InsetCommand::getStatus(cur, cmd, status);
1252 void InsetPrintIndex::updateBuffer(ParIterator const &, UpdateType, bool const /*deleted*/)
1254 Index const * index =
1255 buffer().masterParams().indiceslist().findShortcut(getParam("type"));
1257 setParam("name", index->index());
1261 void InsetPrintIndex::latex(otexstream & os, OutputParams const & runparams_in) const
1263 if (!buffer().masterBuffer()->params().use_indices) {
1264 if (getParam("type") == from_ascii("idx"))
1265 os << "\\printindex" << termcmd;
1268 OutputParams runparams = runparams_in;
1269 os << getCommand(runparams);
1273 void InsetPrintIndex::validate(LaTeXFeatures & features) const
1275 features.require("makeidx");
1276 if (buffer().masterBuffer()->params().use_indices)
1277 features.require("splitidx");
1278 InsetCommand::validate(features);
1282 string InsetPrintIndex::contextMenuName() const
1284 return buffer().masterBuffer()->params().use_indices ?
1285 "context-indexprint" : string();
1289 bool InsetPrintIndex::hasSettings() const
1291 return buffer().masterBuffer()->params().use_indices;
1298 /// Builds an entry for the index.
1299 IndexEntry(const InsetIndex * inset, OutputParams const * runparams) : inset_(inset), runparams_(runparams)
1301 LASSERT(runparams, return);
1303 // Convert the inset as text. The resulting text usually only contains an XHTML anchor (<a id='...'/>) and text.
1304 odocstringstream entry;
1305 OutputParams ours = *runparams;
1306 ours.for_toc = false;
1307 inset_->plaintext(entry, ours);
1308 entry_ = entry.str();
1310 // Determine in which index this entry belongs to.
1311 if (inset_->buffer().masterBuffer()->params().use_indices) {
1312 index_ = inset_->params_.index;
1315 // Attempt parsing the inset.
1322 /// When parsing this entry, some errors may be found; they are reported as a single string.
1323 // It is up to the caller to send this string to LYXERR and the output file, as needed.
1324 const docstring & output_error() const
1326 return output_error_;
1329 void output_error(XMLStream xs) const
1331 LYXERR0(output_error());
1332 xs << XMLStream::ESCAPE_NONE << (from_utf8("<!-- Output Error: ") + output_error() + from_utf8(" -->\n"));
1339 std::cout << to_utf8(entry_) << std::endl;
1341 // If a modern parameter is present, this is definitely a modern index inset. Similarly, if it contains the
1342 // usual LaTeX symbols (!|@), then it is definitely a legacy index inset. Otherwise, if it has features of
1343 // neither, it is both: consider this is a modern inset, to trigger the least complex code. Mixing both types
1344 // is not allowed (i.e. behaviour is undefined).
1345 const bool is_definitely_modern = inset_->hasSortKey() || inset_->hasSeeRef() || inset_->hasSubentries()
1346 || inset_->params_.range != InsetIndexParams::PageRange::None;
1347 const bool is_definitely_legacy = entry_.find('@') != std::string::npos
1348 || entry_.find('|') != std::string::npos || entry_.find('!') != std::string::npos;
1350 if (is_definitely_legacy && is_definitely_modern)
1351 output_error_ += from_utf8("Mix of index properties and raw LaTeX index commands is unsupported. ");
1354 // - is_definitely_modern == true:
1355 // - is_definitely_legacy == true: error (return whatever)
1356 // - is_definitely_legacy == false: return modern
1357 // - is_definitely_modern == false:
1358 // - is_definitely_legacy == true: return legacy
1359 // - is_definitely_legacy == false: return modern
1360 return !is_definitely_legacy;
1363 void parseAsModern()
1365 LASSERT(runparams_, return);
1367 if (inset_->hasSortKey()) {
1368 sort_as_ = inset_->getSortkeyAsText(*runparams_);
1371 terms_ = inset_->getSubentriesAsText(*runparams_);
1372 // The main term is not present in the vector, as it's not a subentry. The main index term is inserted raw in
1373 // the index inset. Considering that the user either uses the new or the legacy mechanism, the main term is the
1374 // full string within this inset (i.e. without the subinsets).
1375 terms_.insert(terms_.begin(), inset_->getMainSubentryAsText(*runparams_));
1377 has_start_range_ = inset_->params_.range == InsetIndexParams::PageRange::Start;
1378 has_end_range_ = inset_->params_.range == InsetIndexParams::PageRange::End;
1380 see_ = inset_->getSeeAsText(*runparams_);
1381 see_alsoes_ = inset_->getSeeAlsoesAsText(*runparams_);
1384 void parseAsLegacy() {
1385 // Determine if some features are known not to be supported. For now, this is only formatting like
1386 // \index{alpha@\textbf{alpha}} or \index{alpha@$\alpha$}.
1387 // @ is supported, but only for sorting, without specific formatting.
1388 if (entry_.find(from_utf8("@\\")) != lyx::docstring::npos) {
1389 output_error_ += from_utf8("Unsupported feature: an index entry contains an @\\. "
1390 "Complete entry: \"") + entry_ + from_utf8("\". ");
1392 if (entry_.find(from_utf8("@$")) != lyx::docstring::npos) {
1393 output_error_ += from_utf8("Unsupported feature: an index entry contains an @$. "
1394 "Complete entry: \"") + entry_ + from_utf8("\". ");
1397 // Split the string into its main constituents: terms, and command (see, see also, range).
1398 size_t positionVerticalBar = entry_.find(from_ascii("|")); // What comes before | is (sub)(sub)entries.
1399 docstring indexTerms = entry_.substr(0, positionVerticalBar);
1401 if (positionVerticalBar != lyx::docstring::npos) {
1402 command = entry_.substr(positionVerticalBar + 1);
1405 // Handle sorting issues, with @.
1406 vector<docstring> sortingElements = getVectorFromString(indexTerms, from_ascii("@"), false);
1407 if (sortingElements.size() == 2) {
1408 sort_as_ = sortingElements[0];
1409 indexTerms = sortingElements[1];
1412 // Handle entries, subentries, and subsubentries.
1413 terms_ = getVectorFromString(indexTerms, from_ascii("!"), false);
1415 // Handle ranges. Happily, (| and |) can only be at the end of the string!
1416 has_start_range_ = entry_.find(from_ascii("|(")) != lyx::docstring::npos;
1417 has_end_range_ = entry_.find(from_ascii("|)")) != lyx::docstring::npos;
1419 // - Remove the ranges from the command if they do not appear at the beginning.
1420 size_t range_index = 0;
1421 while ((range_index = command.find(from_utf8("|("), range_index)) != std::string::npos)
1422 command.erase(range_index, 1);
1424 while ((range_index = command.find(from_utf8("|)"), range_index)) != std::string::npos)
1425 command.erase(range_index, 1);
1427 // - Remove the ranges when they are the only vertical bar in the complete string.
1428 if (command[0] == '(' || command[0] == ')')
1429 command.erase(0, 1);
1431 // Handle see and seealso. As "see" is a prefix of "seealso", the order of the comparisons is important.
1432 // Both commands are mutually exclusive!
1433 if (command.substr(0, 3) == "see") {
1434 // Unescape brackets.
1435 size_t index_argument_begin = 0;
1436 while ((index_argument_begin = command.find(from_utf8("\\{"), index_argument_begin)) != std::string::npos)
1437 command.erase(index_argument_begin, 1);
1438 size_t index_argument_end = 0;
1439 while ((index_argument_end = command.find(from_utf8("\\}"), index_argument_end)) != std::string::npos)
1440 command.erase(index_argument_end, 1);
1442 // Retrieve the part between brackets, and remove the complete seealso.
1443 size_t position_opening_bracket = command.find(from_ascii("{"));
1444 size_t position_closing_bracket = command.find(from_ascii("}"));
1445 docstring argument = command.substr(position_opening_bracket + 1,
1446 position_closing_bracket - position_opening_bracket - 1);
1448 // Parse the argument of referenced entries (or a single one for see).
1449 if (command.substr(0, 7) == "seealso") {
1450 see_alsoes_ = getVectorFromString(argument, from_ascii(","), false);
1454 if (see_.find(from_ascii(",")) != std::string::npos) {
1455 output_error_ += from_utf8("Several index_argument_end terms found as \"see\"! Only one is "
1456 "acceptable. Complete entry: \"") + entry_ + from_utf8("\". ");
1460 // Remove the complete see/seealso from the commands, in case there is something else to parse.
1461 command = command.substr(position_closing_bracket + 1);
1464 // Some parts of the strings are not parsed, as they do not have anything matching in DocBook or XHTML:
1465 // things like formatting the entry or the page number, other strings for sorting.
1466 // https://wiki.lyx.org/Tips/Indexing
1467 // If there are such things in the index entry, then this code may miserably fail. For example, for
1468 // "Peter|(textbf", no range will be detected.
1469 if (!command.empty()) {
1470 output_error_ += from_utf8("Unsupported feature: an index entry contains a | with an unsupported command, ")
1471 + command + from_utf8(". Complete entry: \"") + entry_ + from_utf8("\". ");
1477 return terms_.size();
1480 const std::vector<docstring>& terms() const {
1484 std::vector<docstring>& terms() {
1488 const InsetIndex* inset() const {
1493 // Input inset. These should only be used when parsing the inset (either parseAsModern or parseAsLegacy, called in
1494 // the constructor).
1495 const InsetIndex * inset_;
1496 OutputParams const * runparams_;
1498 docstring index_; // Useful when there are multiple indices in the same document.
1500 // Errors, concatenated as a single string, available as soon as parsing is done, const afterwards (i.e. once
1501 // constructor is done).
1502 docstring output_error_;
1504 // Parsed index entry.
1505 std::vector<docstring> terms_; // Up to three entries, in general.
1508 bool has_start_range_;
1509 bool has_end_range_;
1511 vector<docstring> see_alsoes_;
1513 // Operators used for sorting entries (alphabetical order).
1514 friend bool operator<(IndexEntry const & lhs, IndexEntry const & rhs);
1517 bool operator<(IndexEntry const & lhs, IndexEntry const & rhs)
1519 if (lhs.terms_.empty())
1522 for (unsigned i = 0; i < min(rhs.terms_.size(), lhs.terms_.size()); ++i) {
1523 int comp = compare_no_case(lhs.terms_[i], rhs.terms_[i]);
1532 std::string generateCssClassAtDepth(unsigned depth) {
1533 std::string css_class = "entry";
1537 css_class.insert(0, "sub");
1544 std::vector<IndexEntry> entries;
1545 std::vector<IndexNode*> children;
1548 docstring termAtLevel(const IndexNode* node, unsigned depth)
1550 // 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
1551 // function could be made constant time by copying the term in each node, but that would make data duplication that
1552 // may fall out of sync; the performance benefit would probably be negligible.
1553 if (!node->entries.empty()) {
1554 LASSERT(node->entries.begin()->terms().size() >= depth + 1, return from_ascii(""));
1555 return node->entries.begin()->terms()[depth];
1558 if (!node->children.empty()) {
1559 return termAtLevel(*node->children.begin(), depth);
1562 LASSERT(false, return from_ascii(""));
1565 void insertIntoNode(const IndexEntry& entry, IndexNode* node, unsigned depth = 0)
1567 // depth == 0 is for the root, not yet the index, hence the increase when going to vector size.
1568 for (IndexNode* child : node->children) {
1569 if (entry.terms()[depth] == termAtLevel(child, depth)) {
1570 if (depth + 1 == entry.terms().size()) { // == child.entries.begin()->terms().size()
1571 // All term entries match: it's an entry.
1572 child->entries.emplace_back(entry);
1575 insertIntoNode(entry, child, depth + 1);
1581 // Out of the loop: no matching child found, create a new (possibly nested) child for this entry. Due to the
1582 // possibility of nestedness, only insert the current entry when the right level is reached. This is needed if the
1583 // first entry for a word has several levels that never appeared.
1584 // In particular, this case is called for the first entry.
1585 IndexNode* new_node = node;
1587 new_node->children.emplace_back(new IndexNode{{}, {}});
1588 new_node = new_node->children.back();
1590 } while (depth + 1 <= entry.terms().size()); // depth == 0: root node, no text associated.
1591 new_node->entries.emplace_back(entry);
1594 IndexNode* buildIndexTree(vector<IndexEntry>& entries)
1596 // Sort the entries, first on the main entry, then the subentry, then the subsubentry,
1597 // thanks to the implementation of operator<.
1598 // If this operation is not performed, the algorithm below is no more correct (and ensuring that it works with
1599 // unsorted entries would make its complexity blow up).
1600 stable_sort(entries.begin(), entries.end());
1602 // Cook the index into a nice tree data structure: entries at a given level in the index as a node, with subentries
1604 auto* index_root = new IndexNode{{}, {}};
1605 for (const IndexEntry& entry : entries) {
1606 insertIntoNode(entry, index_root);
1612 void outputIndexPage(XMLStream & xs, const IndexNode* root_node, unsigned depth = 0) // NOLINT(misc-no-recursion)
1614 LASSERT(root_node->entries.size() + root_node->children.size() > 0, return);
1616 xs << xml::StartTag("li", "class='" + generateCssClassAtDepth(depth) + "'");
1618 xs << XMLStream::ESCAPE_NONE << termAtLevel(root_node, depth);
1619 // By tree assumption, all the entries at this node have the same set of terms.
1621 if (!root_node->entries.empty()) {
1622 xs << XMLStream::ESCAPE_NONE << " — "; // Em dash, i.e. long (---).
1623 unsigned entry_number = 1;
1625 auto writeLinkToEntry = [&xs](const IndexEntry &entry, unsigned entry_number) {
1626 std::string const link_attr = "href='#" + entry.inset()->paragraphs()[0].magicLabel() + "'";
1627 xs << xml::StartTag("a", link_attr);
1628 xs << from_ascii(std::to_string(entry_number));
1629 xs << xml::EndTag("a");
1632 for (unsigned i = 0; i < root_node->entries.size(); ++i) {
1633 const IndexEntry &entry = root_node->entries[i];
1635 switch (entry.inset()->params().range) {
1636 case InsetIndexParams::PageRange::None:
1637 writeLinkToEntry(entry, entry_number);
1639 case InsetIndexParams::PageRange::Start: {
1640 // Try to find the end of the range, if it is just after. Otherwise, the output will be slightly
1641 // scrambled, but understandable. Doing better would mean implementing more of the indexing logic here
1642 // and more complex indexing here (skipping the end is not just incrementing i). Worst case output:
1644 const bool nextEntryIsEnd = i + 1 < root_node->entries.size() &&
1645 root_node->entries[i + 1].inset()->params().range ==
1646 InsetIndexParams::PageRange::End;
1647 // No need to check if both entries are for the same terms: they are in the same IndexNode.
1649 writeLinkToEntry(entry, entry_number);
1650 xs << XMLStream::ESCAPE_NONE << " – "; // En dash, i.e. semi-long (--).
1652 if (nextEntryIsEnd) {
1653 // Skip the next entry in the loop, write it right now, after the dash.
1656 writeLinkToEntry(root_node->entries[i], entry_number);
1660 case InsetIndexParams::PageRange::End:
1661 // This range end was not caught by the range start, do it now to avoid losing content.
1662 xs << XMLStream::ESCAPE_NONE << " – "; // En dash, i.e. semi-long (--).
1663 writeLinkToEntry(root_node->entries[i], entry_number);
1666 if (i < root_node->entries.size() - 1) {
1673 if (!root_node->entries.empty() && !root_node->children.empty()) {
1677 if (!root_node->children.empty()) {
1678 xs << xml::StartTag("ul", "class='" + generateCssClassAtDepth(depth) + "'");
1681 for (const IndexNode* child : root_node->children) {
1682 outputIndexPage(xs, child, depth + 1);
1685 xs << xml::EndTag("ul");
1689 xs << xml::EndTag("li");
1693 #ifdef LYX_INSET_INDEX_DEBUG
1694 void printTree(const IndexNode* root_node, unsigned depth = 0)
1696 static const std::string pattern = " ";
1698 for (unsigned i = 0; i < depth; ++i) {
1701 const std::string prefix_long = prefix + pattern + pattern;
1703 docstring term_at_level;
1705 // The root has no term.
1706 std::cout << "<ROOT>" << std::endl;
1708 LASSERT(depth - 1 <= 10, return); // Check for overflows.
1709 term_at_level = termAtLevel(root_node, depth - 1);
1710 std::cout << prefix << to_utf8(term_at_level) << " (x " << std::to_string(root_node->entries.size()) << ")"
1714 for (const IndexEntry& entry : root_node->entries) {
1715 if (entry.terms().size() != depth) {
1716 std::cout << prefix_long << "ERROR: an entry doesn't have the same number of terms" << std::endl;
1718 if (depth > 0 && entry.terms()[depth - 1] != term_at_level) {
1719 std::cout << prefix_long << "ERROR: an entry doesn't have the right term at depth " << std::to_string(depth)
1724 for (const IndexNode* node : root_node->children) {
1725 printTree(node, depth + 1);
1728 #endif // LYX_INSET_INDEX_DEBUG
1732 docstring InsetPrintIndex::xhtml(XMLStream &, OutputParams const & op) const
1734 BufferParams const & bp = buffer().masterBuffer()->params();
1736 shared_ptr<Toc const> toc = buffer().tocBackend().toc("index");
1740 // Collect the index entries in a form we can use them.
1741 vector<IndexEntry> entries;
1742 const docstring & indexType = params().getParamOr("type", from_ascii("idx"));
1743 for (const TocItem& item : *toc) {
1744 const auto* inset = static_cast<const InsetIndex*>(&(item.dit().inset()));
1745 if (item.isOutput() && inset->params().index == indexType)
1746 entries.emplace_back(IndexEntry{inset, &op});
1749 // If all the index entries are in notes or not displayed, get out sooner.
1750 if (entries.empty())
1753 const IndexNode* index_root = buildIndexTree(entries);
1754 #ifdef LYX_INSET_INDEX_DEBUG
1755 printTree(index_root);
1758 // Start generating the XHTML index.
1759 Layout const & lay = bp.documentClass().htmlTOCLayout();
1760 string const & tocclass = lay.defaultCSSClass();
1761 string const tocattr = "class='index " + tocclass + "'";
1762 docstring const indexName = params().getParamOr("name", from_ascii("Index"));
1764 // we'll use our own stream, because we are going to defer everything.
1765 // that's how we deal with the fact that we're probably inside a standard
1766 // paragraph, and we don't want to be.
1767 odocstringstream ods;
1770 xs << xml::StartTag("div", tocattr);
1772 xs << xml::StartTag(lay.htmltag(), lay.htmlattr());
1773 xs << translateIfPossible(indexName, op.local_font->language()->lang());
1774 xs << xml::EndTag(lay.htmltag());
1776 xs << xml::StartTag("ul", "class='main'");
1779 LASSERT(index_root->entries.empty(), return docstring()); // No index entry should have zero terms.
1780 for (const IndexNode* node : index_root->children) {
1781 outputIndexPage(xs, node);
1784 xs << xml::EndTag("ul");
1786 xs << xml::EndTag("div");