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 // Get the content of the inset as LaTeX, as some things may be encoded as ERT (like {}).
311 // TODO: if there is an ERT within the index term, its conversion should be tried, in case it becomes useful;
312 // otherwise, ERTs should become comments. For now, they are just copied as-is, which is barely satisfactory.
313 odocstringstream odss;
314 otexstream ots(odss);
315 InsetText::latex(ots, runparams);
316 docstring latexString = trim(odss.str());
318 // Check whether there are unsupported things. @ is supported, but only for sorting, without specific formatting.
319 if (latexString.find(from_utf8("@\\")) != lyx::docstring::npos) {
320 docstring error = from_utf8("Unsupported feature: an index entry contains an @\\. "
321 "Complete entry: \"") + latexString + from_utf8("\"");
323 xs << XMLStream::ESCAPE_NONE << (from_utf8("<!-- Output Error: ") + error + from_utf8(" -->\n"));
326 // Handle several indices (indicated in the inset instead of the raw latexString).
327 docstring indexType = from_utf8("");
328 if (buffer().masterBuffer()->params().use_indices) {
329 indexType += " type=\"" + params_.index + "\"";
332 // Split the string into its main constituents: terms, and command (see, see also, range).
333 size_t positionVerticalBar = latexString.find(from_ascii("|")); // What comes before | is (sub)(sub)entries.
334 docstring indexTerms = latexString.substr(0, positionVerticalBar);
336 if (positionVerticalBar != lyx::docstring::npos) {
337 command = latexString.substr(positionVerticalBar + 1);
340 // Handle sorting issues, with @.
341 vector<docstring> sortingElements = getVectorFromString(indexTerms, from_ascii("@"), false);
343 if (sortingElements.size() == 2) {
344 sortAs = sortingElements[0];
345 indexTerms = sortingElements[1];
348 // Handle primary, secondary, and tertiary terms (entries, subentries, and subsubentries, for LaTeX).
349 vector<docstring> terms = getVectorFromString(indexTerms, from_ascii("!"), false);
351 // Handle ranges. Happily, (| and |) can only be at the end of the string!
352 bool hasStartRange = latexString.find(from_ascii("|(")) != lyx::docstring::npos;
353 bool hasEndRange = latexString.find(from_ascii("|)")) != lyx::docstring::npos;
354 if (hasStartRange || hasEndRange) {
355 // Remove the ranges from the command if they do not appear at the beginning.
357 while ((index = command.find(from_utf8("|("), index)) != std::string::npos)
358 command.erase(index, 1);
360 while ((index = command.find(from_utf8("|)"), index)) != std::string::npos)
361 command.erase(index, 1);
363 // Remove the ranges when they are the only vertical bar in the complete string.
364 if (command[0] == '(' || command[0] == ')')
368 // Handle see and seealso. As "see" is a prefix of "seealso", the order of the comparisons is important.
369 // Both commands are mutually exclusive!
370 docstring see = from_utf8("");
371 vector<docstring> seeAlsoes;
372 if (command.substr(0, 3) == "see") {
373 // Unescape brackets.
375 while ((index = command.find(from_utf8("\\{"), index)) != std::string::npos)
376 command.erase(index, 1);
378 while ((index = command.find(from_utf8("\\}"), index)) != std::string::npos)
379 command.erase(index, 1);
381 // Retrieve the part between brackets, and remove the complete seealso.
382 size_t positionOpeningBracket = command.find(from_ascii("{"));
383 size_t positionClosingBracket = command.find(from_ascii("}"));
384 docstring list = command.substr(positionOpeningBracket + 1, positionClosingBracket - positionOpeningBracket - 1);
386 // Parse the list of referenced entries (or a single one for see).
387 if (command.substr(0, 7) == "seealso") {
388 seeAlsoes = getVectorFromString(list, from_ascii(","), false);
392 if (see.find(from_ascii(",")) != std::string::npos) {
393 docstring error = from_utf8("Several index terms found as \"see\"! Only one is acceptable. "
394 "Complete entry: \"") + latexString + from_utf8("\"");
396 xs << XMLStream::ESCAPE_NONE << (from_utf8("<!-- Output Error: ") + error + from_utf8(" -->\n"));
400 // Remove the complete see/seealso from the commands, in case there is something else to parse.
401 command = command.substr(positionClosingBracket + 1);
404 // Some parts of the strings are not parsed, as they do not have anything matching in DocBook: things like
405 // formatting the entry or the page number, other strings for sorting. https://wiki.lyx.org/Tips/Indexing
406 // If there are such things in the index entry, then this code may miserably fail. For example, for "Peter|(textbf",
407 // no range will be detected.
408 // TODO: Could handle formatting as significance="preferred"?
409 if (!command.empty()) {
410 docstring error = from_utf8("Unsupported feature: an index entry contains a | with an unsupported command, ")
411 + command + from_utf8(". ") + from_utf8("Complete entry: \"") + latexString + from_utf8("\"");
413 xs << XMLStream::ESCAPE_NONE << (from_utf8("<!-- Output Error: ") + error + from_utf8(" -->\n"));
416 // Write all of this down.
417 if (terms.empty() && !hasEndRange) {
418 docstring error = from_utf8("No index term found! Complete entry: \"") + latexString + from_utf8("\"");
420 xs << XMLStream::ESCAPE_NONE << (from_utf8("<!-- Output Error: ") + error + from_utf8(" -->\n"));
422 // Generate the attributes for ranges. It is based on the terms that are indexed, but the ID must be unique
423 // to this indexing area (xml::cleanID does not guarantee this: for each call with the same arguments,
424 // the same legal ID is produced; here, as the input would be the same, the output must be, by design).
425 // Hence the thread-local storage, as the numbers must strictly be unique, and thus cannot be shared across
426 // a paragraph (making the solution used for HTML worthless). This solution is very similar to the one used in
428 // indexType can only be used for singular and startofrange types!
430 if (!hasStartRange && !hasEndRange) {
433 // Append an ID if uniqueness is not guaranteed across the document.
434 static QThreadStorage<set<docstring>> tKnownTermLists;
435 static QThreadStorage<int> tID;
437 set<docstring> &knownTermLists = tKnownTermLists.localData();
438 int &ID = tID.localData();
440 if (!tID.hasLocalData()) {
444 // Modify the index terms to add the unique ID if needed.
445 docstring newIndexTerms = indexTerms;
446 if (knownTermLists.find(indexTerms) != knownTermLists.end()) {
447 newIndexTerms += from_ascii(string("-") + to_string(ID));
449 // Only increment for the end of range, so that the same number is used for the start of range.
455 // Term list not yet known: add it to the set AFTER the end of range. After
456 if (knownTermLists.find(indexTerms) == knownTermLists.end() && hasEndRange) {
457 knownTermLists.insert(indexTerms);
460 // Generate the attributes.
461 docstring id = xml::cleanID(newIndexTerms);
463 attrs = indexType + " class=\"startofrange\" xml:id=\"" + id + "\"";
465 attrs = " class=\"endofrange\" startref=\"" + id + "\"";
469 // Handle the index terms (including the specific index for this entry).
471 xs << xml::CompTag("indexterm", attrs);
473 xs << xml::StartTag("indexterm", attrs);
474 if (!terms.empty()) { // hasEndRange has no content.
476 if (!sortAs.empty()) {
477 attr = from_utf8("sortas='") + sortAs + from_utf8("'");
480 xs << xml::StartTag("primary", attr);
482 xs << xml::EndTag("primary");
484 if (terms.size() > 1) {
485 xs << xml::StartTag("secondary");
487 xs << xml::EndTag("secondary");
489 if (terms.size() > 2) {
490 xs << xml::StartTag("tertiary");
492 xs << xml::EndTag("tertiary");
495 // Handle see and see also.
497 xs << xml::StartTag("see");
499 xs << xml::EndTag("see");
502 if (!seeAlsoes.empty()) {
503 for (auto &entry : seeAlsoes) {
504 xs << xml::StartTag("seealso");
506 xs << xml::EndTag("seealso");
511 xs << xml::EndTag("indexterm");
517 docstring InsetIndex::xhtml(XMLStream & xs, OutputParams const &) const
519 // we just print an anchor, taking the paragraph ID from
520 // our own interior paragraph, which doesn't get printed
521 std::string const magic = paragraphs().front().magicLabel();
522 std::string const attr = "id='" + magic + "'";
523 xs << xml::CompTag("a", attr);
528 bool InsetIndex::showInsetDialog(BufferView * bv) const
530 bv->showDialog("index", params2string(params_),
531 const_cast<InsetIndex *>(this));
536 void InsetIndex::doDispatch(Cursor & cur, FuncRequest & cmd)
538 switch (cmd.action()) {
540 case LFUN_INSET_MODIFY: {
541 if (cmd.getArg(0) == "changetype") {
542 cur.recordUndoInset(this);
543 params_.index = from_utf8(cmd.getArg(1));
546 InsetIndexParams params;
547 InsetIndex::string2params(to_utf8(cmd.argument()), params);
548 cur.recordUndoInset(this);
549 params_.index = params.index;
550 params_.range = params.range;
551 params_.pagefmt = params.pagefmt;
552 // what we really want here is a TOC update, but that means
553 // a full buffer update
554 cur.forceBufferUpdate();
558 case LFUN_INSET_DIALOG_UPDATE:
559 cur.bv().updateDialog("index", params2string(params_));
563 InsetCollapsible::doDispatch(cur, cmd);
569 bool InsetIndex::getStatus(Cursor & cur, FuncRequest const & cmd,
570 FuncStatus & flag) const
572 switch (cmd.action()) {
574 case LFUN_INSET_MODIFY:
575 if (cmd.getArg(0) == "changetype") {
576 docstring const newtype = from_utf8(cmd.getArg(1));
577 Buffer const & realbuffer = *buffer().masterBuffer();
578 IndicesList const & indiceslist = realbuffer.params().indiceslist();
579 Index const * index = indiceslist.findShortcut(newtype);
580 flag.setEnabled(index != 0);
582 from_utf8(cmd.getArg(1)) == params_.index);
585 return InsetCollapsible::getStatus(cur, cmd, flag);
587 case LFUN_INSET_DIALOG_UPDATE: {
588 Buffer const & realbuffer = *buffer().masterBuffer();
589 flag.setEnabled(realbuffer.params().use_indices);
593 case LFUN_INDEXMACRO_INSERT:
594 return macrosPossible(cmd.getArg(0));
597 return InsetCollapsible::getStatus(cur, cmd, flag);
602 void InsetIndex::getSortkey(otexstream & os, OutputParams const & runparams) const
604 Paragraph const & par = paragraphs().front();
605 InsetList::const_iterator it = par.insetList().begin();
606 for (; it != par.insetList().end(); ++it) {
607 Inset & inset = *it->inset;
608 if (inset.lyxCode() == INDEXMACRO_SORTKEY_CODE) {
609 InsetIndexMacro const & iim =
610 static_cast<InsetIndexMacro const &>(inset);
611 iim.getLatex(os, runparams);
618 void InsetIndex::getSubentries(otexstream & os, OutputParams const & runparams) const
620 Paragraph const & par = paragraphs().front();
621 InsetList::const_iterator it = par.insetList().begin();
623 for (; it != par.insetList().end(); ++it) {
624 Inset & inset = *it->inset;
625 if (inset.lyxCode() == INDEXMACRO_CODE) {
626 InsetIndexMacro const & iim =
627 static_cast<InsetIndexMacro const &>(inset);
628 if (iim.params().type == InsetIndexMacroParams::Subindex) {
633 iim.getLatex(os, runparams);
640 void InsetIndex::getSeeRefs(otexstream & os, OutputParams const & runparams) const
642 Paragraph const & par = paragraphs().front();
643 InsetList::const_iterator it = par.insetList().begin();
644 for (; it != par.insetList().end(); ++it) {
645 Inset & inset = *it->inset;
646 if (inset.lyxCode() == INDEXMACRO_CODE) {
647 InsetIndexMacro const & iim =
648 static_cast<InsetIndexMacro const &>(inset);
649 if (iim.params().type == InsetIndexMacroParams::See
650 || iim.params().type == InsetIndexMacroParams::Seealso) {
651 iim.getLatex(os, runparams);
659 bool InsetIndex::hasSeeRef() const
661 Paragraph const & par = paragraphs().front();
662 InsetList::const_iterator it = par.insetList().begin();
663 for (; it != par.insetList().end(); ++it) {
664 Inset & inset = *it->inset;
665 if (inset.lyxCode() == INDEXMACRO_CODE) {
666 InsetIndexMacro const & iim =
667 static_cast<InsetIndexMacro const &>(inset);
668 if (iim.params().type == InsetIndexMacroParams::See
669 || iim.params().type == InsetIndexMacroParams::Seealso)
677 bool InsetIndex::hasSortKey() const
679 Paragraph const & par = paragraphs().front();
680 InsetList::const_iterator it = par.insetList().begin();
681 for (; it != par.insetList().end(); ++it) {
682 Inset & inset = *it->inset;
683 if (inset.lyxCode() == INDEXMACRO_SORTKEY_CODE)
690 bool InsetIndex::macrosPossible(string const type) const
692 if (type != "see" && type != "seealso"
693 && type != "sortkey" && type != "subindex")
696 Paragraph const & par = paragraphs().front();
697 InsetList::const_iterator it = par.insetList().begin();
699 for (; it != par.insetList().end(); ++it) {
700 Inset & inset = *it->inset;
701 if (type == "sortkey" && inset.lyxCode() == INDEXMACRO_SORTKEY_CODE)
703 if (inset.lyxCode() == INDEXMACRO_CODE) {
704 InsetIndexMacro const & iim = static_cast<InsetIndexMacro const &>(inset);
705 if ((type == "see" || type == "seealso")
706 && (iim.params().type == InsetIndexMacroParams::See
707 || iim.params().type == InsetIndexMacroParams::Seealso))
709 if (type == "subindex"
710 && iim.params().type == InsetIndexMacroParams::Subindex) {
721 ColorCode InsetIndex::labelColor() const
723 if (params_.index.empty() || params_.index == from_ascii("idx"))
724 return InsetCollapsible::labelColor();
726 ColorCode c = lcolor.getFromLyXName(to_utf8(params_.index)
727 + "@" + buffer().fileName().absFileName());
729 c = InsetCollapsible::labelColor();
734 docstring InsetIndex::toolTip(BufferView const &, int, int) const
736 docstring tip = _("Index Entry");
737 if (buffer().params().use_indices && !params_.index.empty()) {
738 Buffer const & realbuffer = *buffer().masterBuffer();
739 IndicesList const & indiceslist = realbuffer.params().indiceslist();
741 Index const * index = indiceslist.findShortcut(params_.index);
743 tip += _("unknown type!");
745 tip += index->index();
749 docstring res = toolTipText(tip);
750 if (!insetindexpagerangetranslator_loc().find(params_.range).empty())
751 res += "\n" + insetindexpagerangetranslator_loc().find(params_.range);
752 if (!params_.pagefmt.empty() && params_.pagefmt != "default") {
753 res += "\n" + _("Pagination format:") + " ";
754 if (params_.pagefmt == "textbf")
756 else if (params_.pagefmt == "textit")
758 else if (params_.pagefmt == "emph")
759 res += _("emphasized");
761 res += from_utf8(params_.pagefmt);
767 docstring const InsetIndex::buttonLabel(BufferView const & bv) const
769 InsetLayout const & il = getLayout();
770 docstring label = translateIfPossible(il.labelstring());
772 if (buffer().params().use_indices && !params_.index.empty()) {
773 Buffer const & realbuffer = *buffer().masterBuffer();
774 IndicesList const & indiceslist = realbuffer.params().indiceslist();
776 Index const * index = indiceslist.findShortcut(params_.index);
778 label += _("unknown type!");
780 label += index->index();
785 if (!il.contentaslabel() || geometry(bv) != ButtonOnly)
788 res = getNewLabel(label);
789 if (!insetindexpagerangetranslator_latex().find(params_.range).empty())
790 res += " " + from_ascii(insetindexpagerangetranslator_latex().find(params_.range));
795 void InsetIndex::write(ostream & os) const
797 os << to_utf8(layoutName());
799 InsetCollapsible::write(os);
803 void InsetIndex::read(Lexer & lex)
806 InsetCollapsible::read(lex);
810 string InsetIndex::params2string(InsetIndexParams const & params)
819 void InsetIndex::string2params(string const & in, InsetIndexParams & params)
821 params = InsetIndexParams();
825 istringstream data(in);
828 lex.setContext("InsetIndex::string2params");
834 void InsetIndex::addToToc(DocIterator const & cpit, bool output_active,
835 UpdateType utype, TocBackend & backend) const
837 DocIterator pit = cpit;
838 pit.push_back(CursorSlice(const_cast<InsetIndex &>(*this)));
840 string type = "index";
841 if (buffer().masterBuffer()->params().use_indices)
842 type += ":" + to_utf8(params_.index);
843 // this is unlikely to be terribly long
844 text().forOutliner(str, INT_MAX);
845 TocBuilder & b = backend.builder(type);
846 b.pushItem(pit, str, output_active);
847 // Proceed with the rest of the inset.
848 InsetCollapsible::addToToc(cpit, output_active, utype, backend);
853 void InsetIndex::validate(LaTeXFeatures & features) const
855 if (buffer().masterBuffer()->params().use_indices
856 && !params_.index.empty()
857 && params_.index != "idx")
858 features.require("splitidx");
859 InsetCollapsible::validate(features);
863 string InsetIndex::contextMenuName() const
865 return "context-index";
869 string InsetIndex::contextMenu(BufferView const & bv, int x, int y) const
871 // We override the implementation of InsetCollapsible,
872 // because we have eytra entries.
873 string owncm = "context-edit-index;";
874 return owncm + InsetCollapsible::contextMenu(bv, x, y);
878 bool InsetIndex::hasSettings() const
884 bool InsetIndex::insetAllowed(InsetCode code) const
887 case INDEXMACRO_CODE:
888 case INDEXMACRO_SORTKEY_CODE:
893 return InsetCollapsible::insetAllowed(code);
898 /////////////////////////////////////////////////////////////////////
902 ///////////////////////////////////////////////////////////////////////
905 void InsetIndexParams::write(ostream & os) const
909 os << to_utf8(index);
914 << insetindexpagerangetranslator().find(range)
922 void InsetIndexParams::read(Lexer & lex)
925 index = lex.getDocString();
927 index = from_ascii("idx");
928 if (lex.checkFor("range")) {
929 string st = lex.getString();
931 st = lex.getString();
932 range = insetindexpagerangetranslator().find(lex.getString());
935 if (lex.checkFor("pageformat") && lex.eatLine()) {
936 pagefmt = lex.getString();
941 /////////////////////////////////////////////////////////////////////
945 ///////////////////////////////////////////////////////////////////////
947 InsetPrintIndex::InsetPrintIndex(Buffer * buf, InsetCommandParams const & p)
948 : InsetCommand(buf, p)
952 ParamInfo const & InsetPrintIndex::findInfo(string const & /* cmdName */)
954 static ParamInfo param_info_;
955 if (param_info_.empty()) {
956 param_info_.add("type", ParamInfo::LATEX_OPTIONAL,
957 ParamInfo::HANDLING_ESCAPE);
958 param_info_.add("name", ParamInfo::LATEX_OPTIONAL,
959 ParamInfo::HANDLING_LATEXIFY);
960 param_info_.add("literal", ParamInfo::LYX_INTERNAL);
966 docstring InsetPrintIndex::screenLabel() const
968 bool const printall = suffixIs(getCmdName(), '*');
969 bool const multind = buffer().masterBuffer()->params().use_indices;
971 && getParam("type") == from_ascii("idx"))
972 || (getParam("type").empty() && !printall))
974 Buffer const & realbuffer = *buffer().masterBuffer();
975 IndicesList const & indiceslist = realbuffer.params().indiceslist();
976 Index const * index = indiceslist.findShortcut(getParam("type"));
977 if (!index && !printall)
978 return _("Unknown index type!");
979 docstring res = printall ? _("All indexes") : index->index();
981 res += " (" + _("non-active") + ")";
982 else if (contains(getCmdName(), "printsubindex"))
983 res += " (" + _("subindex") + ")";
988 bool InsetPrintIndex::isCompatibleCommand(string const & s)
990 return s == "printindex" || s == "printsubindex"
991 || s == "printindex*" || s == "printsubindex*";
995 void InsetPrintIndex::doDispatch(Cursor & cur, FuncRequest & cmd)
997 switch (cmd.action()) {
999 case LFUN_INSET_MODIFY: {
1000 if (cmd.argument() == from_ascii("toggle-subindex")) {
1001 string scmd = getCmdName();
1002 if (contains(scmd, "printindex"))
1003 scmd = subst(scmd, "printindex", "printsubindex");
1005 scmd = subst(scmd, "printsubindex", "printindex");
1009 } else if (cmd.argument() == from_ascii("check-printindex*")) {
1010 string scmd = getCmdName();
1011 if (suffixIs(scmd, '*'))
1015 setParam("type", docstring());
1019 InsetCommandParams p(INDEX_PRINT_CODE);
1021 InsetCommand::string2params(to_utf8(cmd.argument()), p);
1022 if (p.getCmdName().empty()) {
1023 cur.noScreenUpdate();
1032 InsetCommand::doDispatch(cur, cmd);
1038 bool InsetPrintIndex::getStatus(Cursor & cur, FuncRequest const & cmd,
1039 FuncStatus & status) const
1041 switch (cmd.action()) {
1043 case LFUN_INSET_MODIFY: {
1044 if (cmd.argument() == from_ascii("toggle-subindex")) {
1045 status.setEnabled(buffer().masterBuffer()->params().use_indices);
1046 status.setOnOff(contains(getCmdName(), "printsubindex"));
1048 } else if (cmd.argument() == from_ascii("check-printindex*")) {
1049 status.setEnabled(buffer().masterBuffer()->params().use_indices);
1050 status.setOnOff(suffixIs(getCmdName(), '*'));
1052 } if (cmd.getArg(0) == "index_print"
1053 && cmd.getArg(1) == "CommandInset") {
1054 InsetCommandParams p(INDEX_PRINT_CODE);
1055 InsetCommand::string2params(to_utf8(cmd.argument()), p);
1056 if (suffixIs(p.getCmdName(), '*')) {
1057 status.setEnabled(true);
1058 status.setOnOff(false);
1061 Buffer const & realbuffer = *buffer().masterBuffer();
1062 IndicesList const & indiceslist =
1063 realbuffer.params().indiceslist();
1064 Index const * index = indiceslist.findShortcut(p["type"]);
1065 status.setEnabled(index != 0);
1066 status.setOnOff(p["type"] == getParam("type"));
1069 return InsetCommand::getStatus(cur, cmd, status);
1072 case LFUN_INSET_DIALOG_UPDATE: {
1073 status.setEnabled(buffer().masterBuffer()->params().use_indices);
1078 return InsetCommand::getStatus(cur, cmd, status);
1083 void InsetPrintIndex::updateBuffer(ParIterator const &, UpdateType, bool const /*deleted*/)
1085 Index const * index =
1086 buffer().masterParams().indiceslist().findShortcut(getParam("type"));
1088 setParam("name", index->index());
1092 void InsetPrintIndex::latex(otexstream & os, OutputParams const & runparams_in) const
1094 if (!buffer().masterBuffer()->params().use_indices) {
1095 if (getParam("type") == from_ascii("idx"))
1096 os << "\\printindex" << termcmd;
1099 OutputParams runparams = runparams_in;
1100 os << getCommand(runparams);
1104 void InsetPrintIndex::validate(LaTeXFeatures & features) const
1106 features.require("makeidx");
1107 if (buffer().masterBuffer()->params().use_indices)
1108 features.require("splitidx");
1109 InsetCommand::validate(features);
1113 string InsetPrintIndex::contextMenuName() const
1115 return buffer().masterBuffer()->params().use_indices ?
1116 "context-indexprint" : string();
1120 bool InsetPrintIndex::hasSettings() const
1122 return buffer().masterBuffer()->params().use_indices;
1128 void parseItem(docstring & s, bool for_output)
1130 // this does not yet check for escaped things
1131 size_type loc = s.find(from_ascii("@"));
1132 if (loc != string::npos) {
1134 s.erase(0, loc + 1);
1138 loc = s.find(from_ascii("|"));
1139 if (loc != string::npos)
1144 void extractSubentries(docstring const & entry, docstring & main,
1145 docstring & sub1, docstring & sub2)
1149 size_type const loc = entry.find(from_ascii(" ! "));
1150 if (loc == string::npos)
1153 main = trim(entry.substr(0, loc));
1154 size_t const locend = loc + 3;
1155 size_type const loc2 = entry.find(from_ascii(" ! "), locend);
1156 if (loc2 == string::npos) {
1157 sub1 = trim(entry.substr(locend));
1159 sub1 = trim(entry.substr(locend, loc2 - locend));
1160 sub2 = trim(entry.substr(loc2 + 3));
1171 IndexEntry(docstring const & s, DocIterator const & d)
1174 extractSubentries(s, main, sub, subsub);
1175 parseItem(main, false);
1176 parseItem(sub, false);
1177 parseItem(subsub, false);
1180 bool equal(IndexEntry const & rhs) const
1182 return main == rhs.main && sub == rhs.sub && subsub == rhs.subsub;
1185 bool same_sub(IndexEntry const & rhs) const
1187 return main == rhs.main && sub == rhs.sub;
1190 bool same_main(IndexEntry const & rhs) const
1192 return main == rhs.main;
1201 bool operator<(IndexEntry const & lhs, IndexEntry const & rhs)
1203 int comp = compare_no_case(lhs.main, rhs.main);
1205 comp = compare_no_case(lhs.sub, rhs.sub);
1207 comp = compare_no_case(lhs.subsub, rhs.subsub);
1214 docstring InsetPrintIndex::xhtml(XMLStream &, OutputParams const & op) const
1216 BufferParams const & bp = buffer().masterBuffer()->params();
1218 // we do not presently support multiple indices, so we refuse to print
1219 // anything but the main index, so as not to generate multiple indices.
1220 // NOTE Multiple index support would require some work. The reason
1221 // is that the TOC does not know about multiple indices. Either it would
1222 // need to be told about them (not a bad idea), or else the index entries
1223 // would need to be collected differently, say, during validation.
1224 if (bp.use_indices && getParam("type") != from_ascii("idx"))
1227 shared_ptr<Toc const> toc = buffer().tocBackend().toc("index");
1231 // Collect the index entries in a form we can use them.
1232 Toc::const_iterator it = toc->begin();
1233 Toc::const_iterator const en = toc->end();
1234 vector<IndexEntry> entries;
1235 for (; it != en; ++it)
1237 entries.push_back(IndexEntry(it->str(), it->dit()));
1239 if (entries.empty())
1240 // not very likely that all the index entries are in notes or
1241 // whatever, but....
1244 stable_sort(entries.begin(), entries.end());
1246 Layout const & lay = bp.documentClass().htmlTOCLayout();
1247 string const & tocclass = lay.defaultCSSClass();
1248 string const tocattr = "class='index " + tocclass + "'";
1250 // we'll use our own stream, because we are going to defer everything.
1251 // that's how we deal with the fact that we're probably inside a standard
1252 // paragraph, and we don't want to be.
1253 odocstringstream ods;
1256 xs << xml::StartTag("div", tocattr);
1257 xs << xml::StartTag(lay.htmltag(), lay.htmlattr())
1258 << translateIfPossible(from_ascii("Index"),
1259 op.local_font->language()->lang())
1260 << xml::EndTag(lay.htmltag());
1261 xs << xml::StartTag("ul", "class='main'");
1264 vector<IndexEntry>::const_iterator eit = entries.begin();
1265 vector<IndexEntry>::const_iterator const een = entries.end();
1266 // tracks whether we are already inside a main entry (1),
1267 // a sub-entry (2), or a sub-sub-entry (3). see below for the
1270 // the last one we saw
1272 int entry_number = -1;
1273 for (; eit != een; ++eit) {
1274 Paragraph const & par = eit->dit.innerParagraph();
1275 if (entry_number == -1 || !eit->equal(last)) {
1276 if (entry_number != -1) {
1277 // not the first time through the loop, so
1278 // close last entry or entries, depending.
1280 // close this sub-sub-entry
1281 xs << xml::EndTag("li") << xml::CR();
1282 // is this another sub-sub-entry within the same sub-entry?
1283 if (!eit->same_sub(last)) {
1285 xs << xml::EndTag("ul") << xml::CR();
1289 // the point of the second test here is that we might get
1290 // here two ways: (i) by falling through from above; (ii) because,
1291 // though the sub-entry hasn't changed, the sub-sub-entry has,
1292 // which means that it is the first sub-sub-entry within this
1293 // sub-entry. In that case, we do not want to close anything.
1294 if (level == 2 && !eit->same_sub(last)) {
1296 xs << xml::EndTag("li") << xml::CR();
1297 // is this another sub-entry with the same main entry?
1298 if (!eit->same_main(last)) {
1300 xs << xml::EndTag("ul") << xml::CR();
1304 // again, we can get here two ways: from above, or because we have
1305 // found the first sub-entry. in the latter case, we do not want to
1307 if (level == 1 && !eit->same_main(last)) {
1309 xs << xml::EndTag("li") << xml::CR();
1313 // we'll be starting new entries
1316 // We need to use our own stream, since we will have to
1317 // modify what we get back.
1318 odocstringstream ent;
1319 XMLStream entstream(ent);
1320 OutputParams ours = op;
1321 ours.for_toc = true;
1322 par.simpleLyXHTMLOnePar(buffer(), entstream, ours, dummy);
1324 // these will contain XHTML versions of the main entry, etc
1325 // remember that everything will already have been escaped,
1326 // so we'll need to use NextRaw() during output.
1330 extractSubentries(ent.str(), main, sub, subsub);
1331 parseItem(main, true);
1332 parseItem(sub, true);
1333 parseItem(subsub, true);
1336 // another subsubentry
1337 xs << xml::StartTag("li", "class='subsubentry'")
1338 << XMLStream::ESCAPE_NONE << subsub;
1339 } else if (level == 2) {
1340 // there are two ways we can be here:
1341 // (i) we can actually be inside a sub-entry already and be about
1342 // to output the first sub-sub-entry. in this case, our sub
1343 // and the last sub will be the same.
1344 // (ii) we can just have closed a sub-entry, possibly after also
1345 // closing a list of sub-sub-entries. here our sub and the last
1346 // sub are different.
1347 // only in the latter case do we need to output the new sub-entry.
1348 // note that in this case, too, though, the sub-entry might already
1349 // have a sub-sub-entry.
1350 if (eit->sub != last.sub)
1351 xs << xml::StartTag("li", "class='subentry'")
1352 << XMLStream::ESCAPE_NONE << sub;
1353 if (!subsub.empty()) {
1354 // it's actually a subsubentry, so we need to start that list
1356 << xml::StartTag("ul", "class='subsubentry'")
1357 << xml::StartTag("li", "class='subsubentry'")
1358 << XMLStream::ESCAPE_NONE << subsub;
1362 // there are also two ways we can be here:
1363 // (i) we can actually be inside an entry already and be about
1364 // to output the first sub-entry. in this case, our main
1365 // and the last main will be the same.
1366 // (ii) we can just have closed an entry, possibly after also
1367 // closing a list of sub-entries. here our main and the last
1368 // main are different.
1369 // only in the latter case do we need to output the new main entry.
1370 // note that in this case, too, though, the main entry might already
1371 // have a sub-entry, or even a sub-sub-entry.
1372 if (eit->main != last.main)
1373 xs << xml::StartTag("li", "class='main'") << main;
1375 // there's a sub-entry, too
1377 << xml::StartTag("ul", "class='subentry'")
1378 << xml::StartTag("li", "class='subentry'")
1379 << XMLStream::ESCAPE_NONE << sub;
1381 if (!subsub.empty()) {
1382 // and a sub-sub-entry
1384 << xml::StartTag("ul", "class='subsubentry'")
1385 << xml::StartTag("li", "class='subsubentry'")
1386 << XMLStream::ESCAPE_NONE << subsub;
1392 // finally, then, we can output the index link itself
1393 string const parattr = "href='#" + par.magicLabel() + "'";
1394 xs << (entry_number == 0 ? ":" : ",");
1395 xs << " " << xml::StartTag("a", parattr)
1396 << ++entry_number << xml::EndTag("a");
1399 // now we have to close all the open levels
1401 xs << xml::EndTag("li") << xml::EndTag("ul") << xml::CR();
1404 xs << xml::EndTag("div") << xml::CR();