3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
7 * \author Jürgen Spitzmüller
9 * Full author contact details are available in file CREDITS.
13 #include "InsetIndex.h"
14 #include "InsetIndexMacro.h"
17 #include "BufferParams.h"
18 #include "BufferView.h"
21 #include "CutAndPaste.h"
22 #include "DispatchResult.h"
24 #include "ErrorList.h"
25 #include "FuncRequest.h"
26 #include "FuncStatus.h"
27 #include "IndicesList.h"
28 #include "InsetList.h"
31 #include "LaTeXFeatures.h"
34 #include "output_latex.h"
35 #include "output_xhtml.h"
37 #include "texstream.h"
38 #include "TextClass.h"
39 #include "TocBackend.h"
41 #include "support/debug.h"
42 #include "support/docstream.h"
43 #include "support/FileName.h"
44 #include "support/gettext.h"
45 #include "support/lstrings.h"
46 #include "support/Translator.h"
48 #include "frontends/alert.h"
54 #include <QThreadStorage>
57 using namespace lyx::support;
59 // Uncomment to enable InsetIndex-specific debugging mode: the tree for the index will be printed to std::cout.
60 // #define LYX_INSET_INDEX_DEBUG
66 typedef Translator<string, InsetIndexParams::PageRange> PageRangeTranslator;
67 typedef Translator<docstring, InsetIndexParams::PageRange> PageRangeTranslatorLoc;
69 PageRangeTranslator const init_insetindexpagerangetranslator()
71 PageRangeTranslator translator("none", InsetIndexParams::None);
72 translator.addPair("start", InsetIndexParams::Start);
73 translator.addPair("end", InsetIndexParams::End);
77 PageRangeTranslator const init_insetindexpagerangetranslator_latex()
79 PageRangeTranslator translator("", InsetIndexParams::None);
80 translator.addPair("(", InsetIndexParams::Start);
81 translator.addPair(")", InsetIndexParams::End);
86 PageRangeTranslatorLoc const init_insetindexpagerangetranslator_loc()
88 PageRangeTranslatorLoc translator(docstring(), InsetIndexParams::None);
89 translator.addPair(_("Starts page range"), InsetIndexParams::Start);
90 translator.addPair(_("Ends page range"), InsetIndexParams::End);
95 PageRangeTranslator const & insetindexpagerangetranslator()
97 static PageRangeTranslator const prtranslator =
98 init_insetindexpagerangetranslator();
103 PageRangeTranslatorLoc const & insetindexpagerangetranslator_loc()
105 static PageRangeTranslatorLoc const translator =
106 init_insetindexpagerangetranslator_loc();
111 PageRangeTranslator const & insetindexpagerangetranslator_latex()
113 static PageRangeTranslator const lttranslator =
114 init_insetindexpagerangetranslator_latex();
120 /////////////////////////////////////////////////////////////////////
124 ///////////////////////////////////////////////////////////////////////
127 InsetIndex::InsetIndex(Buffer * buf, InsetIndexParams const & params)
128 : InsetCollapsible(buf), params_(params)
132 void InsetIndex::latex(otexstream & ios, OutputParams const & runparams_in) const
134 OutputParams runparams(runparams_in);
135 runparams.inIndexEntry = true;
136 if (runparams_in.postpone_fragile_stuff)
137 // This is not needed and would impact sorting
138 runparams.moving_arg = false;
142 if (buffer().masterBuffer()->params().use_indices && !params_.index.empty()
143 && params_.index != "idx") {
145 os << escape(params_.index);
152 // Get the LaTeX output from InsetText. We need to deconstruct this later
153 // in order to check if we need to generate a sorting key
154 odocstringstream ourlatex;
155 otexstream ots(ourlatex);
156 InsetText::latex(ots, runparams);
157 if (runparams.find_effective()) {
158 // No need for special handling, if we are only searching for some patterns
159 os << ourlatex.str() << "}";
164 getSortkey(os, runparams);
166 os << ourlatex.str();
167 getSubentries(os, runparams, ourlatex.str());
170 os << insetindexpagerangetranslator_latex().find(params_.range);
171 getSeeRefs(os, runparams);
172 } else if (!params_.pagefmt.empty() && params_.pagefmt != "default") {
174 os << insetindexpagerangetranslator_latex().find(params_.range);
175 os << from_utf8(params_.pagefmt);
176 } else if (params_.range != InsetIndexParams::PageRange::None) {
178 os << insetindexpagerangetranslator_latex().find(params_.range);
181 // We check whether we need a sort key.
182 // If so, we use the plaintext version
183 odocstringstream ourplain;
184 InsetText::plaintext(ourplain, runparams);
186 // These are the LaTeX and plaintext representations
187 docstring latexstr = ourlatex.str();
188 docstring plainstr = ourplain.str();
190 // This will get what follows | if anything does,
191 // the command (e.g., see, textbf) for pagination
196 odocstringstream seeref;
197 otexstream otsee(seeref);
198 getSeeRefs(otsee, runparams);
200 } else if (!params_.pagefmt.empty() && params_.pagefmt != "default") {
201 cmd = from_utf8(params_.pagefmt);
203 // Check for the | separator to strip the cmd.
204 // This goes wrong on an escaped "|", but as the escape
205 // character can be changed in style files, we cannot
207 size_t pos = latexstr.find(from_ascii("|"));
208 if (pos != docstring::npos) {
209 // Put the bit after "|" into cmd...
210 cmd = latexstr.substr(pos + 1);
211 // ...and erase that stuff from latexstr
212 latexstr = latexstr.erase(pos);
213 // ...as well as from plainstr
214 size_t ppos = plainstr.find(from_ascii("|"));
215 if (ppos < plainstr.size())
216 plainstr.erase(ppos);
218 LYXERR0("The `|' separator was not found in the plaintext version!");
222 odocstringstream subentries;
223 otexstream otsub(subentries);
224 getSubentries(otsub, runparams, ourlatex.str());
225 if (subentries.str().empty()) {
226 // Separate the entries and subentries, i.e., split on "!".
227 // This goes wrong on an escaped "!", but as the escape
228 // character can be changed in style files, we cannot
230 std::vector<docstring> const levels =
231 getVectorFromString(latexstr, from_ascii("!"), true);
232 std::vector<docstring> const levels_plain =
233 getVectorFromString(plainstr, from_ascii("!"), true);
235 vector<docstring>::const_iterator it = levels.begin();
236 vector<docstring>::const_iterator end = levels.end();
237 vector<docstring>::const_iterator it2 = levels_plain.begin();
239 for (; it != end; ++it) {
241 emptySubentriesWarning(ourlatex.str());
242 if (it2 < levels_plain.end())
246 // The separator needs to be put back when
247 // writing the levels, except for the first level
253 // Now here comes the reason for this whole procedure:
254 // We try to correctly sort macros and formatted strings.
255 // If we find a command, prepend a plain text
256 // version of the content to get sorting right,
257 // e.g. \index{LyX@\LyX}, \index{text@\textbf{text}}.
258 // We do this on all levels.
259 // We don't do it if the level already contains a '@', though.
260 // Plaintext might return nothing (e.g. for ERTs).
261 // In that case, we use LaTeX.
262 docstring const spart = (levels_plain.empty() || (*it2).empty()) ? *it : *it2;
263 processLatexSorting(os, runparams, *it, spart);
264 if (it2 < levels_plain.end())
268 processLatexSorting(os, runparams, latexstr, plainstr);
269 os << subentries.str();
272 // At last, re-insert the command, separated by "|"
275 << insetindexpagerangetranslator_latex().find(params_.range)
277 } else if (params_.range != InsetIndexParams::PageRange::None) {
279 os << insetindexpagerangetranslator_latex().find(params_.range);
284 // In macros with moving arguments, such as \section,
285 // we store the index and output it after the macro (#2154)
286 if (runparams_in.postpone_fragile_stuff)
287 runparams_in.post_macro += os.str();
293 void InsetIndex::processLatexSorting(otexstream & os, OutputParams const & runparams,
294 docstring const latex, docstring const spart) const
296 if (contains(latex, '\\') && !contains(latex, '@')) {
297 // Now we need to validate that all characters in
298 // the sorting part are representable in the current
299 // encoding. If not try the LaTeX macro which might
300 // or might not be a good choice, and issue a warning.
301 pair<docstring, docstring> spart_latexed =
302 runparams.encoding->latexString(spart, runparams.dryrun);
303 if (!spart_latexed.second.empty())
304 LYXERR0("Uncodable character in index entry. Sorting might be wrong!");
305 if (spart != spart_latexed.first && !runparams.dryrun) {
307 ErrorList & errorList = buffer().errorList("Export");
308 docstring const s = bformat(_("LyX's automatic index sorting algorithm faced "
309 "problems with the entry '%1$s'.\n"
310 "Please specify the sorting of this entry manually, as "
311 "explained in the User Guide."), spart);
312 Paragraph const & par = buffer().paragraphs().front();
313 errorList.push_back(ErrorItem(_("Index sorting failed"), s,
314 {par.id(), 0}, {par.id(), -1}));
315 buffer().bufferErrors(terr, errorList);
317 // Remove remaining \'s from the sort key
318 docstring ppart = subst(spart_latexed.first, from_ascii("\\"), docstring());
319 // Plain quotes need to be escaped, however (#10649), as this
320 // is the default escape character
321 ppart = subst(ppart, from_ascii("\""), from_ascii("\\\""));
323 // Now insert the sortkey, separated by '@'.
327 // Insert the actual level text
332 void InsetIndex::docbook(XMLStream & xs, OutputParams const & runparams) const
334 // Two ways of processing this inset are implemented:
335 // - the legacy one, based on parsing the raw LaTeX (before LyX 2.4) -- unlikely to be deprecated
336 // - the modern one, based on precise insets for indexing features
337 // Like the LaTeX implementation, consider the user chooses either of those options.
339 // Get the content of the inset as LaTeX, as some things may be encoded as ERT (like {}).
340 // TODO: if there is an ERT within the index term, its conversion should be tried, in case it becomes useful;
341 // otherwise, ERTs should become comments. For now, they are just copied as-is, which is barely satisfactory.
342 odocstringstream odss;
343 otexstream ots(odss);
344 InsetText::latex(ots, runparams);
345 docstring latexString = trim(odss.str());
347 // Handle several indices (indicated in the inset instead of the raw latexString).
348 docstring indexType = from_utf8("");
349 if (buffer().masterBuffer()->params().use_indices) {
350 indexType += " type=\"" + params_.index + "\"";
353 // Split the string into its main constituents: terms, and command (see, see also, range).
354 size_t positionVerticalBar = latexString.find(from_ascii("|")); // What comes before | is (sub)(sub)entries.
355 docstring indexTerms = latexString.substr(0, positionVerticalBar);
357 if (positionVerticalBar != lyx::docstring::npos) {
358 command = latexString.substr(positionVerticalBar + 1);
361 // Handle sorting issues, with @.
364 sortAs = getSortkeyAsText(runparams);
365 // indexTerms may contain a sort key if the user has both the inset and the manual key.
367 vector<docstring> sortingElements = getVectorFromString(indexTerms, from_ascii("@"), false);
368 if (sortingElements.size() == 2) {
369 sortAs = sortingElements[0];
370 indexTerms = sortingElements[1];
374 // Handle primary, secondary, and tertiary terms (entries, subentries, and subsubentries, for LaTeX).
375 vector<docstring> terms;
376 if (const vector<docstring> potential_terms = getSubentriesAsText(runparams); !potential_terms.empty()) {
377 terms = potential_terms;
378 // The main term is not present in the vector, as it's not a subentry. The main index term is inserted raw in
379 // the index inset. Considering that the user either uses the new or the legacy mechanism, the main term is the
380 // full string within this inset (i.e. without the subinsets).
381 terms.insert(terms.begin(), latexString);
383 terms = getVectorFromString(indexTerms, from_ascii("!"), false);
386 // Handle ranges. Happily, in the raw LaTeX mode, (| and |) can only be at the end of the string!
387 const bool hasInsetRange = params_.range != InsetIndexParams::PageRange::None;
388 const bool hasStartRange = params_.range == InsetIndexParams::PageRange::Start ||
389 latexString.find(from_ascii("|(")) != lyx::docstring::npos;
390 const bool hasEndRange = params_.range == InsetIndexParams::PageRange::End ||
391 latexString.find(from_ascii("|)")) != lyx::docstring::npos;
394 // Remove the ranges from the command if they do not appear at the beginning.
396 while ((index = command.find(from_utf8("|("), index)) != std::string::npos)
397 command.erase(index, 1);
399 while ((index = command.find(from_utf8("|)"), index)) != std::string::npos)
400 command.erase(index, 1);
402 // Remove the ranges when they are the only vertical bar in the complete string.
403 if (command[0] == '(' || command[0] == ')')
407 // Handle see and seealso. As "see" is a prefix of "seealso", the order of the comparisons is important.
408 // Both commands are mutually exclusive!
409 docstring see = getSeeAsText(runparams);
410 vector<docstring> seeAlsoes = getSeeAlsoesAsText(runparams);
412 if (see.empty() && seeAlsoes.empty() && command.substr(0, 3) == "see") {
413 // Unescape brackets.
415 while ((index = command.find(from_utf8("\\{"), index)) != std::string::npos)
416 command.erase(index, 1);
418 while ((index = command.find(from_utf8("\\}"), index)) != std::string::npos)
419 command.erase(index, 1);
421 // Retrieve the part between brackets, and remove the complete seealso.
422 size_t positionOpeningBracket = command.find(from_ascii("{"));
423 size_t positionClosingBracket = command.find(from_ascii("}"));
424 docstring list = command.substr(positionOpeningBracket + 1, positionClosingBracket - positionOpeningBracket - 1);
426 // Parse the list of referenced entries (or a single one for see).
427 if (command.substr(0, 7) == "seealso") {
428 seeAlsoes = getVectorFromString(list, from_ascii(","), false);
432 if (see.find(from_ascii(",")) != std::string::npos) {
433 docstring error = from_utf8("Several index terms found as \"see\"! Only one is acceptable. "
434 "Complete entry: \"") + latexString + from_utf8("\"");
436 xs << XMLStream::ESCAPE_NONE << (from_utf8("<!-- Output Error: ") + error + from_utf8(" -->\n"));
440 // Remove the complete see/seealso from the commands, in case there is something else to parse.
441 command = command.substr(positionClosingBracket + 1);
444 // Some parts of the strings are not parsed, as they do not have anything matching in DocBook: things like
445 // formatting the entry or the page number, other strings for sorting. https://wiki.lyx.org/Tips/Indexing
446 // If there are such things in the index entry, then this code may miserably fail. For example, for "Peter|(textbf",
447 // no range will be detected.
448 // TODO: Could handle formatting as significance="preferred"?
449 if (!command.empty()) {
450 docstring error = from_utf8("Unsupported feature: an index entry contains a | with an unsupported command, ")
451 + command + from_utf8(". ") + from_utf8("Complete entry: \"") + latexString + from_utf8("\"");
453 xs << XMLStream::ESCAPE_NONE << (from_utf8("<!-- Output Error: ") + error + from_utf8(" -->\n"));
456 // Write all of this down.
457 if (terms.empty() && !hasEndRange) {
458 docstring error = from_utf8("No index term found! Complete entry: \"") + latexString + from_utf8("\"");
460 xs << XMLStream::ESCAPE_NONE << (from_utf8("<!-- Output Error: ") + error + from_utf8(" -->\n"));
462 // Generate the attributes for ranges. It is based on the terms that are indexed, but the ID must be unique
463 // to this indexing area (xml::cleanID does not guarantee this: for each call with the same arguments,
464 // the same legal ID is produced; here, as the input would be the same, the output must be, by design).
465 // Hence the thread-local storage, as the numbers must strictly be unique, and thus cannot be shared across
466 // a paragraph (making the solution used for HTML worthless). This solution is very similar to the one used in
468 // indexType can only be used for singular and startofrange types!
470 if (!hasStartRange && !hasEndRange) {
473 // Append an ID if uniqueness is not guaranteed across the document.
474 static QThreadStorage<set<docstring>> tKnownTermLists;
475 static QThreadStorage<int> tID;
477 set<docstring> &knownTermLists = tKnownTermLists.localData();
478 int &ID = tID.localData();
480 if (!tID.hasLocalData()) {
484 // Modify the index terms to add the unique ID if needed.
485 docstring newIndexTerms = indexTerms;
486 if (knownTermLists.find(indexTerms) != knownTermLists.end()) {
487 newIndexTerms += from_ascii(string("-") + to_string(ID));
489 // Only increment for the end of range, so that the same number is used for the start of range.
495 // Term list not yet known: add it to the set AFTER the end of range. After
496 if (knownTermLists.find(indexTerms) == knownTermLists.end() && hasEndRange) {
497 knownTermLists.insert(indexTerms);
500 // Generate the attributes.
501 docstring id = xml::cleanID(newIndexTerms);
503 attrs = indexType + " class=\"startofrange\" xml:id=\"" + id + "\"";
505 attrs = " class=\"endofrange\" startref=\"" + id + "\"";
509 // Handle the index terms (including the specific index for this entry).
511 xs << xml::CompTag("indexterm", attrs);
513 xs << xml::StartTag("indexterm", attrs);
514 if (!terms.empty()) { // hasEndRange has no content.
516 if (!sortAs.empty()) {
517 attr = from_utf8("sortas='") + sortAs + from_utf8("'");
520 xs << xml::StartTag("primary", attr);
522 xs << xml::EndTag("primary");
524 if (terms.size() > 1) {
525 xs << xml::StartTag("secondary");
527 xs << xml::EndTag("secondary");
529 if (terms.size() > 2) {
530 xs << xml::StartTag("tertiary");
532 xs << xml::EndTag("tertiary");
535 // Handle see and see also.
537 xs << xml::StartTag("see");
539 xs << xml::EndTag("see");
542 if (!seeAlsoes.empty()) {
543 for (auto &entry : seeAlsoes) {
544 xs << xml::StartTag("seealso");
546 xs << xml::EndTag("seealso");
551 xs << xml::EndTag("indexterm");
557 docstring InsetIndex::xhtml(XMLStream & xs, OutputParams const &) const
559 // we just print an anchor, taking the paragraph ID from
560 // our own interior paragraph, which doesn't get printed
561 std::string const magic = paragraphs().front().magicLabel();
562 std::string const attr = "id='" + magic + "'";
563 xs << xml::CompTag("a", attr);
568 bool InsetIndex::showInsetDialog(BufferView * bv) const
570 bv->showDialog("index", params2string(params_),
571 const_cast<InsetIndex *>(this));
576 void InsetIndex::doDispatch(Cursor & cur, FuncRequest & cmd)
578 switch (cmd.action()) {
580 case LFUN_INSET_MODIFY: {
581 if (cmd.getArg(0) == "changetype") {
582 cur.recordUndoInset(this);
583 params_.index = from_utf8(cmd.getArg(1));
586 if (cmd.getArg(0) == "changeparam") {
587 string const p = cmd.getArg(1);
588 string const v = cmd.getArg(2);
589 cur.recordUndoInset(this);
591 params_.range = insetindexpagerangetranslator().find(v);
592 if (p == "pagefmt") {
593 if (v == "default" || v == "textbf"
594 || v == "textit" || v == "emph")
597 lyx::dispatch(FuncRequest(LFUN_INSET_SETTINGS, "index"));
601 InsetIndexParams params;
602 InsetIndex::string2params(to_utf8(cmd.argument()), params);
603 cur.recordUndoInset(this);
604 params_.index = params.index;
605 params_.range = params.range;
606 params_.pagefmt = params.pagefmt;
607 // what we really want here is a TOC update, but that means
608 // a full buffer update
609 cur.forceBufferUpdate();
613 case LFUN_INSET_DIALOG_UPDATE:
614 cur.bv().updateDialog("index", params2string(params_));
617 case LFUN_PARAGRAPH_BREAK: {
618 // Since this inset in single-par anyway, let's use
619 // return to enter subentries
620 FuncRequest fr(LFUN_INDEXMACRO_INSERT, "subentry");
625 case LFUN_INSET_INSERT_COPY: {
626 Cursor & bvcur = cur.bv().cursor();
627 if (cmd.origin() == FuncRequest::TOC && bvcur.inTexted()) {
628 cap::copyInsetToTemp(cur, clone());
629 cap::pasteFromTemp(bvcur, bvcur.buffer()->errorList("Paste"));
636 InsetCollapsible::doDispatch(cur, cmd);
642 bool InsetIndex::getStatus(Cursor & cur, FuncRequest const & cmd,
643 FuncStatus & flag) const
645 switch (cmd.action()) {
647 case LFUN_INSET_MODIFY:
648 if (cmd.getArg(0) == "changetype") {
649 docstring const newtype = from_utf8(cmd.getArg(1));
650 Buffer const & realbuffer = *buffer().masterBuffer();
651 IndicesList const & indiceslist = realbuffer.params().indiceslist();
652 Index const * index = indiceslist.findShortcut(newtype);
653 flag.setEnabled(index != 0);
655 from_utf8(cmd.getArg(1)) == params_.index);
658 if (cmd.getArg(0) == "changeparam") {
659 string const p = cmd.getArg(1);
660 string const v = cmd.getArg(2);
662 flag.setEnabled(v == "none" || v == "start" || v == "end");
663 flag.setOnOff(params_.range == insetindexpagerangetranslator().find(v));
665 if (p == "pagefmt") {
666 flag.setEnabled(!v.empty());
667 if (params_.pagefmt == "default" || params_.pagefmt == "textbf"
668 || params_.pagefmt == "textit" || params_.pagefmt == "emph")
669 flag.setOnOff(params_.pagefmt == v);
671 flag.setOnOff(v == "custom");
675 return InsetCollapsible::getStatus(cur, cmd, flag);
677 case LFUN_INSET_DIALOG_UPDATE: {
678 Buffer const & realbuffer = *buffer().masterBuffer();
679 flag.setEnabled(realbuffer.params().use_indices);
683 case LFUN_INSET_INSERT_COPY:
684 // This can only be invoked by ToC widget
685 flag.setEnabled(cmd.origin() == FuncRequest::TOC
686 && cur.bv().cursor().inset().insetAllowed(lyxCode()));
689 case LFUN_PARAGRAPH_BREAK:
690 return macrosPossible("subentry");
692 case LFUN_INDEXMACRO_INSERT:
693 return macrosPossible(cmd.getArg(0));
696 return InsetCollapsible::getStatus(cur, cmd, flag);
701 void InsetIndex::getSortkey(otexstream & os, OutputParams const & runparams) const
703 Paragraph const & par = paragraphs().front();
704 InsetList::const_iterator it = par.insetList().begin();
705 for (; it != par.insetList().end(); ++it) {
706 Inset & inset = *it->inset;
707 if (inset.lyxCode() == INDEXMACRO_SORTKEY_CODE) {
708 InsetIndexMacro const & iim =
709 static_cast<InsetIndexMacro const &>(inset);
710 iim.getLatex(os, runparams);
717 docstring InsetIndex::getSortkeyAsText(OutputParams const & runparams) const
719 Paragraph const & par = paragraphs().front();
720 InsetList::const_iterator it = par.insetList().begin();
721 for (; it != par.insetList().end(); ++it) {
722 Inset & inset = *it->inset;
723 if (inset.lyxCode() == INDEXMACRO_SORTKEY_CODE) {
725 InsetIndexMacro const & iim =
726 static_cast<InsetIndexMacro const &>(inset);
727 iim.getLatex(os, runparams);
731 return from_ascii("");
735 void InsetIndex::emptySubentriesWarning(docstring const & mainentry) const
737 // Empty subentries crash makeindex. So warn and ignore this.
739 ErrorList & errorList = buffer().errorList("Export");
740 docstring const s = bformat(_("There is an empty index subentry in the entry '%1$s'.\n"
741 "It will be ignored in the output."), mainentry);
742 Paragraph const & par = buffer().paragraphs().front();
743 errorList.push_back(ErrorItem(_("Empty index subentry!"), s,
744 {par.id(), 0}, {par.id(), -1}));
745 buffer().bufferErrors(terr, errorList);
749 void InsetIndex::getSubentries(otexstream & os, OutputParams const & runparams,
750 docstring const & mainentry) const
752 Paragraph const & par = paragraphs().front();
753 InsetList::const_iterator it = par.insetList().begin();
755 for (; it != par.insetList().end(); ++it) {
756 Inset & inset = *it->inset;
757 if (inset.lyxCode() == INDEXMACRO_CODE) {
758 InsetIndexMacro const & iim =
759 static_cast<InsetIndexMacro const &>(inset);
760 if (iim.params().type == InsetIndexMacroParams::Subentry) {
761 if (iim.hasNoContent()) {
762 emptySubentriesWarning(mainentry);
769 iim.getLatex(os, runparams);
776 std::vector<docstring> InsetIndex::getSubentriesAsText(OutputParams const & runparams,
777 bool const asLabel) const
779 std::vector<docstring> subentries;
781 Paragraph const & par = paragraphs().front();
782 InsetList::const_iterator it = par.insetList().begin();
784 for (; it != par.insetList().end(); ++it) {
785 Inset & inset = *it->inset;
786 if (inset.lyxCode() == INDEXMACRO_CODE) {
787 InsetIndexMacro const & iim =
788 static_cast<InsetIndexMacro const &>(inset);
789 if (iim.params().type == InsetIndexMacroParams::Subentry) {
795 docstring const sl = iim.getNewLabel(l);
796 subentries.emplace_back(sl);
799 iim.getLatex(os, runparams);
800 subentries.emplace_back(os.str());
810 docstring InsetIndex::getMainSubentryAsText(OutputParams const & runparams) const
813 InsetText::latex(os, runparams);
818 void InsetIndex::getSeeRefs(otexstream & os, OutputParams const & runparams) const
820 Paragraph const & par = paragraphs().front();
821 InsetList::const_iterator it = par.insetList().begin();
822 for (; it != par.insetList().end(); ++it) {
823 Inset & inset = *it->inset;
824 if (inset.lyxCode() == INDEXMACRO_CODE) {
825 InsetIndexMacro const & iim =
826 static_cast<InsetIndexMacro const &>(inset);
827 if (iim.params().type == InsetIndexMacroParams::See
828 || iim.params().type == InsetIndexMacroParams::Seealso) {
829 iim.getLatex(os, runparams);
837 docstring InsetIndex::getSeeAsText(OutputParams const & runparams,
838 bool const asLabel) const
840 Paragraph const & par = paragraphs().front();
841 InsetList::const_iterator it = par.insetList().begin();
842 for (; it != par.insetList().end(); ++it) {
843 Inset & inset = *it->inset;
844 if (inset.lyxCode() == INDEXMACRO_CODE) {
845 InsetIndexMacro const & iim =
846 static_cast<InsetIndexMacro const &>(inset);
847 if (iim.params().type == InsetIndexMacroParams::See) {
850 return iim.getNewLabel(l);
853 iim.getLatex(os, runparams);
859 return from_ascii("");
863 std::vector<docstring> InsetIndex::getSeeAlsoesAsText(OutputParams const & runparams,
864 bool const asLabel) const
866 std::vector<docstring> seeAlsoes;
868 Paragraph const & par = paragraphs().front();
869 InsetList::const_iterator it = par.insetList().begin();
870 for (; it != par.insetList().end(); ++it) {
871 Inset & inset = *it->inset;
872 if (inset.lyxCode() == INDEXMACRO_CODE) {
873 InsetIndexMacro const & iim =
874 static_cast<InsetIndexMacro const &>(inset);
875 if (iim.params().type == InsetIndexMacroParams::Seealso) {
878 seeAlsoes.emplace_back(iim.getNewLabel(l));
881 iim.getLatex(os, runparams);
882 seeAlsoes.emplace_back(os.str());
894 bool hasInsetWithCode(const InsetIndex * const inset_index, const InsetCode code,
895 const std::set<InsetIndexMacroParams::Type> types = {})
897 Paragraph const & par = inset_index->paragraphs().front();
898 InsetList::const_iterator it = par.insetList().begin();
899 for (; it != par.insetList().end(); ++it) {
900 Inset & inset = *it->inset;
901 if (inset.lyxCode() == code) {
905 LASSERT(code == INDEXMACRO_CODE, return false);
906 InsetIndexMacro const & iim =
907 static_cast<InsetIndexMacro const &>(inset);
908 if (types.find(iim.params().type) != types.end())
918 bool InsetIndex::hasSubentries() const
920 return hasInsetWithCode(this, INDEXMACRO_CODE, {InsetIndexMacroParams::Subentry});
924 bool InsetIndex::hasSeeRef() const
926 return hasInsetWithCode(this, INDEXMACRO_CODE, {InsetIndexMacroParams::See, InsetIndexMacroParams::Seealso});
930 bool InsetIndex::hasSortKey() const
932 return hasInsetWithCode(this, INDEXMACRO_SORTKEY_CODE);
936 bool InsetIndex::macrosPossible(string const type) const
938 if (type != "see" && type != "seealso"
939 && type != "sortkey" && type != "subentry")
942 Paragraph const & par = paragraphs().front();
943 InsetList::const_iterator it = par.insetList().begin();
945 for (; it != par.insetList().end(); ++it) {
946 Inset & inset = *it->inset;
947 if (type == "sortkey" && inset.lyxCode() == INDEXMACRO_SORTKEY_CODE)
949 if (inset.lyxCode() == INDEXMACRO_CODE) {
950 InsetIndexMacro const & iim = static_cast<InsetIndexMacro const &>(inset);
951 if ((type == "see" || type == "seealso")
952 && (iim.params().type == InsetIndexMacroParams::See
953 || iim.params().type == InsetIndexMacroParams::Seealso))
955 if (type == "subentry"
956 && iim.params().type == InsetIndexMacroParams::Subentry) {
967 ColorCode InsetIndex::labelColor() const
969 if (params_.index.empty() || params_.index == from_ascii("idx"))
970 return InsetCollapsible::labelColor();
972 ColorCode c = lcolor.getFromLyXName(to_utf8(params_.index)
973 + "@" + buffer().fileName().absFileName());
975 c = InsetCollapsible::labelColor();
980 docstring InsetIndex::toolTip(BufferView const &, int, int) const
982 docstring tip = _("Index Entry");
983 if (buffer().params().use_indices && !params_.index.empty()) {
984 Buffer const & realbuffer = *buffer().masterBuffer();
985 IndicesList const & indiceslist = realbuffer.params().indiceslist();
987 Index const * index = indiceslist.findShortcut(params_.index);
989 tip += _("unknown type!");
991 tip += index->index();
995 docstring res = toolTipText(tip);
996 if (!insetindexpagerangetranslator_loc().find(params_.range).empty())
997 res += "\n" + insetindexpagerangetranslator_loc().find(params_.range);
998 if (!params_.pagefmt.empty() && params_.pagefmt != "default") {
999 res += "\n" + _("Pagination format:") + " ";
1000 if (params_.pagefmt == "textbf")
1002 else if (params_.pagefmt == "textit")
1004 else if (params_.pagefmt == "emph")
1005 res += _("emphasized");
1007 res += from_utf8(params_.pagefmt);
1013 docstring const InsetIndex::buttonLabel(BufferView const & bv) const
1015 InsetLayout const & il = getLayout();
1016 docstring label = translateIfPossible(il.labelstring());
1018 if (buffer().params().use_indices && !params_.index.empty()) {
1019 Buffer const & realbuffer = *buffer().masterBuffer();
1020 IndicesList const & indiceslist = realbuffer.params().indiceslist();
1022 Index const * index = indiceslist.findShortcut(params_.index);
1024 label += _("unknown type!");
1026 label += index->index();
1031 if (!il.contentaslabel() || geometry(bv) != ButtonOnly)
1034 res = getNewLabel(label);
1035 OutputParams const rp(0);
1036 vector<docstring> sublbls = getSubentriesAsText(rp, true);
1037 for (auto const & sublbl : sublbls) {
1038 res += " " + docstring(1, char_type(0x2023));// TRIANGULAR BULLET
1039 res += " " + sublbl;
1041 docstring see = getSeeAsText(rp, true);
1042 if (see.empty() && !getSeeAlsoesAsText(rp, true).empty())
1043 see = getSeeAlsoesAsText(rp, true).front();
1045 res += " " + docstring(1, char_type(0x261e));// WHITE RIGHT POINTING INDEX
1049 if (!insetindexpagerangetranslator_latex().find(params_.range).empty())
1050 res += " " + from_ascii(insetindexpagerangetranslator_latex().find(params_.range));
1055 void InsetIndex::write(ostream & os) const
1057 os << to_utf8(layoutName());
1059 InsetCollapsible::write(os);
1063 void InsetIndex::read(Lexer & lex)
1066 InsetCollapsible::read(lex);
1070 string InsetIndex::params2string(InsetIndexParams const & params)
1079 void InsetIndex::string2params(string const & in, InsetIndexParams & params)
1081 params = InsetIndexParams();
1085 istringstream data(in);
1087 lex.setStream(data);
1088 lex.setContext("InsetIndex::string2params");
1094 void InsetIndex::addToToc(DocIterator const & cpit, bool output_active,
1095 UpdateType utype, TocBackend & backend) const
1097 DocIterator pit = cpit;
1098 pit.push_back(CursorSlice(const_cast<InsetIndex &>(*this)));
1100 InsetLayout const & il = getLayout();
1101 docstring label = translateIfPossible(il.labelstring());
1102 if (!il.contentaslabel())
1105 str = getNewLabel(label);
1106 OutputParams const rp(0);
1107 vector<docstring> sublbls = getSubentriesAsText(rp, true);
1108 for (auto const & sublbl : sublbls) {
1109 str += " " + docstring(1, char_type(0x2023));// TRIANGULAR BULLET
1110 str += " " + sublbl;
1112 docstring see = getSeeAsText(rp, true);
1113 if (see.empty() && !getSeeAlsoesAsText(rp, true).empty())
1114 see = getSeeAlsoesAsText(rp, true).front();
1116 str += " " + docstring(1, char_type(0x261e));// WHITE RIGHT POINTING INDEX
1120 string type = "index";
1121 if (buffer().masterBuffer()->params().use_indices)
1122 type += ":" + to_utf8(params_.index);
1123 TocBuilder & b = backend.builder(type);
1124 b.pushItem(pit, str, output_active);
1125 // Proceed with the rest of the inset.
1126 InsetCollapsible::addToToc(cpit, output_active, utype, backend);
1131 void InsetIndex::validate(LaTeXFeatures & features) const
1133 if (buffer().masterBuffer()->params().use_indices
1134 && !params_.index.empty()
1135 && params_.index != "idx")
1136 features.require("splitidx");
1137 InsetCollapsible::validate(features);
1141 string InsetIndex::contextMenuName() const
1143 return "context-index";
1147 string InsetIndex::contextMenu(BufferView const & bv, int x, int y) const
1149 // We override the implementation of InsetCollapsible,
1150 // because we have eytra entries.
1151 string owncm = "context-edit-index;";
1152 return owncm + InsetCollapsible::contextMenu(bv, x, y);
1156 bool InsetIndex::hasSettings() const
1162 bool InsetIndex::insetAllowed(InsetCode code) const
1165 case INDEXMACRO_CODE:
1166 case INDEXMACRO_SORTKEY_CODE:
1171 return InsetCollapsible::insetAllowed(code);
1176 /////////////////////////////////////////////////////////////////////
1180 ///////////////////////////////////////////////////////////////////////
1183 void InsetIndexParams::write(ostream & os) const
1187 os << to_utf8(index);
1192 << insetindexpagerangetranslator().find(range)
1200 void InsetIndexParams::read(Lexer & lex)
1203 index = lex.getDocString();
1205 index = from_ascii("idx");
1206 if (lex.checkFor("range")) {
1207 string st = lex.getString();
1208 if (lex.eatLine()) {
1209 st = lex.getString();
1210 range = insetindexpagerangetranslator().find(lex.getString());
1213 if (lex.checkFor("pageformat") && lex.eatLine()) {
1214 pagefmt = lex.getString();
1219 /////////////////////////////////////////////////////////////////////
1223 ///////////////////////////////////////////////////////////////////////
1225 InsetPrintIndex::InsetPrintIndex(Buffer * buf, InsetCommandParams const & p)
1226 : InsetCommand(buf, p)
1230 ParamInfo const & InsetPrintIndex::findInfo(string const & /* cmdName */)
1232 static ParamInfo param_info_;
1233 if (param_info_.empty()) {
1234 param_info_.add("type", ParamInfo::LATEX_OPTIONAL,
1235 ParamInfo::HANDLING_ESCAPE);
1236 param_info_.add("name", ParamInfo::LATEX_OPTIONAL,
1237 ParamInfo::HANDLING_LATEXIFY);
1238 param_info_.add("literal", ParamInfo::LYX_INTERNAL);
1244 docstring InsetPrintIndex::screenLabel() const
1246 bool const printall = suffixIs(getCmdName(), '*');
1247 bool const multind = buffer().masterBuffer()->params().use_indices;
1249 && getParam("type") == from_ascii("idx"))
1250 || (getParam("type").empty() && !printall))
1252 Buffer const & realbuffer = *buffer().masterBuffer();
1253 IndicesList const & indiceslist = realbuffer.params().indiceslist();
1254 Index const * index = indiceslist.findShortcut(getParam("type"));
1255 if (!index && !printall)
1256 return _("Unknown index type!");
1257 docstring res = printall ? _("All indexes") : index->index();
1259 res += " (" + _("non-active") + ")";
1260 else if (contains(getCmdName(), "printsubindex"))
1261 res += " (" + _("subindex") + ")";
1266 bool InsetPrintIndex::isCompatibleCommand(string const & s)
1268 return s == "printindex" || s == "printsubindex"
1269 || s == "printindex*" || s == "printsubindex*";
1273 void InsetPrintIndex::doDispatch(Cursor & cur, FuncRequest & cmd)
1275 switch (cmd.action()) {
1277 case LFUN_INSET_MODIFY: {
1278 if (cmd.argument() == from_ascii("toggle-subindex")) {
1279 string scmd = getCmdName();
1280 if (contains(scmd, "printindex"))
1281 scmd = subst(scmd, "printindex", "printsubindex");
1283 scmd = subst(scmd, "printsubindex", "printindex");
1287 } else if (cmd.argument() == from_ascii("check-printindex*")) {
1288 string scmd = getCmdName();
1289 if (suffixIs(scmd, '*'))
1293 setParam("type", docstring());
1297 InsetCommandParams p(INDEX_PRINT_CODE);
1299 InsetCommand::string2params(to_utf8(cmd.argument()), p);
1300 if (p.getCmdName().empty()) {
1301 cur.noScreenUpdate();
1310 InsetCommand::doDispatch(cur, cmd);
1316 bool InsetPrintIndex::getStatus(Cursor & cur, FuncRequest const & cmd,
1317 FuncStatus & status) const
1319 switch (cmd.action()) {
1321 case LFUN_INSET_MODIFY: {
1322 if (cmd.argument() == from_ascii("toggle-subindex")) {
1323 status.setEnabled(buffer().masterBuffer()->params().use_indices);
1324 status.setOnOff(contains(getCmdName(), "printsubindex"));
1326 } else if (cmd.argument() == from_ascii("check-printindex*")) {
1327 status.setEnabled(buffer().masterBuffer()->params().use_indices);
1328 status.setOnOff(suffixIs(getCmdName(), '*'));
1330 } if (cmd.getArg(0) == "index_print"
1331 && cmd.getArg(1) == "CommandInset") {
1332 InsetCommandParams p(INDEX_PRINT_CODE);
1333 InsetCommand::string2params(to_utf8(cmd.argument()), p);
1334 if (suffixIs(p.getCmdName(), '*')) {
1335 status.setEnabled(true);
1336 status.setOnOff(false);
1339 Buffer const & realbuffer = *buffer().masterBuffer();
1340 IndicesList const & indiceslist =
1341 realbuffer.params().indiceslist();
1342 Index const * index = indiceslist.findShortcut(p["type"]);
1343 status.setEnabled(index != 0);
1344 status.setOnOff(p["type"] == getParam("type"));
1347 return InsetCommand::getStatus(cur, cmd, status);
1350 case LFUN_INSET_DIALOG_UPDATE: {
1351 status.setEnabled(buffer().masterBuffer()->params().use_indices);
1356 return InsetCommand::getStatus(cur, cmd, status);
1361 void InsetPrintIndex::updateBuffer(ParIterator const &, UpdateType, bool const /*deleted*/)
1363 Index const * index =
1364 buffer().masterParams().indiceslist().findShortcut(getParam("type"));
1366 setParam("name", index->index());
1370 void InsetPrintIndex::latex(otexstream & os, OutputParams const & runparams_in) const
1372 if (!buffer().masterBuffer()->params().use_indices) {
1373 if (getParam("type") == from_ascii("idx"))
1374 os << "\\printindex" << termcmd;
1377 OutputParams runparams = runparams_in;
1378 os << getCommand(runparams);
1382 void InsetPrintIndex::validate(LaTeXFeatures & features) const
1384 features.require("makeidx");
1385 if (buffer().masterBuffer()->params().use_indices)
1386 features.require("splitidx");
1387 InsetCommand::validate(features);
1391 string InsetPrintIndex::contextMenuName() const
1393 return buffer().masterBuffer()->params().use_indices ?
1394 "context-indexprint" : string();
1398 bool InsetPrintIndex::hasSettings() const
1400 return buffer().masterBuffer()->params().use_indices;
1407 /// Builds an entry for the index.
1408 IndexEntry(const InsetIndex * inset, OutputParams const * runparams) : inset_(inset), runparams_(runparams)
1410 LASSERT(runparams, return);
1412 // Convert the inset as text. The resulting text usually only contains an XHTML anchor (<a id='...'/>) and text.
1413 odocstringstream entry;
1414 OutputParams ours = *runparams;
1415 ours.for_toc = false;
1416 inset_->plaintext(entry, ours);
1417 entry_ = entry.str();
1419 // Determine in which index this entry belongs to.
1420 if (inset_->buffer().masterBuffer()->params().use_indices) {
1421 index_ = inset_->params_.index;
1424 // Attempt parsing the inset.
1431 /// When parsing this entry, some errors may be found; they are reported as a single string.
1432 // It is up to the caller to send this string to LYXERR and the output file, as needed.
1433 const docstring & output_error() const
1435 return output_error_;
1438 void output_error(XMLStream xs) const
1440 LYXERR0(output_error());
1441 xs << XMLStream::ESCAPE_NONE << (from_utf8("<!-- Output Error: ") + output_error() + from_utf8(" -->\n"));
1448 std::cout << to_utf8(entry_) << std::endl;
1450 // If a modern parameter is present, this is definitely a modern index inset. Similarly, if it contains the
1451 // usual LaTeX symbols (!|@), then it is definitely a legacy index inset. Otherwise, if it has features of
1452 // neither, it is both: consider this is a modern inset, to trigger the least complex code. Mixing both types
1453 // is not allowed (i.e. behaviour is undefined).
1454 const bool is_definitely_modern = inset_->hasSortKey() || inset_->hasSeeRef() || inset_->hasSubentries()
1455 || inset_->params_.range != InsetIndexParams::PageRange::None;
1456 const bool is_definitely_legacy = entry_.find('@') != std::string::npos
1457 || entry_.find('|') != std::string::npos || entry_.find('!') != std::string::npos;
1459 if (is_definitely_legacy && is_definitely_modern)
1460 output_error_ += from_utf8("Mix of index properties and raw LaTeX index commands is unsupported. ");
1463 // - is_definitely_modern == true:
1464 // - is_definitely_legacy == true: error (return whatever)
1465 // - is_definitely_legacy == false: return modern
1466 // - is_definitely_modern == false:
1467 // - is_definitely_legacy == true: return legacy
1468 // - is_definitely_legacy == false: return modern
1469 return !is_definitely_legacy;
1472 void parseAsModern()
1474 LASSERT(runparams_, return);
1476 if (inset_->hasSortKey()) {
1477 sort_as_ = inset_->getSortkeyAsText(*runparams_);
1480 terms_ = inset_->getSubentriesAsText(*runparams_);
1481 // The main term is not present in the vector, as it's not a subentry. The main index term is inserted raw in
1482 // the index inset. Considering that the user either uses the new or the legacy mechanism, the main term is the
1483 // full string within this inset (i.e. without the subinsets).
1484 terms_.insert(terms_.begin(), inset_->getMainSubentryAsText(*runparams_));
1486 has_start_range_ = inset_->params_.range == InsetIndexParams::PageRange::Start;
1487 has_end_range_ = inset_->params_.range == InsetIndexParams::PageRange::End;
1489 see_ = inset_->getSeeAsText(*runparams_);
1490 see_alsoes_ = inset_->getSeeAlsoesAsText(*runparams_);
1493 void parseAsLegacy() {
1494 // Determine if some features are known not to be supported. For now, this is only formatting like
1495 // \index{alpha@\textbf{alpha}} or \index{alpha@$\alpha$}.
1496 // @ is supported, but only for sorting, without specific formatting.
1497 if (entry_.find(from_utf8("@\\")) != lyx::docstring::npos) {
1498 output_error_ += from_utf8("Unsupported feature: an index entry contains an @\\. "
1499 "Complete entry: \"") + entry_ + from_utf8("\". ");
1501 if (entry_.find(from_utf8("@$")) != lyx::docstring::npos) {
1502 output_error_ += from_utf8("Unsupported feature: an index entry contains an @$. "
1503 "Complete entry: \"") + entry_ + from_utf8("\". ");
1506 // Split the string into its main constituents: terms, and command (see, see also, range).
1507 size_t positionVerticalBar = entry_.find(from_ascii("|")); // What comes before | is (sub)(sub)entries.
1508 docstring indexTerms = entry_.substr(0, positionVerticalBar);
1510 if (positionVerticalBar != lyx::docstring::npos) {
1511 command = entry_.substr(positionVerticalBar + 1);
1514 // Handle sorting issues, with @.
1515 vector<docstring> sortingElements = getVectorFromString(indexTerms, from_ascii("@"), false);
1516 if (sortingElements.size() == 2) {
1517 sort_as_ = sortingElements[0];
1518 indexTerms = sortingElements[1];
1521 // Handle entries, subentries, and subsubentries.
1522 terms_ = getVectorFromString(indexTerms, from_ascii("!"), false);
1524 // Handle ranges. Happily, (| and |) can only be at the end of the string!
1525 has_start_range_ = entry_.find(from_ascii("|(")) != lyx::docstring::npos;
1526 has_end_range_ = entry_.find(from_ascii("|)")) != lyx::docstring::npos;
1528 // - Remove the ranges from the command if they do not appear at the beginning.
1529 size_t range_index = 0;
1530 while ((range_index = command.find(from_utf8("|("), range_index)) != std::string::npos)
1531 command.erase(range_index, 1);
1533 while ((range_index = command.find(from_utf8("|)"), range_index)) != std::string::npos)
1534 command.erase(range_index, 1);
1536 // - Remove the ranges when they are the only vertical bar in the complete string.
1537 if (command[0] == '(' || command[0] == ')')
1538 command.erase(0, 1);
1540 // Handle see and seealso. As "see" is a prefix of "seealso", the order of the comparisons is important.
1541 // Both commands are mutually exclusive!
1542 if (command.substr(0, 3) == "see") {
1543 // Unescape brackets.
1544 size_t index_argument_begin = 0;
1545 while ((index_argument_begin = command.find(from_utf8("\\{"), index_argument_begin)) != std::string::npos)
1546 command.erase(index_argument_begin, 1);
1547 size_t index_argument_end = 0;
1548 while ((index_argument_end = command.find(from_utf8("\\}"), index_argument_end)) != std::string::npos)
1549 command.erase(index_argument_end, 1);
1551 // Retrieve the part between brackets, and remove the complete seealso.
1552 size_t position_opening_bracket = command.find(from_ascii("{"));
1553 size_t position_closing_bracket = command.find(from_ascii("}"));
1554 docstring argument = command.substr(position_opening_bracket + 1,
1555 position_closing_bracket - position_opening_bracket - 1);
1557 // Parse the argument of referenced entries (or a single one for see).
1558 if (command.substr(0, 7) == "seealso") {
1559 see_alsoes_ = getVectorFromString(argument, from_ascii(","), false);
1563 if (see_.find(from_ascii(",")) != std::string::npos) {
1564 output_error_ += from_utf8("Several index_argument_end terms found as \"see\"! Only one is "
1565 "acceptable. Complete entry: \"") + entry_ + from_utf8("\". ");
1569 // Remove the complete see/seealso from the commands, in case there is something else to parse.
1570 command = command.substr(position_closing_bracket + 1);
1573 // Some parts of the strings are not parsed, as they do not have anything matching in DocBook or XHTML:
1574 // things like formatting the entry or the page number, other strings for sorting.
1575 // https://wiki.lyx.org/Tips/Indexing
1576 // If there are such things in the index entry, then this code may miserably fail. For example, for
1577 // "Peter|(textbf", no range will be detected.
1578 if (!command.empty()) {
1579 output_error_ += from_utf8("Unsupported feature: an index entry contains a | with an unsupported command, ")
1580 + command + from_utf8(". Complete entry: \"") + entry_ + from_utf8("\". ");
1586 return terms_.size();
1589 const std::vector<docstring>& terms() const {
1593 std::vector<docstring>& terms() {
1597 const InsetIndex* inset() const {
1602 // Input inset. These should only be used when parsing the inset (either parseAsModern or parseAsLegacy, called in
1603 // the constructor).
1604 const InsetIndex * inset_;
1605 OutputParams const * runparams_;
1607 docstring index_; // Useful when there are multiple indices in the same document.
1609 // Errors, concatenated as a single string, available as soon as parsing is done, const afterwards (i.e. once
1610 // constructor is done).
1611 docstring output_error_;
1613 // Parsed index entry.
1614 std::vector<docstring> terms_; // Up to three entries, in general.
1617 bool has_start_range_;
1618 bool has_end_range_;
1620 vector<docstring> see_alsoes_;
1622 // Operators used for sorting entries (alphabetical order).
1623 friend bool operator<(IndexEntry const & lhs, IndexEntry const & rhs);
1626 bool operator<(IndexEntry const & lhs, IndexEntry const & rhs)
1628 if (lhs.terms_.empty())
1631 for (unsigned i = 0; i < min(rhs.terms_.size(), lhs.terms_.size()); ++i) {
1632 int comp = compare_no_case(lhs.terms_[i], rhs.terms_[i]);
1641 std::string generateCssClassAtDepth(unsigned depth) {
1642 std::string css_class = "entry";
1646 css_class.insert(0, "sub");
1653 std::vector<IndexEntry> entries;
1654 std::vector<IndexNode*> children;
1657 docstring termAtLevel(const IndexNode* node, unsigned depth)
1659 // 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
1660 // function could be made constant time by copying the term in each node, but that would make data duplication that
1661 // may fall out of sync; the performance benefit would probably be negligible.
1662 if (!node->entries.empty()) {
1663 LASSERT(node->entries.begin()->terms().size() >= depth + 1, return from_ascii(""));
1664 return node->entries.begin()->terms()[depth];
1667 if (!node->children.empty()) {
1668 return termAtLevel(*node->children.begin(), depth);
1671 LASSERT(false, return from_ascii(""));
1674 void insertIntoNode(const IndexEntry& entry, IndexNode* node, unsigned depth = 0)
1676 // depth == 0 is for the root, not yet the index, hence the increase when going to vector size.
1677 for (IndexNode* child : node->children) {
1678 if (entry.terms()[depth] == termAtLevel(child, depth)) {
1679 if (depth + 1 == entry.terms().size()) { // == child.entries.begin()->terms().size()
1680 // All term entries match: it's an entry.
1681 child->entries.emplace_back(entry);
1684 insertIntoNode(entry, child, depth + 1);
1690 // Out of the loop: no matching child found, create a new (possibly nested) child for this entry. Due to the
1691 // possibility of nestedness, only insert the current entry when the right level is reached. This is needed if the
1692 // first entry for a word has several levels that never appeared.
1693 // In particular, this case is called for the first entry.
1694 IndexNode* new_node = node;
1696 new_node->children.emplace_back(new IndexNode{{}, {}});
1697 new_node = new_node->children.back();
1699 } while (depth + 1 <= entry.terms().size()); // depth == 0: root node, no text associated.
1700 new_node->entries.emplace_back(entry);
1703 IndexNode* buildIndexTree(vector<IndexEntry>& entries)
1705 // Sort the entries, first on the main entry, then the subentry, then the subsubentry,
1706 // thanks to the implementation of operator<.
1707 // If this operation is not performed, the algorithm below is no more correct (and ensuring that it works with
1708 // unsorted entries would make its complexity blow up).
1709 stable_sort(entries.begin(), entries.end());
1711 // Cook the index into a nice tree data structure: entries at a given level in the index as a node, with subentries
1713 auto* index_root = new IndexNode{{}, {}};
1714 for (const IndexEntry& entry : entries) {
1715 insertIntoNode(entry, index_root);
1721 void outputIndexPage(XMLStream & xs, const IndexNode* root_node, unsigned depth = 0) // NOLINT(misc-no-recursion)
1723 LASSERT(root_node->entries.size() + root_node->children.size() > 0, return);
1725 xs << xml::StartTag("li", "class='" + generateCssClassAtDepth(depth) + "'");
1727 xs << XMLStream::ESCAPE_NONE << termAtLevel(root_node, depth);
1728 // By tree assumption, all the entries at this node have the same set of terms.
1730 if (!root_node->entries.empty()) {
1731 xs << XMLStream::ESCAPE_NONE << " — "; // Em dash, i.e. long (---).
1732 unsigned entry_number = 1;
1734 auto writeLinkToEntry = [&xs](const IndexEntry &entry, unsigned entry_number) {
1735 std::string const link_attr = "href='#" + entry.inset()->paragraphs()[0].magicLabel() + "'";
1736 xs << xml::StartTag("a", link_attr);
1737 xs << from_ascii(std::to_string(entry_number));
1738 xs << xml::EndTag("a");
1741 for (unsigned i = 0; i < root_node->entries.size(); ++i) {
1742 const IndexEntry &entry = root_node->entries[i];
1744 switch (entry.inset()->params().range) {
1745 case InsetIndexParams::PageRange::None:
1746 writeLinkToEntry(entry, entry_number);
1748 case InsetIndexParams::PageRange::Start: {
1749 // Try to find the end of the range, if it is just after. Otherwise, the output will be slightly
1750 // scrambled, but understandable. Doing better would mean implementing more of the indexing logic here
1751 // and more complex indexing here (skipping the end is not just incrementing i). Worst case output:
1753 const bool nextEntryIsEnd = i + 1 < root_node->entries.size() &&
1754 root_node->entries[i + 1].inset()->params().range ==
1755 InsetIndexParams::PageRange::End;
1756 // No need to check if both entries are for the same terms: they are in the same IndexNode.
1758 writeLinkToEntry(entry, entry_number);
1759 xs << XMLStream::ESCAPE_NONE << " – "; // En dash, i.e. semi-long (--).
1761 if (nextEntryIsEnd) {
1762 // Skip the next entry in the loop, write it right now, after the dash.
1765 writeLinkToEntry(root_node->entries[i], entry_number);
1769 case InsetIndexParams::PageRange::End:
1770 // This range end was not caught by the range start, do it now to avoid losing content.
1771 xs << XMLStream::ESCAPE_NONE << " – "; // En dash, i.e. semi-long (--).
1772 writeLinkToEntry(root_node->entries[i], entry_number);
1775 if (i < root_node->entries.size() - 1) {
1782 if (!root_node->entries.empty() && !root_node->children.empty()) {
1786 if (!root_node->children.empty()) {
1787 xs << xml::StartTag("ul", "class='" + generateCssClassAtDepth(depth) + "'");
1790 for (const IndexNode* child : root_node->children) {
1791 outputIndexPage(xs, child, depth + 1);
1794 xs << xml::EndTag("ul");
1798 xs << xml::EndTag("li");
1802 #ifdef LYX_INSET_INDEX_DEBUG
1803 void printTree(const IndexNode* root_node, unsigned depth = 0)
1805 static const std::string pattern = " ";
1807 for (unsigned i = 0; i < depth; ++i) {
1810 const std::string prefix_long = prefix + pattern + pattern;
1812 docstring term_at_level;
1814 // The root has no term.
1815 std::cout << "<ROOT>" << std::endl;
1817 LASSERT(depth - 1 <= 10, return); // Check for overflows.
1818 term_at_level = termAtLevel(root_node, depth - 1);
1819 std::cout << prefix << to_utf8(term_at_level) << " (x " << std::to_string(root_node->entries.size()) << ")"
1823 for (const IndexEntry& entry : root_node->entries) {
1824 if (entry.terms().size() != depth) {
1825 std::cout << prefix_long << "ERROR: an entry doesn't have the same number of terms" << std::endl;
1827 if (depth > 0 && entry.terms()[depth - 1] != term_at_level) {
1828 std::cout << prefix_long << "ERROR: an entry doesn't have the right term at depth " << std::to_string(depth)
1833 for (const IndexNode* node : root_node->children) {
1834 printTree(node, depth + 1);
1837 #endif // LYX_INSET_INDEX_DEBUG
1841 docstring InsetPrintIndex::xhtml(XMLStream &, OutputParams const & op) const
1843 BufferParams const & bp = buffer().masterBuffer()->params();
1845 shared_ptr<Toc const> toc = buffer().tocBackend().toc("index");
1849 // Collect the index entries in a form we can use them.
1850 vector<IndexEntry> entries;
1851 const docstring & indexType = params().getParamOr("type", from_ascii("idx"));
1852 for (const TocItem& item : *toc) {
1853 const auto* inset = static_cast<const InsetIndex*>(&(item.dit().inset()));
1854 if (item.isOutput() && inset->params().index == indexType)
1855 entries.emplace_back(IndexEntry{inset, &op});
1858 // If all the index entries are in notes or not displayed, get out sooner.
1859 if (entries.empty())
1862 const IndexNode* index_root = buildIndexTree(entries);
1863 #ifdef LYX_INSET_INDEX_DEBUG
1864 printTree(index_root);
1867 // Start generating the XHTML index.
1868 Layout const & lay = bp.documentClass().htmlTOCLayout();
1869 string const & tocclass = lay.defaultCSSClass();
1870 string const tocattr = "class='index " + tocclass + "'";
1871 docstring const indexName = params().getParamOr("name", from_ascii("Index"));
1873 // we'll use our own stream, because we are going to defer everything.
1874 // that's how we deal with the fact that we're probably inside a standard
1875 // paragraph, and we don't want to be.
1876 odocstringstream ods;
1879 xs << xml::StartTag("div", tocattr);
1881 xs << xml::StartTag(lay.htmltag(), lay.htmlattr());
1882 xs << translateIfPossible(indexName, op.local_font->language()->lang());
1883 xs << xml::EndTag(lay.htmltag());
1885 xs << xml::StartTag("ul", "class='main'");
1888 LASSERT(index_root->entries.empty(), return docstring()); // No index entry should have zero terms.
1889 for (const IndexNode* node : index_root->children) {
1890 outputIndexPage(xs, node);
1893 xs << xml::EndTag("ul");
1895 xs << xml::EndTag("div");