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;
62 typedef Translator<string, InsetIndexParams::PageRange> PageRangeTranslator;
63 typedef Translator<docstring, InsetIndexParams::PageRange> PageRangeTranslatorLoc;
65 PageRangeTranslator const init_insetindexpagerangetranslator()
67 PageRangeTranslator translator("none", InsetIndexParams::None);
68 translator.addPair("start", InsetIndexParams::Start);
69 translator.addPair("end", InsetIndexParams::End);
73 PageRangeTranslator const init_insetindexpagerangetranslator_latex()
75 PageRangeTranslator translator("", InsetIndexParams::None);
76 translator.addPair("(", InsetIndexParams::Start);
77 translator.addPair(")", InsetIndexParams::End);
82 PageRangeTranslatorLoc const init_insetindexpagerangetranslator_loc()
84 PageRangeTranslatorLoc translator(docstring(), InsetIndexParams::None);
85 translator.addPair(_("Starts page range"), InsetIndexParams::Start);
86 translator.addPair(_("Ends page range"), InsetIndexParams::End);
91 PageRangeTranslator const & insetindexpagerangetranslator()
93 static PageRangeTranslator const prtranslator =
94 init_insetindexpagerangetranslator();
99 PageRangeTranslatorLoc const & insetindexpagerangetranslator_loc()
101 static PageRangeTranslatorLoc const translator =
102 init_insetindexpagerangetranslator_loc();
107 PageRangeTranslator const & insetindexpagerangetranslator_latex()
109 static PageRangeTranslator const lttranslator =
110 init_insetindexpagerangetranslator_latex();
116 /////////////////////////////////////////////////////////////////////
120 ///////////////////////////////////////////////////////////////////////
123 InsetIndex::InsetIndex(Buffer * buf, InsetIndexParams const & params)
124 : InsetCollapsible(buf), params_(params)
128 void InsetIndex::latex(otexstream & ios, OutputParams const & runparams_in) const
130 OutputParams runparams(runparams_in);
131 runparams.inIndexEntry = true;
135 if (buffer().masterBuffer()->params().use_indices && !params_.index.empty()
136 && params_.index != "idx") {
138 os << escape(params_.index);
145 // Get the LaTeX output from InsetText. We need to deconstruct this later
146 // in order to check if we need to generate a sorting key
147 odocstringstream ourlatex;
148 otexstream ots(ourlatex);
149 InsetText::latex(ots, runparams);
150 if (runparams.find_effective()) {
151 // No need for special handling, if we are only searching for some patterns
152 os << ourlatex.str() << "}";
157 getSortkey(os, runparams);
159 os << ourlatex.str();
160 getSubentries(os, runparams);
163 os << insetindexpagerangetranslator_latex().find(params_.range);
164 getSeeRefs(os, runparams);
165 } else if (!params_.pagefmt.empty() && params_.pagefmt != "default") {
167 os << insetindexpagerangetranslator_latex().find(params_.range);
168 os << from_utf8(params_.pagefmt);
171 // We check whether we need a sort key.
172 // If so, we use the plaintext version
173 odocstringstream ourplain;
174 InsetText::plaintext(ourplain, runparams);
176 // These are the LaTeX and plaintext representations
177 docstring latexstr = ourlatex.str();
178 docstring plainstr = ourplain.str();
180 // This will get what follows | if anything does,
181 // the command (e.g., see, textbf) for pagination
186 odocstringstream seeref;
187 otexstream otsee(seeref);
188 getSeeRefs(otsee, runparams);
190 } else if (!params_.pagefmt.empty() && params_.pagefmt != "default") {
191 cmd = from_utf8(params_.pagefmt);
193 // Check for the | separator to strip the cmd.
194 // This goes wrong on an escaped "|", but as the escape
195 // character can be changed in style files, we cannot
197 size_t pos = latexstr.find(from_ascii("|"));
198 if (pos != docstring::npos) {
199 // Put the bit after "|" into cmd...
200 cmd = latexstr.substr(pos + 1);
201 // ...and erase that stuff from latexstr
202 latexstr = latexstr.erase(pos);
203 // ...as well as from plainstr
204 size_t ppos = plainstr.find(from_ascii("|"));
205 if (ppos < plainstr.size())
206 plainstr.erase(ppos);
208 LYXERR0("The `|' separator was not found in the plaintext version!");
212 odocstringstream subentries;
213 otexstream otsub(subentries);
214 getSubentries(otsub, runparams);
215 if (subentries.str().empty()) {
216 // Separate the entries and subentries, i.e., split on "!".
217 // This goes wrong on an escaped "!", but as the escape
218 // character can be changed in style files, we cannot
220 std::vector<docstring> const levels =
221 getVectorFromString(latexstr, from_ascii("!"), true);
222 std::vector<docstring> const levels_plain =
223 getVectorFromString(plainstr, from_ascii("!"), true);
225 vector<docstring>::const_iterator it = levels.begin();
226 vector<docstring>::const_iterator end = levels.end();
227 vector<docstring>::const_iterator it2 = levels_plain.begin();
229 for (; it != end; ++it) {
230 // The separator needs to be put back when
231 // writing the levels, except for the first level
237 // Now here comes the reason for this whole procedure:
238 // We try to correctly sort macros and formatted strings.
239 // If we find a command, prepend a plain text
240 // version of the content to get sorting right,
241 // e.g. \index{LyX@\LyX}, \index{text@\textbf{text}}.
242 // We do this on all levels.
243 // We don't do it if the level already contains a '@', though.
244 // Plaintext might return nothing (e.g. for ERTs).
245 // In that case, we use LaTeX.
246 docstring const spart = (levels_plain.empty() || (*it2).empty()) ? *it : *it2;
247 processLatexSorting(os, runparams, *it, spart);
248 if (it2 < levels_plain.end())
252 processLatexSorting(os, runparams, latexstr, plainstr);
253 os << subentries.str();
256 // At last, re-insert the command, separated by "|"
259 << insetindexpagerangetranslator_latex().find(params_.range)
265 // In macros with moving arguments, such as \section,
266 // we store the index and output it after the macro (#2154)
267 if (runparams_in.postpone_fragile_stuff)
268 runparams_in.post_macro += os.str();
274 void InsetIndex::processLatexSorting(otexstream & os, OutputParams const & runparams,
275 docstring const latex, docstring const spart) const
277 if (contains(latex, '\\') && !contains(latex, '@')) {
278 // Now we need to validate that all characters in
279 // the sorting part are representable in the current
280 // encoding. If not try the LaTeX macro which might
281 // or might not be a good choice, and issue a warning.
282 pair<docstring, docstring> spart_latexed =
283 runparams.encoding->latexString(spart, runparams.dryrun);
284 if (!spart_latexed.second.empty())
285 LYXERR0("Uncodable character in index entry. Sorting might be wrong!");
286 if (spart != spart_latexed.first && !runparams.dryrun) {
288 ErrorList & errorList = buffer().errorList("Export");
289 docstring const s = bformat(_("LyX's automatic index sorting algorithm faced "
290 "problems with the entry '%1$s'.\n"
291 "Please specify the sorting of this entry manually, as "
292 "explained in the User Guide."), spart);
293 Paragraph const & par = buffer().paragraphs().front();
294 errorList.push_back(ErrorItem(_("Index sorting failed"), s,
295 {par.id(), 0}, {par.id(), -1}));
296 buffer().bufferErrors(terr, errorList);
298 // Remove remaining \'s from the sort key
299 docstring ppart = subst(spart_latexed.first, from_ascii("\\"), docstring());
300 // Plain quotes need to be escaped, however (#10649), as this
301 // is the default escape character
302 ppart = subst(ppart, from_ascii("\""), from_ascii("\\\""));
304 // Now insert the sortkey, separated by '@'.
308 // Insert the actual level text
313 void InsetIndex::docbook(XMLStream & xs, OutputParams const & runparams) const
315 // Two ways of processing this inset are implemented:
316 // - the legacy one, based on parsing the raw LaTeX (before LyX 2.4) -- unlikely to be deprecated
317 // - the modern one, based on precise insets for indexing features
318 // Like the LaTeX implementation, consider the user chooses either of those options.
320 // Get the content of the inset as LaTeX, as some things may be encoded as ERT (like {}).
321 // TODO: if there is an ERT within the index term, its conversion should be tried, in case it becomes useful;
322 // otherwise, ERTs should become comments. For now, they are just copied as-is, which is barely satisfactory.
323 odocstringstream odss;
324 otexstream ots(odss);
325 InsetText::latex(ots, runparams);
326 docstring latexString = trim(odss.str());
328 // Handle several indices (indicated in the inset instead of the raw latexString).
329 docstring indexType = from_utf8("");
330 if (buffer().masterBuffer()->params().use_indices) {
331 indexType += " type=\"" + params_.index + "\"";
334 // Split the string into its main constituents: terms, and command (see, see also, range).
335 size_t positionVerticalBar = latexString.find(from_ascii("|")); // What comes before | is (sub)(sub)entries.
336 docstring indexTerms = latexString.substr(0, positionVerticalBar);
338 if (positionVerticalBar != lyx::docstring::npos) {
339 command = latexString.substr(positionVerticalBar + 1);
342 // Handle sorting issues, with @.
345 sortAs = getSortkeyAsText(runparams);
346 // indexTerms may contain a sort key if the user has both the inset and the manual key.
348 vector<docstring> sortingElements = getVectorFromString(indexTerms, from_ascii("@"), false);
349 if (sortingElements.size() == 2) {
350 sortAs = sortingElements[0];
351 indexTerms = sortingElements[1];
355 // Handle primary, secondary, and tertiary terms (entries, subentries, and subsubentries, for LaTeX).
356 vector<docstring> terms;
357 if (const vector<docstring> potential_terms = getSubentriesAsText(runparams); !potential_terms.empty()) {
358 terms = potential_terms;
359 // The main term is not present in the vector, as it's not a subentry. The main index term is inserted raw in
360 // the index inset. Considering that the user either uses the new or the legacy mechanism, the main term is the
361 // full string within this inset (i.e. without the subinsets).
362 terms.insert(terms.begin(), latexString);
364 terms = getVectorFromString(indexTerms, from_ascii("!"), false);
367 // Handle ranges. Happily, in the raw LaTeX mode, (| and |) can only be at the end of the string!
368 const bool hasInsetRange = params_.range != InsetIndexParams::PageRange::None;
369 const bool hasStartRange = params_.range == InsetIndexParams::PageRange::Start ||
370 latexString.find(from_ascii("|(")) != lyx::docstring::npos;
371 const bool hasEndRange = params_.range == InsetIndexParams::PageRange::End ||
372 latexString.find(from_ascii("|)")) != lyx::docstring::npos;
375 // Remove the ranges from the command if they do not appear at the beginning.
377 while ((index = command.find(from_utf8("|("), index)) != std::string::npos)
378 command.erase(index, 1);
380 while ((index = command.find(from_utf8("|)"), index)) != std::string::npos)
381 command.erase(index, 1);
383 // Remove the ranges when they are the only vertical bar in the complete string.
384 if (command[0] == '(' || command[0] == ')')
388 // Handle see and seealso. As "see" is a prefix of "seealso", the order of the comparisons is important.
389 // Both commands are mutually exclusive!
390 docstring see = getSeeAsText(runparams);
391 vector<docstring> seeAlsoes = getSeeAlsoesAsText(runparams);
393 if (see.empty() && seeAlsoes.empty() && command.substr(0, 3) == "see") {
394 // Unescape brackets.
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 // Retrieve the part between brackets, and remove the complete seealso.
403 size_t positionOpeningBracket = command.find(from_ascii("{"));
404 size_t positionClosingBracket = command.find(from_ascii("}"));
405 docstring list = command.substr(positionOpeningBracket + 1, positionClosingBracket - positionOpeningBracket - 1);
407 // Parse the list of referenced entries (or a single one for see).
408 if (command.substr(0, 7) == "seealso") {
409 seeAlsoes = getVectorFromString(list, from_ascii(","), false);
413 if (see.find(from_ascii(",")) != std::string::npos) {
414 docstring error = from_utf8("Several index terms found as \"see\"! Only one is acceptable. "
415 "Complete entry: \"") + latexString + from_utf8("\"");
417 xs << XMLStream::ESCAPE_NONE << (from_utf8("<!-- Output Error: ") + error + from_utf8(" -->\n"));
421 // Remove the complete see/seealso from the commands, in case there is something else to parse.
422 command = command.substr(positionClosingBracket + 1);
425 // Some parts of the strings are not parsed, as they do not have anything matching in DocBook: things like
426 // formatting the entry or the page number, other strings for sorting. https://wiki.lyx.org/Tips/Indexing
427 // If there are such things in the index entry, then this code may miserably fail. For example, for "Peter|(textbf",
428 // no range will be detected.
429 // TODO: Could handle formatting as significance="preferred"?
430 if (!command.empty()) {
431 docstring error = from_utf8("Unsupported feature: an index entry contains a | with an unsupported command, ")
432 + command + from_utf8(". ") + from_utf8("Complete entry: \"") + latexString + from_utf8("\"");
434 xs << XMLStream::ESCAPE_NONE << (from_utf8("<!-- Output Error: ") + error + from_utf8(" -->\n"));
437 // Write all of this down.
438 if (terms.empty() && !hasEndRange) {
439 docstring error = from_utf8("No index term found! Complete entry: \"") + latexString + from_utf8("\"");
441 xs << XMLStream::ESCAPE_NONE << (from_utf8("<!-- Output Error: ") + error + from_utf8(" -->\n"));
443 // Generate the attributes for ranges. It is based on the terms that are indexed, but the ID must be unique
444 // to this indexing area (xml::cleanID does not guarantee this: for each call with the same arguments,
445 // the same legal ID is produced; here, as the input would be the same, the output must be, by design).
446 // Hence the thread-local storage, as the numbers must strictly be unique, and thus cannot be shared across
447 // a paragraph (making the solution used for HTML worthless). This solution is very similar to the one used in
449 // indexType can only be used for singular and startofrange types!
451 if (!hasStartRange && !hasEndRange) {
454 // Append an ID if uniqueness is not guaranteed across the document.
455 static QThreadStorage<set<docstring>> tKnownTermLists;
456 static QThreadStorage<int> tID;
458 set<docstring> &knownTermLists = tKnownTermLists.localData();
459 int &ID = tID.localData();
461 if (!tID.hasLocalData()) {
465 // Modify the index terms to add the unique ID if needed.
466 docstring newIndexTerms = indexTerms;
467 if (knownTermLists.find(indexTerms) != knownTermLists.end()) {
468 newIndexTerms += from_ascii(string("-") + to_string(ID));
470 // Only increment for the end of range, so that the same number is used for the start of range.
476 // Term list not yet known: add it to the set AFTER the end of range. After
477 if (knownTermLists.find(indexTerms) == knownTermLists.end() && hasEndRange) {
478 knownTermLists.insert(indexTerms);
481 // Generate the attributes.
482 docstring id = xml::cleanID(newIndexTerms);
484 attrs = indexType + " class=\"startofrange\" xml:id=\"" + id + "\"";
486 attrs = " class=\"endofrange\" startref=\"" + id + "\"";
490 // Handle the index terms (including the specific index for this entry).
492 xs << xml::CompTag("indexterm", attrs);
494 xs << xml::StartTag("indexterm", attrs);
495 if (!terms.empty()) { // hasEndRange has no content.
497 if (!sortAs.empty()) {
498 attr = from_utf8("sortas='") + sortAs + from_utf8("'");
501 xs << xml::StartTag("primary", attr);
503 xs << xml::EndTag("primary");
505 if (terms.size() > 1) {
506 xs << xml::StartTag("secondary");
508 xs << xml::EndTag("secondary");
510 if (terms.size() > 2) {
511 xs << xml::StartTag("tertiary");
513 xs << xml::EndTag("tertiary");
516 // Handle see and see also.
518 xs << xml::StartTag("see");
520 xs << xml::EndTag("see");
523 if (!seeAlsoes.empty()) {
524 for (auto &entry : seeAlsoes) {
525 xs << xml::StartTag("seealso");
527 xs << xml::EndTag("seealso");
532 xs << xml::EndTag("indexterm");
538 docstring InsetIndex::xhtml(XMLStream & xs, OutputParams const &) const
540 // we just print an anchor, taking the paragraph ID from
541 // our own interior paragraph, which doesn't get printed
542 std::string const magic = paragraphs().front().magicLabel();
543 std::string const attr = "id='" + magic + "'";
544 xs << xml::CompTag("a", attr);
549 bool InsetIndex::showInsetDialog(BufferView * bv) const
551 bv->showDialog("index", params2string(params_),
552 const_cast<InsetIndex *>(this));
557 void InsetIndex::doDispatch(Cursor & cur, FuncRequest & cmd)
559 switch (cmd.action()) {
561 case LFUN_INSET_MODIFY: {
562 if (cmd.getArg(0) == "changetype") {
563 cur.recordUndoInset(this);
564 params_.index = from_utf8(cmd.getArg(1));
567 InsetIndexParams params;
568 InsetIndex::string2params(to_utf8(cmd.argument()), params);
569 cur.recordUndoInset(this);
570 params_.index = params.index;
571 params_.range = params.range;
572 params_.pagefmt = params.pagefmt;
573 // what we really want here is a TOC update, but that means
574 // a full buffer update
575 cur.forceBufferUpdate();
579 case LFUN_INSET_DIALOG_UPDATE:
580 cur.bv().updateDialog("index", params2string(params_));
583 case LFUN_PARAGRAPH_BREAK: {
584 // Since this inset in single-par anyway, let's use
585 // return to enter subindexes
586 FuncRequest fr(LFUN_INDEXMACRO_INSERT, "subindex");
592 InsetCollapsible::doDispatch(cur, cmd);
598 bool InsetIndex::getStatus(Cursor & cur, FuncRequest const & cmd,
599 FuncStatus & flag) const
601 switch (cmd.action()) {
603 case LFUN_INSET_MODIFY:
604 if (cmd.getArg(0) == "changetype") {
605 docstring const newtype = from_utf8(cmd.getArg(1));
606 Buffer const & realbuffer = *buffer().masterBuffer();
607 IndicesList const & indiceslist = realbuffer.params().indiceslist();
608 Index const * index = indiceslist.findShortcut(newtype);
609 flag.setEnabled(index != 0);
611 from_utf8(cmd.getArg(1)) == params_.index);
614 return InsetCollapsible::getStatus(cur, cmd, flag);
616 case LFUN_INSET_DIALOG_UPDATE: {
617 Buffer const & realbuffer = *buffer().masterBuffer();
618 flag.setEnabled(realbuffer.params().use_indices);
622 case LFUN_PARAGRAPH_BREAK:
623 return macrosPossible("subindex");
625 case LFUN_INDEXMACRO_INSERT:
626 return macrosPossible(cmd.getArg(0));
629 return InsetCollapsible::getStatus(cur, cmd, flag);
634 void InsetIndex::getSortkey(otexstream & os, OutputParams const & runparams) const
636 Paragraph const & par = paragraphs().front();
637 InsetList::const_iterator it = par.insetList().begin();
638 for (; it != par.insetList().end(); ++it) {
639 Inset & inset = *it->inset;
640 if (inset.lyxCode() == INDEXMACRO_SORTKEY_CODE) {
641 InsetIndexMacro const & iim =
642 static_cast<InsetIndexMacro const &>(inset);
643 iim.getLatex(os, runparams);
650 docstring InsetIndex::getSortkeyAsText(OutputParams const & runparams) const
652 Paragraph const & par = paragraphs().front();
653 InsetList::const_iterator it = par.insetList().begin();
654 for (; it != par.insetList().end(); ++it) {
655 Inset & inset = *it->inset;
656 if (inset.lyxCode() == INDEXMACRO_SORTKEY_CODE) {
658 InsetIndexMacro const & iim =
659 static_cast<InsetIndexMacro const &>(inset);
660 iim.getLatex(os, runparams);
664 return from_ascii("");
668 void InsetIndex::getSubentries(otexstream & os, OutputParams const & runparams) const
670 Paragraph const & par = paragraphs().front();
671 InsetList::const_iterator it = par.insetList().begin();
673 for (; it != par.insetList().end(); ++it) {
674 Inset & inset = *it->inset;
675 if (inset.lyxCode() == INDEXMACRO_CODE) {
676 InsetIndexMacro const & iim =
677 static_cast<InsetIndexMacro const &>(inset);
678 if (iim.params().type == InsetIndexMacroParams::Subindex) {
683 iim.getLatex(os, runparams);
690 std::vector<docstring> InsetIndex::getSubentriesAsText(OutputParams const & runparams) const
692 std::vector<docstring> subentries;
694 Paragraph const & par = paragraphs().front();
695 InsetList::const_iterator it = par.insetList().begin();
697 for (; it != par.insetList().end(); ++it) {
698 Inset & inset = *it->inset;
699 if (inset.lyxCode() == INDEXMACRO_CODE) {
700 InsetIndexMacro const & iim =
701 static_cast<InsetIndexMacro const &>(inset);
702 if (iim.params().type == InsetIndexMacroParams::Subindex) {
708 iim.getLatex(os, runparams);
709 subentries.emplace_back(os.str());
718 docstring InsetIndex::getMainSubentryAsText(OutputParams const & runparams) const
721 InsetText::latex(os, runparams);
726 void InsetIndex::getSeeRefs(otexstream & os, OutputParams const & runparams) const
728 Paragraph const & par = paragraphs().front();
729 InsetList::const_iterator it = par.insetList().begin();
730 for (; it != par.insetList().end(); ++it) {
731 Inset & inset = *it->inset;
732 if (inset.lyxCode() == INDEXMACRO_CODE) {
733 InsetIndexMacro const & iim =
734 static_cast<InsetIndexMacro const &>(inset);
735 if (iim.params().type == InsetIndexMacroParams::See
736 || iim.params().type == InsetIndexMacroParams::Seealso) {
737 iim.getLatex(os, runparams);
745 docstring InsetIndex::getSeeAsText(OutputParams const & runparams) const
747 Paragraph const & par = paragraphs().front();
748 InsetList::const_iterator it = par.insetList().begin();
749 for (; it != par.insetList().end(); ++it) {
750 Inset & inset = *it->inset;
751 if (inset.lyxCode() == INDEXMACRO_CODE) {
752 InsetIndexMacro const & iim =
753 static_cast<InsetIndexMacro const &>(inset);
754 if (iim.params().type == InsetIndexMacroParams::See) {
756 iim.getLatex(os, runparams);
761 return from_ascii("");
765 std::vector<docstring> InsetIndex::getSeeAlsoesAsText(OutputParams const & runparams) const
767 std::vector<docstring> seeAlsoes;
769 Paragraph const & par = paragraphs().front();
770 InsetList::const_iterator it = par.insetList().begin();
771 for (; it != par.insetList().end(); ++it) {
772 Inset & inset = *it->inset;
773 if (inset.lyxCode() == INDEXMACRO_CODE) {
774 InsetIndexMacro const & iim =
775 static_cast<InsetIndexMacro const &>(inset);
776 if (iim.params().type == InsetIndexMacroParams::Seealso) {
778 iim.getLatex(os, runparams);
779 seeAlsoes.emplace_back(os.str());
790 bool hasInsetWithCode(const InsetIndex * const inset_index, const InsetCode code,
791 const std::set<InsetIndexMacroParams::Type> types = {})
793 Paragraph const & par = inset_index->paragraphs().front();
794 InsetList::const_iterator it = par.insetList().begin();
795 for (; it != par.insetList().end(); ++it) {
796 Inset & inset = *it->inset;
797 if (inset.lyxCode() == code) {
801 LASSERT(code == INDEXMACRO_CODE, return false);
802 InsetIndexMacro const & iim =
803 static_cast<InsetIndexMacro const &>(inset);
804 if (types.find(iim.params().type) != types.end())
814 bool InsetIndex::hasSubentries() const
816 return hasInsetWithCode(this, INDEXMACRO_CODE, {InsetIndexMacroParams::Subindex});
820 bool InsetIndex::hasSeeRef() const
822 return hasInsetWithCode(this, INDEXMACRO_CODE, {InsetIndexMacroParams::See, InsetIndexMacroParams::Seealso});
826 bool InsetIndex::hasSortKey() const
828 return hasInsetWithCode(this, INDEXMACRO_SORTKEY_CODE);
832 bool InsetIndex::macrosPossible(string const type) const
834 if (type != "see" && type != "seealso"
835 && type != "sortkey" && type != "subindex")
838 Paragraph const & par = paragraphs().front();
839 InsetList::const_iterator it = par.insetList().begin();
841 for (; it != par.insetList().end(); ++it) {
842 Inset & inset = *it->inset;
843 if (type == "sortkey" && inset.lyxCode() == INDEXMACRO_SORTKEY_CODE)
845 if (inset.lyxCode() == INDEXMACRO_CODE) {
846 InsetIndexMacro const & iim = static_cast<InsetIndexMacro const &>(inset);
847 if ((type == "see" || type == "seealso")
848 && (iim.params().type == InsetIndexMacroParams::See
849 || iim.params().type == InsetIndexMacroParams::Seealso))
851 if (type == "subindex"
852 && iim.params().type == InsetIndexMacroParams::Subindex) {
863 ColorCode InsetIndex::labelColor() const
865 if (params_.index.empty() || params_.index == from_ascii("idx"))
866 return InsetCollapsible::labelColor();
868 ColorCode c = lcolor.getFromLyXName(to_utf8(params_.index)
869 + "@" + buffer().fileName().absFileName());
871 c = InsetCollapsible::labelColor();
876 docstring InsetIndex::toolTip(BufferView const &, int, int) const
878 docstring tip = _("Index Entry");
879 if (buffer().params().use_indices && !params_.index.empty()) {
880 Buffer const & realbuffer = *buffer().masterBuffer();
881 IndicesList const & indiceslist = realbuffer.params().indiceslist();
883 Index const * index = indiceslist.findShortcut(params_.index);
885 tip += _("unknown type!");
887 tip += index->index();
891 docstring res = toolTipText(tip);
892 if (!insetindexpagerangetranslator_loc().find(params_.range).empty())
893 res += "\n" + insetindexpagerangetranslator_loc().find(params_.range);
894 if (!params_.pagefmt.empty() && params_.pagefmt != "default") {
895 res += "\n" + _("Pagination format:") + " ";
896 if (params_.pagefmt == "textbf")
898 else if (params_.pagefmt == "textit")
900 else if (params_.pagefmt == "emph")
901 res += _("emphasized");
903 res += from_utf8(params_.pagefmt);
909 docstring const InsetIndex::buttonLabel(BufferView const & bv) const
911 InsetLayout const & il = getLayout();
912 docstring label = translateIfPossible(il.labelstring());
914 if (buffer().params().use_indices && !params_.index.empty()) {
915 Buffer const & realbuffer = *buffer().masterBuffer();
916 IndicesList const & indiceslist = realbuffer.params().indiceslist();
918 Index const * index = indiceslist.findShortcut(params_.index);
920 label += _("unknown type!");
922 label += index->index();
927 if (!il.contentaslabel() || geometry(bv) != ButtonOnly)
930 res = getNewLabel(label);
931 if (!insetindexpagerangetranslator_latex().find(params_.range).empty())
932 res += " " + from_ascii(insetindexpagerangetranslator_latex().find(params_.range));
937 void InsetIndex::write(ostream & os) const
939 os << to_utf8(layoutName());
941 InsetCollapsible::write(os);
945 void InsetIndex::read(Lexer & lex)
948 InsetCollapsible::read(lex);
952 string InsetIndex::params2string(InsetIndexParams const & params)
961 void InsetIndex::string2params(string const & in, InsetIndexParams & params)
963 params = InsetIndexParams();
967 istringstream data(in);
970 lex.setContext("InsetIndex::string2params");
976 void InsetIndex::addToToc(DocIterator const & cpit, bool output_active,
977 UpdateType utype, TocBackend & backend) const
979 DocIterator pit = cpit;
980 pit.push_back(CursorSlice(const_cast<InsetIndex &>(*this)));
982 string type = "index";
983 if (buffer().masterBuffer()->params().use_indices)
984 type += ":" + to_utf8(params_.index);
985 // this is unlikely to be terribly long
986 text().forOutliner(str, INT_MAX);
987 TocBuilder & b = backend.builder(type);
988 b.pushItem(pit, str, output_active);
989 // Proceed with the rest of the inset.
990 InsetCollapsible::addToToc(cpit, output_active, utype, backend);
995 void InsetIndex::validate(LaTeXFeatures & features) const
997 if (buffer().masterBuffer()->params().use_indices
998 && !params_.index.empty()
999 && params_.index != "idx")
1000 features.require("splitidx");
1001 InsetCollapsible::validate(features);
1005 string InsetIndex::contextMenuName() const
1007 return "context-index";
1011 string InsetIndex::contextMenu(BufferView const & bv, int x, int y) const
1013 // We override the implementation of InsetCollapsible,
1014 // because we have eytra entries.
1015 string owncm = "context-edit-index;";
1016 return owncm + InsetCollapsible::contextMenu(bv, x, y);
1020 bool InsetIndex::hasSettings() const
1026 bool InsetIndex::insetAllowed(InsetCode code) const
1029 case INDEXMACRO_CODE:
1030 case INDEXMACRO_SORTKEY_CODE:
1035 return InsetCollapsible::insetAllowed(code);
1040 /////////////////////////////////////////////////////////////////////
1044 ///////////////////////////////////////////////////////////////////////
1047 void InsetIndexParams::write(ostream & os) const
1051 os << to_utf8(index);
1056 << insetindexpagerangetranslator().find(range)
1064 void InsetIndexParams::read(Lexer & lex)
1067 index = lex.getDocString();
1069 index = from_ascii("idx");
1070 if (lex.checkFor("range")) {
1071 string st = lex.getString();
1072 if (lex.eatLine()) {
1073 st = lex.getString();
1074 range = insetindexpagerangetranslator().find(lex.getString());
1077 if (lex.checkFor("pageformat") && lex.eatLine()) {
1078 pagefmt = lex.getString();
1083 /////////////////////////////////////////////////////////////////////
1087 ///////////////////////////////////////////////////////////////////////
1089 InsetPrintIndex::InsetPrintIndex(Buffer * buf, InsetCommandParams const & p)
1090 : InsetCommand(buf, p)
1094 ParamInfo const & InsetPrintIndex::findInfo(string const & /* cmdName */)
1096 static ParamInfo param_info_;
1097 if (param_info_.empty()) {
1098 param_info_.add("type", ParamInfo::LATEX_OPTIONAL,
1099 ParamInfo::HANDLING_ESCAPE);
1100 param_info_.add("name", ParamInfo::LATEX_OPTIONAL,
1101 ParamInfo::HANDLING_LATEXIFY);
1102 param_info_.add("literal", ParamInfo::LYX_INTERNAL);
1108 docstring InsetPrintIndex::screenLabel() const
1110 bool const printall = suffixIs(getCmdName(), '*');
1111 bool const multind = buffer().masterBuffer()->params().use_indices;
1113 && getParam("type") == from_ascii("idx"))
1114 || (getParam("type").empty() && !printall))
1116 Buffer const & realbuffer = *buffer().masterBuffer();
1117 IndicesList const & indiceslist = realbuffer.params().indiceslist();
1118 Index const * index = indiceslist.findShortcut(getParam("type"));
1119 if (!index && !printall)
1120 return _("Unknown index type!");
1121 docstring res = printall ? _("All indexes") : index->index();
1123 res += " (" + _("non-active") + ")";
1124 else if (contains(getCmdName(), "printsubindex"))
1125 res += " (" + _("subindex") + ")";
1130 bool InsetPrintIndex::isCompatibleCommand(string const & s)
1132 return s == "printindex" || s == "printsubindex"
1133 || s == "printindex*" || s == "printsubindex*";
1137 void InsetPrintIndex::doDispatch(Cursor & cur, FuncRequest & cmd)
1139 switch (cmd.action()) {
1141 case LFUN_INSET_MODIFY: {
1142 if (cmd.argument() == from_ascii("toggle-subindex")) {
1143 string scmd = getCmdName();
1144 if (contains(scmd, "printindex"))
1145 scmd = subst(scmd, "printindex", "printsubindex");
1147 scmd = subst(scmd, "printsubindex", "printindex");
1151 } else if (cmd.argument() == from_ascii("check-printindex*")) {
1152 string scmd = getCmdName();
1153 if (suffixIs(scmd, '*'))
1157 setParam("type", docstring());
1161 InsetCommandParams p(INDEX_PRINT_CODE);
1163 InsetCommand::string2params(to_utf8(cmd.argument()), p);
1164 if (p.getCmdName().empty()) {
1165 cur.noScreenUpdate();
1174 InsetCommand::doDispatch(cur, cmd);
1180 bool InsetPrintIndex::getStatus(Cursor & cur, FuncRequest const & cmd,
1181 FuncStatus & status) const
1183 switch (cmd.action()) {
1185 case LFUN_INSET_MODIFY: {
1186 if (cmd.argument() == from_ascii("toggle-subindex")) {
1187 status.setEnabled(buffer().masterBuffer()->params().use_indices);
1188 status.setOnOff(contains(getCmdName(), "printsubindex"));
1190 } else if (cmd.argument() == from_ascii("check-printindex*")) {
1191 status.setEnabled(buffer().masterBuffer()->params().use_indices);
1192 status.setOnOff(suffixIs(getCmdName(), '*'));
1194 } if (cmd.getArg(0) == "index_print"
1195 && cmd.getArg(1) == "CommandInset") {
1196 InsetCommandParams p(INDEX_PRINT_CODE);
1197 InsetCommand::string2params(to_utf8(cmd.argument()), p);
1198 if (suffixIs(p.getCmdName(), '*')) {
1199 status.setEnabled(true);
1200 status.setOnOff(false);
1203 Buffer const & realbuffer = *buffer().masterBuffer();
1204 IndicesList const & indiceslist =
1205 realbuffer.params().indiceslist();
1206 Index const * index = indiceslist.findShortcut(p["type"]);
1207 status.setEnabled(index != 0);
1208 status.setOnOff(p["type"] == getParam("type"));
1211 return InsetCommand::getStatus(cur, cmd, status);
1214 case LFUN_INSET_DIALOG_UPDATE: {
1215 status.setEnabled(buffer().masterBuffer()->params().use_indices);
1220 return InsetCommand::getStatus(cur, cmd, status);
1225 void InsetPrintIndex::updateBuffer(ParIterator const &, UpdateType, bool const /*deleted*/)
1227 Index const * index =
1228 buffer().masterParams().indiceslist().findShortcut(getParam("type"));
1230 setParam("name", index->index());
1234 void InsetPrintIndex::latex(otexstream & os, OutputParams const & runparams_in) const
1236 if (!buffer().masterBuffer()->params().use_indices) {
1237 if (getParam("type") == from_ascii("idx"))
1238 os << "\\printindex" << termcmd;
1241 OutputParams runparams = runparams_in;
1242 os << getCommand(runparams);
1246 void InsetPrintIndex::validate(LaTeXFeatures & features) const
1248 features.require("makeidx");
1249 if (buffer().masterBuffer()->params().use_indices)
1250 features.require("splitidx");
1251 InsetCommand::validate(features);
1255 string InsetPrintIndex::contextMenuName() const
1257 return buffer().masterBuffer()->params().use_indices ?
1258 "context-indexprint" : string();
1262 bool InsetPrintIndex::hasSettings() const
1264 return buffer().masterBuffer()->params().use_indices;
1271 /// Builds an entry for the index.
1272 IndexEntry(const InsetIndex * inset, OutputParams const * runparams) : inset_(inset), runparams_(runparams)
1274 LASSERT(runparams, return);
1276 // Convert the inset as text. The resulting text usually only contains an XHTML anchor (<a id='...'/>) and text.
1277 odocstringstream entry;
1278 OutputParams ours = *runparams;
1279 ours.for_toc = false;
1280 inset_->plaintext(entry, ours);
1281 entry_ = entry.str();
1283 // Determine in which index this entry belongs to.
1284 if (inset_->buffer().masterBuffer()->params().use_indices) {
1285 index_ = inset_->params_.index;
1288 // Attempt parsing the inset.
1295 /// When parsing this entry, some errors may be found; they are reported as a single string.
1296 // It is up to the caller to send this string to LYXERR and the output file, as needed.
1297 const docstring & output_error() const
1299 return output_error_;
1302 void output_error(XMLStream xs) const
1304 LYXERR0(output_error());
1305 xs << XMLStream::ESCAPE_NONE << (from_utf8("<!-- Output Error: ") + output_error() + from_utf8(" -->\n"));
1312 std::cout << to_utf8(entry_) << std::endl;
1314 // If a modern parameter is present, this is definitely a modern index inset. Similarly, if it contains the
1315 // usual LaTeX symbols (!|@), then it is definitely a legacy index inset. Otherwise, if it has features of
1316 // neither, it is both: consider this is a modern inset, to trigger the least complex code. Mixing both types
1317 // is not allowed (i.e. behaviour is undefined).
1318 const bool is_definitely_modern = inset_->hasSortKey() || inset_->hasSeeRef() || inset_->hasSubentries()
1319 || inset_->params_.range != InsetIndexParams::PageRange::None;
1320 const bool is_definitely_legacy = entry_.find('@') != std::string::npos
1321 || entry_.find('|') != std::string::npos || entry_.find('!') != std::string::npos;
1323 if (is_definitely_legacy && is_definitely_modern)
1324 output_error_ += from_utf8("Mix of index properties and raw LaTeX index commands is unsupported. ");
1327 // - is_definitely_modern == true:
1328 // - is_definitely_legacy == true: error (return whatever)
1329 // - is_definitely_legacy == false: return modern
1330 // - is_definitely_modern == false:
1331 // - is_definitely_legacy == true: return legacy
1332 // - is_definitely_legacy == false: return modern
1333 return !is_definitely_legacy;
1336 void parseAsModern()
1338 LASSERT(runparams_, return);
1340 if (inset_->hasSortKey()) {
1341 sort_as_ = inset_->getSortkeyAsText(*runparams_);
1344 terms_ = inset_->getSubentriesAsText(*runparams_);
1345 // The main term is not present in the vector, as it's not a subentry. The main index term is inserted raw in
1346 // the index inset. Considering that the user either uses the new or the legacy mechanism, the main term is the
1347 // full string within this inset (i.e. without the subinsets).
1348 terms_.insert(terms_.begin(), inset_->getMainSubentryAsText(*runparams_));
1350 has_start_range_ = inset_->params_.range == InsetIndexParams::PageRange::Start;
1351 has_end_range_ = inset_->params_.range == InsetIndexParams::PageRange::End;
1353 see_ = inset_->getSeeAsText(*runparams_);
1354 see_alsoes_ = inset_->getSeeAlsoesAsText(*runparams_);
1357 void parseAsLegacy() {
1358 // Determine if some features are known not to be supported. For now, this is only formatting like
1359 // \index{alpha@\textbf{alpha}} or \index{alpha@$\alpha$}.
1360 // @ is supported, but only for sorting, without specific formatting.
1361 if (entry_.find(from_utf8("@\\")) != lyx::docstring::npos) {
1362 output_error_ += from_utf8("Unsupported feature: an index entry contains an @\\. "
1363 "Complete entry: \"") + entry_ + from_utf8("\". ");
1365 if (entry_.find(from_utf8("@$")) != lyx::docstring::npos) {
1366 output_error_ += from_utf8("Unsupported feature: an index entry contains an @$. "
1367 "Complete entry: \"") + entry_ + from_utf8("\". ");
1370 // Split the string into its main constituents: terms, and command (see, see also, range).
1371 size_t positionVerticalBar = entry_.find(from_ascii("|")); // What comes before | is (sub)(sub)entries.
1372 docstring indexTerms = entry_.substr(0, positionVerticalBar);
1374 if (positionVerticalBar != lyx::docstring::npos) {
1375 command = entry_.substr(positionVerticalBar + 1);
1378 // Handle sorting issues, with @.
1379 vector<docstring> sortingElements = getVectorFromString(indexTerms, from_ascii("@"), false);
1380 if (sortingElements.size() == 2) {
1381 sort_as_ = sortingElements[0];
1382 indexTerms = sortingElements[1];
1385 // Handle entries, subentries, and subsubentries.
1386 terms_ = getVectorFromString(indexTerms, from_ascii("!"), false);
1388 // Handle ranges. Happily, (| and |) can only be at the end of the string!
1389 has_start_range_ = entry_.find(from_ascii("|(")) != lyx::docstring::npos;
1390 has_end_range_ = entry_.find(from_ascii("|)")) != lyx::docstring::npos;
1392 // - Remove the ranges from the command if they do not appear at the beginning.
1393 size_t range_index = 0;
1394 while ((range_index = command.find(from_utf8("|("), range_index)) != std::string::npos)
1395 command.erase(range_index, 1);
1397 while ((range_index = command.find(from_utf8("|)"), range_index)) != std::string::npos)
1398 command.erase(range_index, 1);
1400 // - Remove the ranges when they are the only vertical bar in the complete string.
1401 if (command[0] == '(' || command[0] == ')')
1402 command.erase(0, 1);
1404 // Handle see and seealso. As "see" is a prefix of "seealso", the order of the comparisons is important.
1405 // Both commands are mutually exclusive!
1406 if (command.substr(0, 3) == "see") {
1407 // Unescape brackets.
1408 size_t index_argument_begin = 0;
1409 while ((index_argument_begin = command.find(from_utf8("\\{"), index_argument_begin)) != std::string::npos)
1410 command.erase(index_argument_begin, 1);
1411 size_t index_argument_end = 0;
1412 while ((index_argument_end = command.find(from_utf8("\\}"), index_argument_end)) != std::string::npos)
1413 command.erase(index_argument_end, 1);
1415 // Retrieve the part between brackets, and remove the complete seealso.
1416 size_t position_opening_bracket = command.find(from_ascii("{"));
1417 size_t position_closing_bracket = command.find(from_ascii("}"));
1418 docstring argument = command.substr(position_opening_bracket + 1,
1419 position_closing_bracket - position_opening_bracket - 1);
1421 // Parse the argument of referenced entries (or a single one for see).
1422 if (command.substr(0, 7) == "seealso") {
1423 see_alsoes_ = getVectorFromString(argument, from_ascii(","), false);
1427 if (see_.find(from_ascii(",")) != std::string::npos) {
1428 output_error_ += from_utf8("Several index_argument_end terms found as \"see\"! Only one is "
1429 "acceptable. Complete entry: \"") + entry_ + from_utf8("\". ");
1433 // Remove the complete see/seealso from the commands, in case there is something else to parse.
1434 command = command.substr(position_closing_bracket + 1);
1437 // Some parts of the strings are not parsed, as they do not have anything matching in DocBook or XHTML:
1438 // things like formatting the entry or the page number, other strings for sorting.
1439 // https://wiki.lyx.org/Tips/Indexing
1440 // If there are such things in the index entry, then this code may miserably fail. For example, for
1441 // "Peter|(textbf", no range will be detected.
1442 if (!command.empty()) {
1443 output_error_ += from_utf8("Unsupported feature: an index entry contains a | with an unsupported command, ")
1444 + command + from_utf8(". Complete entry: \"") + entry_ + from_utf8("\". ");
1450 return terms_.size();
1453 const std::vector<docstring>& terms() const {
1457 std::vector<docstring>& terms() {
1461 const InsetIndex* inset() const {
1466 // Input inset. These should only be used when parsing the inset (either parseAsModern or parseAsLegacy, called in
1467 // the constructor).
1468 const InsetIndex * inset_;
1469 OutputParams const * runparams_;
1471 docstring index_; // Useful when there are multiple indices in the same document.
1473 // Errors, concatenated as a single string, available as soon as parsing is done, const afterwards (i.e. once
1474 // constructor is done).
1475 docstring output_error_;
1477 // Parsed index entry.
1478 std::vector<docstring> terms_; // Up to three entries, in general.
1481 bool has_start_range_;
1482 bool has_end_range_;
1484 vector<docstring> see_alsoes_;
1486 // Operators used for sorting entries (alphabetical order).
1487 friend bool operator<(IndexEntry const & lhs, IndexEntry const & rhs);
1490 bool operator<(IndexEntry const & lhs, IndexEntry const & rhs)
1492 if (lhs.terms_.empty())
1495 for (unsigned i = 0; i < min(rhs.terms_.size(), lhs.terms_.size()); ++i) {
1496 int comp = compare_no_case(lhs.terms_[i], rhs.terms_[i]);
1505 std::string generateCssClassAtDepth(unsigned depth) {
1506 std::string css_class = "entry";
1510 css_class.insert(0, "sub");
1517 std::vector<IndexEntry> entries;
1518 std::vector<IndexNode*> children;
1521 docstring termAtLevel(const IndexNode* node, unsigned depth)
1523 // 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
1524 // function could be made constant time by copying the term in each node, but that would make data duplication that
1525 // may fall out of sync; the performance benefit would probably be negligible.
1526 if (!node->entries.empty()) {
1527 LASSERT(node->entries.begin()->terms().size() >= depth + 1, return from_ascii(""));
1528 return node->entries.begin()->terms()[depth];
1531 if (!node->children.empty()) {
1532 return termAtLevel(*node->children.begin(), depth);
1535 LASSERT(false, return from_ascii(""));
1538 void insertIntoNode(const IndexEntry& entry, IndexNode* node, unsigned depth = 0)
1540 // depth == 0 is for the root, not yet the index, hence the increase when going to vector size.
1541 for (IndexNode* child : node->children) {
1542 if (entry.terms()[depth] == termAtLevel(child, depth)) {
1543 if (depth + 1 == entry.terms().size()) { // == child.entries.begin()->terms().size()
1544 // All term entries match: it's an entry.
1545 child->entries.emplace_back(entry);
1548 insertIntoNode(entry, child, depth + 1);
1554 // Out of the loop: no matching child found, create a new (possibly nested) child for this entry. Due to the
1555 // possibility of nestedness, only insert the current entry when the right level is reached. This is needed if the
1556 // first entry for a word has several levels that never appeared.
1557 // In particular, this case is called for the first entry.
1558 IndexNode* new_node = node;
1560 new_node->children.emplace_back(new IndexNode{{}, {}});
1561 new_node = new_node->children.back();
1563 } while (depth + 1 <= entry.terms().size()); // depth == 0: root node, no text associated.
1564 new_node->entries.emplace_back(entry);
1567 IndexNode* buildIndexTree(vector<IndexEntry>& entries)
1569 // Sort the entries, first on the main entry, then the subentry, then the subsubentry,
1570 // thanks to the implementation of operator<.
1571 // If this operation is not performed, the algorithm below is no more correct (and ensuring that it works with
1572 // unsorted entries would make its complexity blow up).
1573 stable_sort(entries.begin(), entries.end());
1575 // Cook the index into a nice tree data structure: entries at a given level in the index as a node, with subentries
1577 auto* index_root = new IndexNode{{}, {}};
1578 for (const IndexEntry& entry : entries) {
1579 insertIntoNode(entry, index_root);
1585 void outputIndexPage(XMLStream & xs, const IndexNode* root_node, unsigned depth = 0) // NOLINT(misc-no-recursion)
1587 LASSERT(root_node->entries.size() + root_node->children.size() > 0, return);
1589 xs << xml::StartTag("li", "class='" + generateCssClassAtDepth(depth) + "'");
1591 xs << XMLStream::ESCAPE_NONE << termAtLevel(root_node, depth);
1592 // By tree assumption, all the entries at this node have the same set of terms.
1594 if (!root_node->entries.empty()) {
1595 xs << XMLStream::ESCAPE_NONE << " — "; // Em dash, i.e. long (---).
1596 unsigned entry_number = 1;
1598 auto writeLinkToEntry = [&xs](const IndexEntry &entry, unsigned entry_number) {
1599 std::string const link_attr = "href='#" + entry.inset()->paragraphs()[0].magicLabel() + "'";
1600 xs << xml::StartTag("a", link_attr);
1601 xs << from_ascii(std::to_string(entry_number));
1602 xs << xml::EndTag("a");
1605 for (unsigned i = 0; i < root_node->entries.size(); ++i) {
1606 const IndexEntry &entry = root_node->entries[i];
1608 switch (entry.inset()->params().range) {
1609 case InsetIndexParams::PageRange::None:
1610 writeLinkToEntry(entry, entry_number);
1612 case InsetIndexParams::PageRange::Start: {
1613 // Try to find the end of the range, if it is just after. Otherwise, the output will be slightly
1614 // scrambled, but understandable. Doing better would mean implementing more of the indexing logic here
1615 // and more complex indexing here (skipping the end is not just incrementing i). Worst case output:
1617 const bool nextEntryIsEnd = i + 1 < root_node->entries.size() &&
1618 root_node->entries[i + 1].inset()->params().range ==
1619 InsetIndexParams::PageRange::End;
1620 // No need to check if both entries are for the same terms: they are in the same IndexNode.
1622 writeLinkToEntry(entry, entry_number);
1623 xs << XMLStream::ESCAPE_NONE << " – "; // En dash, i.e. semi-long (--).
1625 if (nextEntryIsEnd) {
1626 // Skip the next entry in the loop, write it right now, after the dash.
1629 writeLinkToEntry(root_node->entries[i], entry_number);
1633 case InsetIndexParams::PageRange::End:
1634 // This range end was not caught by the range start, do it now to avoid losing content.
1635 xs << XMLStream::ESCAPE_NONE << " – "; // En dash, i.e. semi-long (--).
1636 writeLinkToEntry(root_node->entries[i], entry_number);
1639 if (i < root_node->entries.size() - 1) {
1646 if (!root_node->entries.empty() && !root_node->children.empty()) {
1650 if (!root_node->children.empty()) {
1651 xs << xml::StartTag("ul", "class='" + generateCssClassAtDepth(depth) + "'");
1654 for (const IndexNode* child : root_node->children) {
1655 outputIndexPage(xs, child, depth + 1);
1658 xs << xml::EndTag("ul");
1662 xs << xml::EndTag("li");
1666 // Only useful for debugging.
1667 void printTree(const IndexNode* root_node, unsigned depth = 0)
1669 static const std::string pattern = " ";
1671 for (unsigned i = 0; i < depth; ++i) {
1674 const std::string prefix_long = prefix + pattern + pattern;
1676 docstring term_at_level;
1678 // The root has no term.
1679 std::cout << "<ROOT>" << std::endl;
1681 LASSERT(depth - 1 <= 10, return); // Check for overflows.
1682 term_at_level = termAtLevel(root_node, depth - 1);
1683 std::cout << prefix << to_utf8(term_at_level) << " (x " << std::to_string(root_node->entries.size()) << ")"
1687 for (const IndexEntry& entry : root_node->entries) {
1688 if (entry.terms().size() != depth) {
1689 std::cout << prefix_long << "ERROR: an entry doesn't have the same number of terms" << std::endl;
1691 if (depth > 0 && entry.terms()[depth - 1] != term_at_level) {
1692 std::cout << prefix_long << "ERROR: an entry doesn't have the right term at depth " << std::to_string(depth)
1697 for (const IndexNode* node : root_node->children) {
1698 printTree(node, depth + 1);
1704 docstring InsetPrintIndex::xhtml(XMLStream &, OutputParams const & op) const
1706 BufferParams const & bp = buffer().masterBuffer()->params();
1708 shared_ptr<Toc const> toc = buffer().tocBackend().toc("index");
1712 // Collect the index entries in a form we can use them.
1713 vector<IndexEntry> entries;
1714 const docstring & indexType = params().getParamOr("type", from_ascii("idx"));
1715 for (const TocItem& item : *toc) {
1716 const auto* inset = static_cast<const InsetIndex*>(&(item.dit().inset()));
1717 if (item.isOutput() && inset->params().index == indexType)
1718 entries.emplace_back(IndexEntry{inset, &op});
1721 // If all the index entries are in notes or not displayed, get out sooner.
1722 if (entries.empty())
1725 const IndexNode* index_root = buildIndexTree(entries);
1727 printTree(index_root);
1730 // Start generating the XHTML index.
1731 Layout const & lay = bp.documentClass().htmlTOCLayout();
1732 string const & tocclass = lay.defaultCSSClass();
1733 string const tocattr = "class='index " + tocclass + "'";
1734 docstring const indexName = params().getParamOr("name", from_ascii("Index"));
1736 // we'll use our own stream, because we are going to defer everything.
1737 // that's how we deal with the fact that we're probably inside a standard
1738 // paragraph, and we don't want to be.
1739 odocstringstream ods;
1742 xs << xml::StartTag("div", tocattr);
1744 xs << xml::StartTag(lay.htmltag(), lay.htmlattr());
1745 xs << translateIfPossible(indexName, op.local_font->language()->lang());
1746 xs << xml::EndTag(lay.htmltag());
1748 xs << xml::StartTag("ul", "class='main'");
1751 LASSERT(index_root->entries.empty(), return docstring()); // No index entry should have zero terms.
1752 for (const IndexNode* node : index_root->children) {
1753 outputIndexPage(xs, node);
1756 xs << xml::EndTag("ul");
1758 xs << xml::EndTag("div");