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"
32 #include "output_latex.h"
33 #include "output_xhtml.h"
35 #include "texstream.h"
36 #include "TextClass.h"
37 #include "TocBackend.h"
39 #include "support/debug.h"
40 #include "support/docstream.h"
41 #include "support/FileName.h"
42 #include "support/gettext.h"
43 #include "support/lstrings.h"
44 #include "support/Translator.h"
46 #include "frontends/alert.h"
52 #include <QThreadStorage>
55 using namespace lyx::support;
61 typedef Translator<string, InsetIndexParams::PageRange> PageRangeTranslator;
62 typedef Translator<docstring, InsetIndexParams::PageRange> PageRangeTranslatorLoc;
64 PageRangeTranslator const init_insetindexpagerangetranslator()
66 PageRangeTranslator translator("none", InsetIndexParams::None);
67 translator.addPair("start", InsetIndexParams::Start);
68 translator.addPair("end", InsetIndexParams::End);
72 PageRangeTranslator const init_insetindexpagerangetranslator_latex()
74 PageRangeTranslator translator("", InsetIndexParams::None);
75 translator.addPair("(", InsetIndexParams::Start);
76 translator.addPair(")", InsetIndexParams::End);
81 PageRangeTranslatorLoc const init_insetindexpagerangetranslator_loc()
83 PageRangeTranslatorLoc translator(docstring(), InsetIndexParams::None);
84 translator.addPair(_("Starts page range"), InsetIndexParams::Start);
85 translator.addPair(_("Ends page range"), InsetIndexParams::End);
90 PageRangeTranslator const & insetindexpagerangetranslator()
92 static PageRangeTranslator const prtranslator =
93 init_insetindexpagerangetranslator();
98 PageRangeTranslatorLoc const & insetindexpagerangetranslator_loc()
100 static PageRangeTranslatorLoc const translator =
101 init_insetindexpagerangetranslator_loc();
106 PageRangeTranslator const & insetindexpagerangetranslator_latex()
108 static PageRangeTranslator const lttranslator =
109 init_insetindexpagerangetranslator_latex();
115 /////////////////////////////////////////////////////////////////////
119 ///////////////////////////////////////////////////////////////////////
122 InsetIndex::InsetIndex(Buffer * buf, InsetIndexParams const & params)
123 : InsetCollapsible(buf), params_(params)
127 void InsetIndex::latex(otexstream & ios, OutputParams const & runparams_in) const
129 OutputParams runparams(runparams_in);
130 runparams.inIndexEntry = true;
134 if (buffer().masterBuffer()->params().use_indices && !params_.index.empty()
135 && params_.index != "idx") {
137 os << escape(params_.index);
144 // Get the LaTeX output from InsetText. We need to deconstruct this later
145 // in order to check if we need to generate a sorting key
146 odocstringstream ourlatex;
147 otexstream ots(ourlatex);
148 InsetText::latex(ots, runparams);
149 if (runparams.for_search != OutputParams::NoSearch) {
150 // No need for special handling, if we are only searching for some patterns
151 os << ourlatex.str() << "}";
156 getSortkey(os, runparams);
158 os << ourlatex.str();
159 getSubentries(os, runparams);
162 os << insetindexpagerangetranslator_latex().find(params_.range);
163 getSeeRefs(os, runparams);
166 // We check whether we need a sort key.
167 // If so, we use the plaintext version
168 odocstringstream ourplain;
169 InsetText::plaintext(ourplain, runparams);
171 // These are the LaTeX and plaintext representations
172 docstring latexstr = ourlatex.str();
173 docstring plainstr = ourplain.str();
175 // This will get what follows | if anything does,
176 // the command (e.g., see, textbf) for pagination
181 odocstringstream seeref;
182 otexstream otsee(seeref);
183 getSeeRefs(otsee, runparams);
185 } else if (!params_.pagefmt.empty() && params_.pagefmt != "default") {
186 cmd = from_utf8(params_.pagefmt);
188 // Check for the | separator to strip the cmd.
189 // This goes wrong on an escaped "|", but as the escape
190 // character can be changed in style files, we cannot
192 size_t pos = latexstr.find(from_ascii("|"));
193 if (pos != docstring::npos) {
194 // Put the bit after "|" into cmd...
195 cmd = latexstr.substr(pos + 1);
196 // ...and erase that stuff from latexstr
197 latexstr = latexstr.erase(pos);
198 // ...as well as from plainstr
199 size_t ppos = plainstr.find(from_ascii("|"));
200 if (ppos < plainstr.size())
201 plainstr.erase(ppos);
203 LYXERR0("The `|' separator was not found in the plaintext version!");
207 odocstringstream subentries;
208 otexstream otsub(subentries);
209 getSubentries(otsub, runparams);
210 if (subentries.str().empty()) {
211 // Separate the entries and subentries, i.e., split on "!".
212 // This goes wrong on an escaped "!", but as the escape
213 // character can be changed in style files, we cannot
215 std::vector<docstring> const levels =
216 getVectorFromString(latexstr, from_ascii("!"), true);
217 std::vector<docstring> const levels_plain =
218 getVectorFromString(plainstr, from_ascii("!"), true);
220 vector<docstring>::const_iterator it = levels.begin();
221 vector<docstring>::const_iterator end = levels.end();
222 vector<docstring>::const_iterator it2 = levels_plain.begin();
224 for (; it != end; ++it) {
225 // The separator needs to be put back when
226 // writing the levels, except for the first level
232 // Now here comes the reason for this whole procedure:
233 // We try to correctly sort macros and formatted strings.
234 // If we find a command, prepend a plain text
235 // version of the content to get sorting right,
236 // e.g. \index{LyX@\LyX}, \index{text@\textbf{text}}.
237 // We do this on all levels.
238 // We don't do it if the level already contains a '@', though.
239 // Plaintext might return nothing (e.g. for ERTs).
240 // In that case, we use LaTeX.
241 docstring const spart = (levels_plain.empty() || (*it2).empty()) ? *it : *it2;
242 processLatexSorting(os, runparams, *it, spart);
243 if (it2 < levels_plain.end())
247 processLatexSorting(os, runparams, latexstr, plainstr);
248 os << subentries.str();
251 // At last, re-insert the command, separated by "|"
254 << insetindexpagerangetranslator_latex().find(params_.range)
260 // In macros with moving arguments, such as \section,
261 // we store the index and output it after the macro (#2154)
262 if (runparams_in.postpone_fragile_stuff)
263 runparams_in.post_macro += os.str();
269 void InsetIndex::processLatexSorting(otexstream & os, OutputParams const & runparams,
270 docstring const latex, docstring const spart) const
272 if (contains(latex, '\\') && !contains(latex, '@')) {
273 // Now we need to validate that all characters in
274 // the sorting part are representable in the current
275 // encoding. If not try the LaTeX macro which might
276 // or might not be a good choice, and issue a warning.
277 pair<docstring, docstring> spart_latexed =
278 runparams.encoding->latexString(spart, runparams.dryrun);
279 if (!spart_latexed.second.empty())
280 LYXERR0("Uncodable character in index entry. Sorting might be wrong!");
281 if (spart != spart_latexed.first && !runparams.dryrun) {
283 ErrorList & errorList = buffer().errorList("Export");
284 docstring const s = bformat(_("LyX's automatic index sorting algorithm faced "
285 "problems with the entry '%1$s'.\n"
286 "Please specify the sorting of this entry manually, as "
287 "explained in the User Guide."), spart);
288 Paragraph const & par = buffer().paragraphs().front();
289 errorList.push_back(ErrorItem(_("Index sorting failed"), s,
290 {par.id(), 0}, {par.id(), -1}));
291 buffer().bufferErrors(terr, errorList);
293 // Remove remaining \'s from the sort key
294 docstring ppart = subst(spart_latexed.first, from_ascii("\\"), docstring());
295 // Plain quotes need to be escaped, however (#10649), as this
296 // is the default escape character
297 ppart = subst(ppart, from_ascii("\""), from_ascii("\\\""));
299 // Now insert the sortkey, separated by '@'.
303 // Insert the actual level text
308 void InsetIndex::docbook(XMLStream & xs, OutputParams const & runparams) const
310 // Two ways of processing this inset are implemented:
311 // - the legacy one, based on parsing the raw LaTeX (before LyX 2.4) -- unlikely to be deprecated
312 // - the modern one, based on precise insets for indexing features
313 // Like the LaTeX implementation, consider the user chooses either of those options.
315 // Get the content of the inset as LaTeX, as some things may be encoded as ERT (like {}).
316 // TODO: if there is an ERT within the index term, its conversion should be tried, in case it becomes useful;
317 // otherwise, ERTs should become comments. For now, they are just copied as-is, which is barely satisfactory.
318 odocstringstream odss;
319 otexstream ots(odss);
320 InsetText::latex(ots, runparams);
321 docstring latexString = trim(odss.str());
323 // Check whether there are unsupported things. @ is supported, but only for sorting, without specific formatting.
324 if (latexString.find(from_utf8("@\\")) != lyx::docstring::npos) {
325 docstring error = from_utf8("Unsupported feature: an index entry contains an @\\. "
326 "Complete entry: \"") + latexString + from_utf8("\"");
328 xs << XMLStream::ESCAPE_NONE << (from_utf8("<!-- Output Error: ") + error + from_utf8(" -->\n"));
331 // Handle several indices (indicated in the inset instead of the raw latexString).
332 docstring indexType = from_utf8("");
333 if (buffer().masterBuffer()->params().use_indices) {
334 indexType += " type=\"" + params_.index + "\"";
337 // Split the string into its main constituents: terms, and command (see, see also, range).
338 size_t positionVerticalBar = latexString.find(from_ascii("|")); // What comes before | is (sub)(sub)entries.
339 docstring indexTerms = latexString.substr(0, positionVerticalBar);
341 if (positionVerticalBar != lyx::docstring::npos) {
342 command = latexString.substr(positionVerticalBar + 1);
345 // Handle sorting issues, with @.
348 sortAs = getSortkeyAsText(runparams);
349 // indexTerms may contain a sort key if the user has both the inset and the manual key.
351 vector<docstring> sortingElements = getVectorFromString(indexTerms, from_ascii("@"), false);
352 if (sortingElements.size() == 2) {
353 sortAs = sortingElements[0];
354 indexTerms = sortingElements[1];
358 // Handle primary, secondary, and tertiary terms (entries, subentries, and subsubentries, for LaTeX).
359 vector<docstring> terms;
360 if (const vector<docstring> potential_terms = getSubentriesAsText(runparams); !potential_terms.empty()) {
361 terms = potential_terms;
362 // The main term is not present in the vector, as it's not a subentry. The main index term is inserted raw in
363 // the index inset. Considering that the user either uses the new or the legacy mechanism, the main term is the
364 // full string within this inset (i.e. without the subinsets).
365 terms.insert(terms.begin(), latexString);
367 terms = getVectorFromString(indexTerms, from_ascii("!"), false);
370 // Handle ranges. Happily, in the raw LaTeX mode, (| and |) can only be at the end of the string!
371 bool hasInsetRange = params_.range != InsetIndexParams::PageRange::None;
372 bool hasStartRange = params_.range == InsetIndexParams::PageRange::Start ||
373 latexString.find(from_ascii("|(")) != lyx::docstring::npos;
374 bool hasEndRange = params_.range == InsetIndexParams::PageRange::End ||
375 latexString.find(from_ascii("|)")) != lyx::docstring::npos;
378 // Remove the ranges from the command if they do not appear at the beginning.
380 while ((index = command.find(from_utf8("|("), index)) != std::string::npos)
381 command.erase(index, 1);
383 while ((index = command.find(from_utf8("|)"), index)) != std::string::npos)
384 command.erase(index, 1);
386 // Remove the ranges when they are the only vertical bar in the complete string.
387 if (command[0] == '(' || command[0] == ')')
391 // Handle see and seealso. As "see" is a prefix of "seealso", the order of the comparisons is important.
392 // Both commands are mutually exclusive!
393 docstring see = getSeeAsText(runparams);
394 vector<docstring> seeAlsoes = getSeeAlsoesAsText(runparams);
396 if (see.empty() && seeAlsoes.empty() && command.substr(0, 3) == "see") {
397 // Unescape brackets.
399 while ((index = command.find(from_utf8("\\{"), index)) != std::string::npos)
400 command.erase(index, 1);
402 while ((index = command.find(from_utf8("\\}"), index)) != std::string::npos)
403 command.erase(index, 1);
405 // Retrieve the part between brackets, and remove the complete seealso.
406 size_t positionOpeningBracket = command.find(from_ascii("{"));
407 size_t positionClosingBracket = command.find(from_ascii("}"));
408 docstring list = command.substr(positionOpeningBracket + 1, positionClosingBracket - positionOpeningBracket - 1);
410 // Parse the list of referenced entries (or a single one for see).
411 if (command.substr(0, 7) == "seealso") {
412 seeAlsoes = getVectorFromString(list, from_ascii(","), false);
416 if (see.find(from_ascii(",")) != std::string::npos) {
417 docstring error = from_utf8("Several index terms found as \"see\"! Only one is acceptable. "
418 "Complete entry: \"") + latexString + from_utf8("\"");
420 xs << XMLStream::ESCAPE_NONE << (from_utf8("<!-- Output Error: ") + error + from_utf8(" -->\n"));
424 // Remove the complete see/seealso from the commands, in case there is something else to parse.
425 command = command.substr(positionClosingBracket + 1);
428 // Some parts of the strings are not parsed, as they do not have anything matching in DocBook: things like
429 // formatting the entry or the page number, other strings for sorting. https://wiki.lyx.org/Tips/Indexing
430 // If there are such things in the index entry, then this code may miserably fail. For example, for "Peter|(textbf",
431 // no range will be detected.
432 // TODO: Could handle formatting as significance="preferred"?
433 if (!command.empty()) {
434 docstring error = from_utf8("Unsupported feature: an index entry contains a | with an unsupported command, ")
435 + command + from_utf8(". ") + from_utf8("Complete entry: \"") + latexString + from_utf8("\"");
437 xs << XMLStream::ESCAPE_NONE << (from_utf8("<!-- Output Error: ") + error + from_utf8(" -->\n"));
440 // Write all of this down.
441 if (terms.empty() && !hasEndRange) {
442 docstring error = from_utf8("No index term found! Complete entry: \"") + latexString + from_utf8("\"");
444 xs << XMLStream::ESCAPE_NONE << (from_utf8("<!-- Output Error: ") + error + from_utf8(" -->\n"));
446 // Generate the attributes for ranges. It is based on the terms that are indexed, but the ID must be unique
447 // to this indexing area (xml::cleanID does not guarantee this: for each call with the same arguments,
448 // the same legal ID is produced; here, as the input would be the same, the output must be, by design).
449 // Hence the thread-local storage, as the numbers must strictly be unique, and thus cannot be shared across
450 // a paragraph (making the solution used for HTML worthless). This solution is very similar to the one used in
452 // indexType can only be used for singular and startofrange types!
454 if (!hasStartRange && !hasEndRange) {
457 // Append an ID if uniqueness is not guaranteed across the document.
458 static QThreadStorage<set<docstring>> tKnownTermLists;
459 static QThreadStorage<int> tID;
461 set<docstring> &knownTermLists = tKnownTermLists.localData();
462 int &ID = tID.localData();
464 if (!tID.hasLocalData()) {
468 // Modify the index terms to add the unique ID if needed.
469 docstring newIndexTerms = indexTerms;
470 if (knownTermLists.find(indexTerms) != knownTermLists.end()) {
471 newIndexTerms += from_ascii(string("-") + to_string(ID));
473 // Only increment for the end of range, so that the same number is used for the start of range.
479 // Term list not yet known: add it to the set AFTER the end of range. After
480 if (knownTermLists.find(indexTerms) == knownTermLists.end() && hasEndRange) {
481 knownTermLists.insert(indexTerms);
484 // Generate the attributes.
485 docstring id = xml::cleanID(newIndexTerms);
487 attrs = indexType + " class=\"startofrange\" xml:id=\"" + id + "\"";
489 attrs = " class=\"endofrange\" startref=\"" + id + "\"";
493 // Handle the index terms (including the specific index for this entry).
495 xs << xml::CompTag("indexterm", attrs);
497 xs << xml::StartTag("indexterm", attrs);
498 if (!terms.empty()) { // hasEndRange has no content.
500 if (!sortAs.empty()) {
501 attr = from_utf8("sortas='") + sortAs + from_utf8("'");
504 xs << xml::StartTag("primary", attr);
506 xs << xml::EndTag("primary");
508 if (terms.size() > 1) {
509 xs << xml::StartTag("secondary");
511 xs << xml::EndTag("secondary");
513 if (terms.size() > 2) {
514 xs << xml::StartTag("tertiary");
516 xs << xml::EndTag("tertiary");
519 // Handle see and see also.
521 xs << xml::StartTag("see");
523 xs << xml::EndTag("see");
526 if (!seeAlsoes.empty()) {
527 for (auto &entry : seeAlsoes) {
528 xs << xml::StartTag("seealso");
530 xs << xml::EndTag("seealso");
535 xs << xml::EndTag("indexterm");
541 docstring InsetIndex::xhtml(XMLStream & xs, OutputParams const &) const
543 // we just print an anchor, taking the paragraph ID from
544 // our own interior paragraph, which doesn't get printed
545 std::string const magic = paragraphs().front().magicLabel();
546 std::string const attr = "id='" + magic + "'";
547 xs << xml::CompTag("a", attr);
552 bool InsetIndex::showInsetDialog(BufferView * bv) const
554 bv->showDialog("index", params2string(params_),
555 const_cast<InsetIndex *>(this));
560 void InsetIndex::doDispatch(Cursor & cur, FuncRequest & cmd)
562 switch (cmd.action()) {
564 case LFUN_INSET_MODIFY: {
565 if (cmd.getArg(0) == "changetype") {
566 cur.recordUndoInset(this);
567 params_.index = from_utf8(cmd.getArg(1));
570 InsetIndexParams params;
571 InsetIndex::string2params(to_utf8(cmd.argument()), params);
572 cur.recordUndoInset(this);
573 params_.index = params.index;
574 params_.range = params.range;
575 params_.pagefmt = params.pagefmt;
576 // what we really want here is a TOC update, but that means
577 // a full buffer update
578 cur.forceBufferUpdate();
582 case LFUN_INSET_DIALOG_UPDATE:
583 cur.bv().updateDialog("index", params2string(params_));
587 InsetCollapsible::doDispatch(cur, cmd);
593 bool InsetIndex::getStatus(Cursor & cur, FuncRequest const & cmd,
594 FuncStatus & flag) const
596 switch (cmd.action()) {
598 case LFUN_INSET_MODIFY:
599 if (cmd.getArg(0) == "changetype") {
600 docstring const newtype = from_utf8(cmd.getArg(1));
601 Buffer const & realbuffer = *buffer().masterBuffer();
602 IndicesList const & indiceslist = realbuffer.params().indiceslist();
603 Index const * index = indiceslist.findShortcut(newtype);
604 flag.setEnabled(index != 0);
606 from_utf8(cmd.getArg(1)) == params_.index);
609 return InsetCollapsible::getStatus(cur, cmd, flag);
611 case LFUN_INSET_DIALOG_UPDATE: {
612 Buffer const & realbuffer = *buffer().masterBuffer();
613 flag.setEnabled(realbuffer.params().use_indices);
617 case LFUN_INDEXMACRO_INSERT:
618 return macrosPossible(cmd.getArg(0));
621 return InsetCollapsible::getStatus(cur, cmd, flag);
626 void InsetIndex::getSortkey(otexstream & os, OutputParams const & runparams) const
628 Paragraph const & par = paragraphs().front();
629 InsetList::const_iterator it = par.insetList().begin();
630 for (; it != par.insetList().end(); ++it) {
631 Inset & inset = *it->inset;
632 if (inset.lyxCode() == INDEXMACRO_SORTKEY_CODE) {
633 InsetIndexMacro const & iim =
634 static_cast<InsetIndexMacro const &>(inset);
635 iim.getLatex(os, runparams);
642 docstring InsetIndex::getSortkeyAsText(OutputParams const & runparams) const
644 Paragraph const & par = paragraphs().front();
645 InsetList::const_iterator it = par.insetList().begin();
646 for (; it != par.insetList().end(); ++it) {
647 Inset & inset = *it->inset;
648 if (inset.lyxCode() == INDEXMACRO_SORTKEY_CODE) {
650 InsetIndexMacro const & iim =
651 static_cast<InsetIndexMacro const &>(inset);
652 iim.getLatex(os, runparams);
656 return from_ascii("");
660 void InsetIndex::getSubentries(otexstream & os, OutputParams const & runparams) const
662 Paragraph const & par = paragraphs().front();
663 InsetList::const_iterator it = par.insetList().begin();
665 for (; it != par.insetList().end(); ++it) {
666 Inset & inset = *it->inset;
667 if (inset.lyxCode() == INDEXMACRO_CODE) {
668 InsetIndexMacro const & iim =
669 static_cast<InsetIndexMacro const &>(inset);
670 if (iim.params().type == InsetIndexMacroParams::Subindex) {
675 iim.getLatex(os, runparams);
682 std::vector<docstring> InsetIndex::getSubentriesAsText(OutputParams const & runparams) const
684 std::vector<docstring> subentries;
686 Paragraph const & par = paragraphs().front();
687 InsetList::const_iterator it = par.insetList().begin();
689 for (; it != par.insetList().end(); ++it) {
690 Inset & inset = *it->inset;
691 if (inset.lyxCode() == INDEXMACRO_CODE) {
692 InsetIndexMacro const & iim =
693 static_cast<InsetIndexMacro const &>(inset);
694 if (iim.params().type == InsetIndexMacroParams::Subindex) {
700 iim.getLatex(os, runparams);
701 subentries.emplace_back(os.str());
710 void InsetIndex::getSeeRefs(otexstream & os, OutputParams const & runparams) const
712 Paragraph const & par = paragraphs().front();
713 InsetList::const_iterator it = par.insetList().begin();
714 for (; it != par.insetList().end(); ++it) {
715 Inset & inset = *it->inset;
716 if (inset.lyxCode() == INDEXMACRO_CODE) {
717 InsetIndexMacro const & iim =
718 static_cast<InsetIndexMacro const &>(inset);
719 if (iim.params().type == InsetIndexMacroParams::See
720 || iim.params().type == InsetIndexMacroParams::Seealso) {
721 iim.getLatex(os, runparams);
729 docstring InsetIndex::getSeeAsText(OutputParams const & runparams) const
731 Paragraph const & par = paragraphs().front();
732 InsetList::const_iterator it = par.insetList().begin();
733 for (; it != par.insetList().end(); ++it) {
734 Inset & inset = *it->inset;
735 if (inset.lyxCode() == INDEXMACRO_CODE) {
736 InsetIndexMacro const & iim =
737 static_cast<InsetIndexMacro const &>(inset);
738 if (iim.params().type == InsetIndexMacroParams::See) {
740 iim.getLatex(os, runparams);
745 return from_ascii("");
749 std::vector<docstring> InsetIndex::getSeeAlsoesAsText(OutputParams const & runparams) const
751 std::vector<docstring> seeAlsoes;
753 Paragraph const & par = paragraphs().front();
754 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::Seealso) {
762 iim.getLatex(os, runparams);
763 seeAlsoes.emplace_back(os.str());
772 bool InsetIndex::hasSeeRef() const
774 Paragraph const & par = paragraphs().front();
775 InsetList::const_iterator it = par.insetList().begin();
776 for (; it != par.insetList().end(); ++it) {
777 Inset & inset = *it->inset;
778 if (inset.lyxCode() == INDEXMACRO_CODE) {
779 InsetIndexMacro const & iim =
780 static_cast<InsetIndexMacro const &>(inset);
781 if (iim.params().type == InsetIndexMacroParams::See
782 || iim.params().type == InsetIndexMacroParams::Seealso)
790 bool InsetIndex::hasSortKey() const
792 Paragraph const & par = paragraphs().front();
793 InsetList::const_iterator it = par.insetList().begin();
794 for (; it != par.insetList().end(); ++it) {
795 Inset & inset = *it->inset;
796 if (inset.lyxCode() == INDEXMACRO_SORTKEY_CODE)
803 bool InsetIndex::macrosPossible(string const type) const
805 if (type != "see" && type != "seealso"
806 && type != "sortkey" && type != "subindex")
809 Paragraph const & par = paragraphs().front();
810 InsetList::const_iterator it = par.insetList().begin();
812 for (; it != par.insetList().end(); ++it) {
813 Inset & inset = *it->inset;
814 if (type == "sortkey" && inset.lyxCode() == INDEXMACRO_SORTKEY_CODE)
816 if (inset.lyxCode() == INDEXMACRO_CODE) {
817 InsetIndexMacro const & iim = static_cast<InsetIndexMacro const &>(inset);
818 if ((type == "see" || type == "seealso")
819 && (iim.params().type == InsetIndexMacroParams::See
820 || iim.params().type == InsetIndexMacroParams::Seealso))
822 if (type == "subindex"
823 && iim.params().type == InsetIndexMacroParams::Subindex) {
834 ColorCode InsetIndex::labelColor() const
836 if (params_.index.empty() || params_.index == from_ascii("idx"))
837 return InsetCollapsible::labelColor();
839 ColorCode c = lcolor.getFromLyXName(to_utf8(params_.index)
840 + "@" + buffer().fileName().absFileName());
842 c = InsetCollapsible::labelColor();
847 docstring InsetIndex::toolTip(BufferView const &, int, int) const
849 docstring tip = _("Index Entry");
850 if (buffer().params().use_indices && !params_.index.empty()) {
851 Buffer const & realbuffer = *buffer().masterBuffer();
852 IndicesList const & indiceslist = realbuffer.params().indiceslist();
854 Index const * index = indiceslist.findShortcut(params_.index);
856 tip += _("unknown type!");
858 tip += index->index();
862 docstring res = toolTipText(tip);
863 if (!insetindexpagerangetranslator_loc().find(params_.range).empty())
864 res += "\n" + insetindexpagerangetranslator_loc().find(params_.range);
865 if (!params_.pagefmt.empty() && params_.pagefmt != "default") {
866 res += "\n" + _("Pagination format:") + " ";
867 if (params_.pagefmt == "textbf")
869 else if (params_.pagefmt == "textit")
871 else if (params_.pagefmt == "emph")
872 res += _("emphasized");
874 res += from_utf8(params_.pagefmt);
880 docstring const InsetIndex::buttonLabel(BufferView const & bv) const
882 InsetLayout const & il = getLayout();
883 docstring label = translateIfPossible(il.labelstring());
885 if (buffer().params().use_indices && !params_.index.empty()) {
886 Buffer const & realbuffer = *buffer().masterBuffer();
887 IndicesList const & indiceslist = realbuffer.params().indiceslist();
889 Index const * index = indiceslist.findShortcut(params_.index);
891 label += _("unknown type!");
893 label += index->index();
898 if (!il.contentaslabel() || geometry(bv) != ButtonOnly)
901 res = getNewLabel(label);
902 if (!insetindexpagerangetranslator_latex().find(params_.range).empty())
903 res += " " + from_ascii(insetindexpagerangetranslator_latex().find(params_.range));
908 void InsetIndex::write(ostream & os) const
910 os << to_utf8(layoutName());
912 InsetCollapsible::write(os);
916 void InsetIndex::read(Lexer & lex)
919 InsetCollapsible::read(lex);
923 string InsetIndex::params2string(InsetIndexParams const & params)
932 void InsetIndex::string2params(string const & in, InsetIndexParams & params)
934 params = InsetIndexParams();
938 istringstream data(in);
941 lex.setContext("InsetIndex::string2params");
947 void InsetIndex::addToToc(DocIterator const & cpit, bool output_active,
948 UpdateType utype, TocBackend & backend) const
950 DocIterator pit = cpit;
951 pit.push_back(CursorSlice(const_cast<InsetIndex &>(*this)));
953 string type = "index";
954 if (buffer().masterBuffer()->params().use_indices)
955 type += ":" + to_utf8(params_.index);
956 // this is unlikely to be terribly long
957 text().forOutliner(str, INT_MAX);
958 TocBuilder & b = backend.builder(type);
959 b.pushItem(pit, str, output_active);
960 // Proceed with the rest of the inset.
961 InsetCollapsible::addToToc(cpit, output_active, utype, backend);
966 void InsetIndex::validate(LaTeXFeatures & features) const
968 if (buffer().masterBuffer()->params().use_indices
969 && !params_.index.empty()
970 && params_.index != "idx")
971 features.require("splitidx");
972 InsetCollapsible::validate(features);
976 string InsetIndex::contextMenuName() const
978 return "context-index";
982 string InsetIndex::contextMenu(BufferView const & bv, int x, int y) const
984 // We override the implementation of InsetCollapsible,
985 // because we have eytra entries.
986 string owncm = "context-edit-index;";
987 return owncm + InsetCollapsible::contextMenu(bv, x, y);
991 bool InsetIndex::hasSettings() const
997 bool InsetIndex::insetAllowed(InsetCode code) const
1000 case INDEXMACRO_CODE:
1001 case INDEXMACRO_SORTKEY_CODE:
1006 return InsetCollapsible::insetAllowed(code);
1011 /////////////////////////////////////////////////////////////////////
1015 ///////////////////////////////////////////////////////////////////////
1018 void InsetIndexParams::write(ostream & os) const
1022 os << to_utf8(index);
1027 << insetindexpagerangetranslator().find(range)
1035 void InsetIndexParams::read(Lexer & lex)
1038 index = lex.getDocString();
1040 index = from_ascii("idx");
1041 if (lex.checkFor("range")) {
1042 string st = lex.getString();
1043 if (lex.eatLine()) {
1044 st = lex.getString();
1045 range = insetindexpagerangetranslator().find(lex.getString());
1048 if (lex.checkFor("pageformat") && lex.eatLine()) {
1049 pagefmt = lex.getString();
1054 /////////////////////////////////////////////////////////////////////
1058 ///////////////////////////////////////////////////////////////////////
1060 InsetPrintIndex::InsetPrintIndex(Buffer * buf, InsetCommandParams const & p)
1061 : InsetCommand(buf, p)
1065 ParamInfo const & InsetPrintIndex::findInfo(string const & /* cmdName */)
1067 static ParamInfo param_info_;
1068 if (param_info_.empty()) {
1069 param_info_.add("type", ParamInfo::LATEX_OPTIONAL,
1070 ParamInfo::HANDLING_ESCAPE);
1071 param_info_.add("name", ParamInfo::LATEX_OPTIONAL,
1072 ParamInfo::HANDLING_LATEXIFY);
1073 param_info_.add("literal", ParamInfo::LYX_INTERNAL);
1079 docstring InsetPrintIndex::screenLabel() const
1081 bool const printall = suffixIs(getCmdName(), '*');
1082 bool const multind = buffer().masterBuffer()->params().use_indices;
1084 && getParam("type") == from_ascii("idx"))
1085 || (getParam("type").empty() && !printall))
1087 Buffer const & realbuffer = *buffer().masterBuffer();
1088 IndicesList const & indiceslist = realbuffer.params().indiceslist();
1089 Index const * index = indiceslist.findShortcut(getParam("type"));
1090 if (!index && !printall)
1091 return _("Unknown index type!");
1092 docstring res = printall ? _("All indexes") : index->index();
1094 res += " (" + _("non-active") + ")";
1095 else if (contains(getCmdName(), "printsubindex"))
1096 res += " (" + _("subindex") + ")";
1101 bool InsetPrintIndex::isCompatibleCommand(string const & s)
1103 return s == "printindex" || s == "printsubindex"
1104 || s == "printindex*" || s == "printsubindex*";
1108 void InsetPrintIndex::doDispatch(Cursor & cur, FuncRequest & cmd)
1110 switch (cmd.action()) {
1112 case LFUN_INSET_MODIFY: {
1113 if (cmd.argument() == from_ascii("toggle-subindex")) {
1114 string scmd = getCmdName();
1115 if (contains(scmd, "printindex"))
1116 scmd = subst(scmd, "printindex", "printsubindex");
1118 scmd = subst(scmd, "printsubindex", "printindex");
1122 } else if (cmd.argument() == from_ascii("check-printindex*")) {
1123 string scmd = getCmdName();
1124 if (suffixIs(scmd, '*'))
1128 setParam("type", docstring());
1132 InsetCommandParams p(INDEX_PRINT_CODE);
1134 InsetCommand::string2params(to_utf8(cmd.argument()), p);
1135 if (p.getCmdName().empty()) {
1136 cur.noScreenUpdate();
1145 InsetCommand::doDispatch(cur, cmd);
1151 bool InsetPrintIndex::getStatus(Cursor & cur, FuncRequest const & cmd,
1152 FuncStatus & status) const
1154 switch (cmd.action()) {
1156 case LFUN_INSET_MODIFY: {
1157 if (cmd.argument() == from_ascii("toggle-subindex")) {
1158 status.setEnabled(buffer().masterBuffer()->params().use_indices);
1159 status.setOnOff(contains(getCmdName(), "printsubindex"));
1161 } else if (cmd.argument() == from_ascii("check-printindex*")) {
1162 status.setEnabled(buffer().masterBuffer()->params().use_indices);
1163 status.setOnOff(suffixIs(getCmdName(), '*'));
1165 } if (cmd.getArg(0) == "index_print"
1166 && cmd.getArg(1) == "CommandInset") {
1167 InsetCommandParams p(INDEX_PRINT_CODE);
1168 InsetCommand::string2params(to_utf8(cmd.argument()), p);
1169 if (suffixIs(p.getCmdName(), '*')) {
1170 status.setEnabled(true);
1171 status.setOnOff(false);
1174 Buffer const & realbuffer = *buffer().masterBuffer();
1175 IndicesList const & indiceslist =
1176 realbuffer.params().indiceslist();
1177 Index const * index = indiceslist.findShortcut(p["type"]);
1178 status.setEnabled(index != 0);
1179 status.setOnOff(p["type"] == getParam("type"));
1182 return InsetCommand::getStatus(cur, cmd, status);
1185 case LFUN_INSET_DIALOG_UPDATE: {
1186 status.setEnabled(buffer().masterBuffer()->params().use_indices);
1191 return InsetCommand::getStatus(cur, cmd, status);
1196 void InsetPrintIndex::updateBuffer(ParIterator const &, UpdateType, bool const /*deleted*/)
1198 Index const * index =
1199 buffer().masterParams().indiceslist().findShortcut(getParam("type"));
1201 setParam("name", index->index());
1205 void InsetPrintIndex::latex(otexstream & os, OutputParams const & runparams_in) const
1207 if (!buffer().masterBuffer()->params().use_indices) {
1208 if (getParam("type") == from_ascii("idx"))
1209 os << "\\printindex" << termcmd;
1212 OutputParams runparams = runparams_in;
1213 os << getCommand(runparams);
1217 void InsetPrintIndex::validate(LaTeXFeatures & features) const
1219 features.require("makeidx");
1220 if (buffer().masterBuffer()->params().use_indices)
1221 features.require("splitidx");
1222 InsetCommand::validate(features);
1226 string InsetPrintIndex::contextMenuName() const
1228 return buffer().masterBuffer()->params().use_indices ?
1229 "context-indexprint" : string();
1233 bool InsetPrintIndex::hasSettings() const
1235 return buffer().masterBuffer()->params().use_indices;
1242 IndexEntry() = default;
1244 IndexEntry(docstring const & s, DocIterator const & d, bool for_output = false)
1247 extractSubentries(s);
1248 parseItem(main_, for_output);
1249 parseItem(sub_, for_output);
1250 parseItem(subsub_, for_output);
1253 bool equal(IndexEntry const & rhs) const
1255 return main_ == rhs.main_ && sub_ == rhs.sub_ && subsub_ == rhs.subsub_;
1258 bool same_sub(IndexEntry const & rhs) const
1260 return main_ == rhs.main_ && sub_ == rhs.sub_;
1263 bool same_main(IndexEntry const & rhs) const
1265 return main_ == rhs.main_;
1268 const Paragraph & innerParagraph() const
1270 return dit_.innerParagraph();
1273 const docstring & main() const
1278 const docstring & sub() const
1283 const docstring & subsub() const
1288 const DocIterator & dit() const
1295 void parseItem(docstring & s, bool for_output)
1297 // this does not yet check for escaped things
1298 size_type loc = s.find(from_ascii("@"));
1299 if (loc != string::npos) {
1301 s.erase(0, loc + 1);
1305 loc = s.find(from_ascii("|"));
1306 if (loc != string::npos)
1310 void extractSubentries(docstring const & entry)
1314 size_type const loc = entry.find(from_ascii(" ! "));
1315 if (loc == string::npos)
1318 main_ = trim(entry.substr(0, loc));
1319 size_t const locend = loc + 3;
1320 size_type const loc2 = entry.find(from_ascii(" ! "), locend);
1321 if (loc2 == string::npos) {
1322 sub_ = trim(entry.substr(locend));
1324 sub_ = trim(entry.substr(locend, loc2 - locend));
1325 subsub_ = trim(entry.substr(loc2 + 3));
1336 friend bool operator<(IndexEntry const & lhs, IndexEntry const & rhs);
1339 bool operator<(IndexEntry const & lhs, IndexEntry const & rhs)
1341 int comp = compare_no_case(lhs.main_, rhs.main_);
1343 comp = compare_no_case(lhs.sub_, rhs.sub_);
1345 comp = compare_no_case(lhs.subsub_, rhs.subsub_);
1352 docstring InsetPrintIndex::xhtml(XMLStream &, OutputParams const & op) const
1354 BufferParams const & bp = buffer().masterBuffer()->params();
1356 // we do not presently support multiple indices, so we refuse to print
1357 // anything but the main index, so as not to generate multiple indices.
1358 // NOTE Multiple index support would require some work. The reason
1359 // is that the TOC does not know about multiple indices. Either it would
1360 // need to be told about them (not a bad idea), or else the index entries
1361 // would need to be collected differently, say, during validation.
1362 if (bp.use_indices && getParam("type") != from_ascii("idx"))
1365 shared_ptr<Toc const> toc = buffer().tocBackend().toc("index");
1369 // Collect the index entries in a form we can use them.
1370 Toc::const_iterator it = toc->begin();
1371 Toc::const_iterator const en = toc->end();
1372 vector<IndexEntry> entries;
1373 for (; it != en; ++it)
1375 entries.push_back(IndexEntry(it->str(), it->dit()));
1377 if (entries.empty())
1378 // not very likely that all the index entries are in notes or
1379 // whatever, but....
1382 stable_sort(entries.begin(), entries.end());
1384 Layout const & lay = bp.documentClass().htmlTOCLayout();
1385 string const & tocclass = lay.defaultCSSClass();
1386 string const tocattr = "class='index " + tocclass + "'";
1388 // we'll use our own stream, because we are going to defer everything.
1389 // that's how we deal with the fact that we're probably inside a standard
1390 // paragraph, and we don't want to be.
1391 odocstringstream ods;
1394 xs << xml::StartTag("div", tocattr);
1395 xs << xml::StartTag(lay.htmltag(), lay.htmlattr())
1396 << translateIfPossible(from_ascii("Index"),
1397 op.local_font->language()->lang())
1398 << xml::EndTag(lay.htmltag());
1399 xs << xml::StartTag("ul", "class='main'");
1402 vector<IndexEntry>::const_iterator eit = entries.begin();
1403 vector<IndexEntry>::const_iterator const een = entries.end();
1404 // tracks whether we are already inside a main entry (1),
1405 // a sub-entry (2), or a sub-sub-entry (3). see below for the
1408 // the last one we saw
1410 int entry_number = -1;
1411 for (; eit != een; ++eit) {
1412 Paragraph const & par = eit->innerParagraph();
1413 if (entry_number == -1 || !eit->equal(last)) {
1414 if (entry_number != -1) {
1415 // not the first time through the loop, so
1416 // close last entry or entries, depending.
1418 // close this sub-sub-entry
1419 xs << xml::EndTag("li") << xml::CR();
1420 // is this another sub-sub-entry within the same sub-entry?
1421 if (!eit->same_sub(last)) {
1423 xs << xml::EndTag("ul") << xml::CR();
1427 // the point of the second test here is that we might get
1428 // here two ways: (i) by falling through from above; (ii) because,
1429 // though the sub-entry hasn't changed, the sub-sub-entry has,
1430 // which means that it is the first sub-sub-entry within this
1431 // sub-entry. In that case, we do not want to close anything.
1432 if (level == 2 && !eit->same_sub(last)) {
1434 xs << xml::EndTag("li") << xml::CR();
1435 // is this another sub-entry with the same main entry?
1436 if (!eit->same_main(last)) {
1438 xs << xml::EndTag("ul") << xml::CR();
1442 // again, we can get here two ways: from above, or because we have
1443 // found the first sub-entry. in the latter case, we do not want to
1445 if (level == 1 && !eit->same_main(last)) {
1447 xs << xml::EndTag("li") << xml::CR();
1451 // we'll be starting new entries
1454 // We need to use our own stream, since we will have to
1455 // modify what we get back.
1456 odocstringstream ent;
1457 XMLStream entstream(ent);
1458 OutputParams ours = op;
1459 ours.for_toc = true;
1460 par.simpleLyXHTMLOnePar(buffer(), entstream, ours, dummy);
1462 // these will contain XHTML versions of the main entry, etc.
1463 // remember that everything will already have been escaped,
1464 // so we'll need to use NextRaw() during output.
1465 IndexEntry xhtml_entry = IndexEntry(ent.str(), eit->dit(), true);
1468 // another subsubentry
1469 xs << xml::StartTag("li", "class='subsubentry'")
1470 << XMLStream::ESCAPE_NONE << xhtml_entry.subsub();
1471 } else if (level == 2) {
1472 // there are two ways we can be here:
1473 // (i) we can actually be inside a sub-entry already and be about
1474 // to output the first sub-sub-entry. in this case, our sub
1475 // and the last sub will be the same.
1476 // (ii) we can just have closed a sub-entry, possibly after also
1477 // closing a list of sub-sub-entries. here our sub and the last
1478 // sub are different.
1479 // only in the latter case do we need to output the new sub-entry.
1480 // note that in this case, too, though, the sub-entry might already
1481 // have a sub-sub-entry.
1482 if (eit->sub() != last.sub())
1483 xs << xml::StartTag("li", "class='subentry'")
1484 << XMLStream::ESCAPE_NONE << xhtml_entry.sub();
1485 if (!xhtml_entry.subsub().empty()) {
1486 // it's actually a subsubentry, so we need to start that list
1488 << xml::StartTag("ul", "class='subsubentry'")
1489 << xml::StartTag("li", "class='subsubentry'")
1490 << XMLStream::ESCAPE_NONE << xhtml_entry.subsub();
1494 // there are also two ways we can be here:
1495 // (i) we can actually be inside an entry already and be about
1496 // to output the first sub-entry. in this case, our main
1497 // and the last main will be the same.
1498 // (ii) we can just have closed an entry, possibly after also
1499 // closing a list of sub-entries. here our main and the last
1500 // main are different.
1501 // only in the latter case do we need to output the new main entry.
1502 // note that in this case, too, though, the main entry might already
1503 // have a sub-entry, or even a sub-sub-entry.
1504 if (eit->main() != last.main())
1505 xs << xml::StartTag("li", "class='main'") << xhtml_entry.main();
1506 if (!xhtml_entry.sub().empty()) {
1507 // there's a sub-entry, too
1509 << xml::StartTag("ul", "class='subentry'")
1510 << xml::StartTag("li", "class='subentry'")
1511 << XMLStream::ESCAPE_NONE << xhtml_entry.sub();
1513 if (!xhtml_entry.subsub().empty()) {
1514 // and a sub-sub-entry
1516 << xml::StartTag("ul", "class='subsubentry'")
1517 << xml::StartTag("li", "class='subsubentry'")
1518 << XMLStream::ESCAPE_NONE << xhtml_entry.subsub();
1524 // finally, then, we can output the index link itself
1525 string const parattr = "href='#" + par.magicLabel() + "'";
1526 xs << (entry_number == 0 ? ":" : ",");
1527 xs << " " << xml::StartTag("a", parattr)
1528 << ++entry_number << xml::EndTag("a");
1531 // now we have to close all the open levels
1533 xs << xml::EndTag("li") << xml::EndTag("ul") << xml::CR();
1536 xs << xml::EndTag("div") << xml::CR();