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"
16 #include "BufferParams.h"
17 #include "BufferView.h"
20 #include "DispatchResult.h"
22 #include "FuncRequest.h"
23 #include "FuncStatus.h"
24 #include "IndicesList.h"
26 #include "LaTeXFeatures.h"
28 #include "output_latex.h"
29 #include "output_xhtml.h"
31 #include "texstream.h"
32 #include "TextClass.h"
33 #include "TocBackend.h"
35 #include "support/debug.h"
36 #include "support/docstream.h"
37 #include "support/gettext.h"
38 #include "support/lstrings.h"
40 #include "frontends/alert.h"
46 #include <QThreadStorage>
49 using namespace lyx::support;
53 /////////////////////////////////////////////////////////////////////
57 ///////////////////////////////////////////////////////////////////////
60 InsetIndex::InsetIndex(Buffer * buf, InsetIndexParams const & params)
61 : InsetCollapsible(buf), params_(params)
65 void InsetIndex::latex(otexstream & ios, OutputParams const & runparams_in) const
67 OutputParams runparams(runparams_in);
68 runparams.inIndexEntry = true;
72 if (buffer().masterBuffer()->params().use_indices && !params_.index.empty()
73 && params_.index != "idx") {
75 os << escape(params_.index);
82 odocstringstream ourlatex;
83 otexstream ots(ourlatex);
84 InsetText::latex(ots, runparams);
85 if (runparams.for_search) {
86 // No need for special handling, if we are only searching for some patterns
87 os << ourlatex.str() << "}";
90 // get contents of InsetText as LaTeX and plaintext
91 odocstringstream ourplain;
92 InsetText::plaintext(ourplain, runparams);
93 // FIXME: do Tex/Row correspondence (I don't currently understand what is
94 // being generated from latexstr below)
95 docstring latexstr = ourlatex.str();
96 docstring plainstr = ourplain.str();
98 // this will get what follows | if anything does
101 // check for the | separator
102 // FIXME This would go wrong on an escaped "|", but
103 // how far do we want to go here?
104 size_t pos = latexstr.find(from_ascii("|"));
105 if (pos != docstring::npos) {
106 // put the bit after "|" into cmd...
107 cmd = latexstr.substr(pos + 1);
108 // ...and erase that stuff from latexstr
109 latexstr = latexstr.erase(pos);
110 // ...and similarly from plainstr
111 size_t ppos = plainstr.find(from_ascii("|"));
112 if (ppos < plainstr.size())
113 plainstr.erase(ppos);
115 LYXERR0("The `|' separator was not found in the plaintext version!");
118 // Separate the entries and subentries, i.e., split on "!"
119 // FIXME This would do the wrong thing with escaped ! characters
120 std::vector<docstring> const levels =
121 getVectorFromString(latexstr, from_ascii("!"), true);
122 std::vector<docstring> const levels_plain =
123 getVectorFromString(plainstr, from_ascii("!"), true);
125 vector<docstring>::const_iterator it = levels.begin();
126 vector<docstring>::const_iterator end = levels.end();
127 vector<docstring>::const_iterator it2 = levels_plain.begin();
129 for (; it != end; ++it) {
130 // write the separator except the first time
136 // correctly sort macros and formatted strings
137 // if we do find a command, prepend a plain text
138 // version of the content to get sorting right,
139 // e.g. \index{LyX@\LyX}, \index{text@\textbf{text}}
140 // Don't do that if the user entered '@' himself, though.
141 if (contains(*it, '\\') && !contains(*it, '@')) {
142 // Plaintext might return nothing (e.g. for ERTs)
143 docstring const spart =
144 (it2 < levels_plain.end() && !(*it2).empty())
146 // Now we need to validate that all characters in
147 // the sorting part are representable in the current
148 // encoding. If not try the LaTeX macro which might
149 // or might not be a good choice, and issue a warning.
150 pair<docstring, docstring> spart_latexed =
151 runparams.encoding->latexString(spart, runparams.dryrun);
152 if (!spart_latexed.second.empty())
153 LYXERR0("Uncodable character in index entry. Sorting might be wrong!");
154 if (spart != spart_latexed.first && !runparams.dryrun) {
155 // FIXME: warning should be passed to the error dialog
156 frontend::Alert::warning(_("Index sorting failed"),
157 bformat(_("LyX's automatic index sorting algorithm faced\n"
158 "problems with the entry '%1$s'.\n"
159 "Please specify the sorting of this entry manually, as\n"
160 "explained in the User Guide."), spart));
162 // remove remaining \'s for the sorting part
163 docstring const ppart =
164 subst(spart_latexed.first, from_ascii("\\"), docstring());
168 docstring const tpart = *it;
170 if (it2 < levels_plain.end())
173 // write the bit that followed "|"
179 // In macros with moving arguments, such as \section,
180 // we store the index and output it after the macro (#2154)
181 if (runparams_in.postpone_fragile_stuff)
182 runparams_in.post_macro += os.str();
188 void InsetIndex::docbook(XMLStream & xs, OutputParams const & runparams) const
190 // Get the content of the inset as LaTeX, as some things may be encoded as ERT (like {}).
191 odocstringstream odss;
192 otexstream ots(odss);
193 InsetText::latex(ots, runparams);
194 docstring latexString = trim(odss.str());
196 // Check whether there are unsupported things.
197 if (latexString.find(from_utf8("@")) != latexString.npos) {
198 docstring error = from_utf8("Unsupported feature: an index entry contains an @. "
199 "Complete entry: \"") + latexString + from_utf8("\"");
201 xs << XMLStream::ESCAPE_NONE << (from_utf8("<!-- Output Error: ") + error + from_utf8(" -->\n"));
202 // TODO: implement @ using the sortas attribute (on primary, secondary, tertiary).
205 // Handle several indices.
206 docstring indexType = from_utf8("");
207 if (buffer().masterBuffer()->params().use_indices) {
208 indexType += " type=\"" + params_.index + "\"";
211 // Split the string into its main constituents: terms, and command (see, see also, range).
212 size_t positionVerticalBar = latexString.find(from_ascii("|")); // What comes before | is (sub)(sub)entries.
213 docstring indexTerms = latexString.substr(0, positionVerticalBar);
214 docstring command = latexString.substr(positionVerticalBar + 1);
216 // Handle primary, secondary, and tertiary terms (entries, subentries, and subsubentries, for LaTeX).
217 vector<docstring> terms = getVectorFromString(indexTerms, from_ascii("!"), false);
219 // Handle ranges. Happily, (| and |) can only be at the end of the string! However, | may be trapped by the
220 bool hasStartRange = latexString.find(from_ascii("|(")) != latexString.npos;
221 bool hasEndRange = latexString.find(from_ascii("|)")) != latexString.npos;
222 if (hasStartRange || hasEndRange) {
223 // Remove the ranges from the command if they do not appear at the beginning.
225 while ((index = command.find(from_utf8("|("), index)) != std::string::npos)
226 command.erase(index, 1);
228 while ((index = command.find(from_utf8("|)"), index)) != std::string::npos)
229 command.erase(index, 1);
231 // Remove the ranges when they are the only vertical bar in the complete string.
232 if (command[0] == '(' || command[0] == ')')
236 // Handle see and seealso. As "see" is a prefix of "seealso", the order of the comparisons is important.
237 // Both commands are mutually exclusive!
238 docstring see = from_utf8("");
239 vector<docstring> seeAlsoes;
240 if (command.substr(0, 3) == "see") {
241 // Unescape brackets.
243 while ((index = command.find(from_utf8("\\{"), index)) != std::string::npos)
244 command.erase(index, 1);
246 while ((index = command.find(from_utf8("\\}"), index)) != std::string::npos)
247 command.erase(index, 1);
249 // Retrieve the part between brackets, and remove the complete seealso.
250 size_t positionOpeningBracket = command.find(from_ascii("{"));
251 size_t positionClosingBracket = command.find(from_ascii("}"));
252 docstring list = command.substr(positionOpeningBracket + 1, positionClosingBracket - positionOpeningBracket - 1);
254 // Parse the list of referenced entries (or a single one for see).
255 if (command.substr(0, 7) == "seealso") {
256 seeAlsoes = getVectorFromString(list, from_ascii(","), false);
260 if (see.find(from_ascii(",")) != see.npos) {
261 docstring error = from_utf8("Several index terms found as \"see\"! Only one is acceptable. "
262 "Complete entry: \"") + latexString + from_utf8("\"");
264 xs << XMLStream::ESCAPE_NONE << (from_utf8("<!-- Output Error: ") + error + from_utf8(" -->\n"));
268 // Remove the complete see/seealso from the commands, in case there is something else to parse.
269 command = command.substr(positionClosingBracket + 1);
272 // Some parts of the strings are not parsed, as they do not have anything matching in DocBook: things like
273 // formatting the entry or the page number, other strings for sorting. https://wiki.lyx.org/Tips/Indexing
274 // If there are such things in the index entry, then this code may miserably fail. For example, for "Peter|(textbf",
275 // no range will be detected.
276 // TODO: Could handle formatting as significance="preferred"?
278 // Write all of this down.
279 if (terms.empty() && !hasEndRange) {
280 docstring error = from_utf8("No index term found! Complete entry: \"") + latexString + from_utf8("\"");
282 xs << XMLStream::ESCAPE_NONE << (from_utf8("<!-- Output Error: ") + error + from_utf8(" -->\n"));
284 // Generate the attributes for ranges. It is based on the terms that are indexed, but the ID must be unique
285 // to this indexing area (xml::cleanID does not guarantee this: for each call with the same arguments,
286 // the same legal ID is produced; here, as the input would be the same, the output must be, by design).
287 // Hence the thread-local storage, as the numbers must strictly be unique, and thus cannot be shared across
288 // a paragraph (making the solution used for HTML worthless). This solution is very similar to the one used in
290 docstring attrs = indexType;
291 if (hasStartRange || hasEndRange) {
292 // Append an ID if uniqueness is not guaranteed across the document.
293 static QThreadStorage<set<docstring>> tKnownTermLists;
294 static QThreadStorage<int> tID;
296 set<docstring> & knownTermLists = tKnownTermLists.localData();
297 int & ID = tID.localData();
299 if (!tID.hasLocalData()) {
303 // Modify the index terms to add the unique ID if needed.
304 docstring newIndexTerms = indexTerms;
305 if (knownTermLists.find(indexTerms) != knownTermLists.end()) {
306 newIndexTerms += from_ascii(string("-") + to_string(ID));
308 // Only increment for the end of range, so that the same number is used for the start of range.
314 // Term list not yet known: add it to the set AFTER the end of range. After
315 if (knownTermLists.find(indexTerms) == knownTermLists.end() && hasEndRange) {
316 knownTermLists.insert(indexTerms);
319 // Generate the attributes.
320 docstring id = xml::cleanID(newIndexTerms);
322 attrs += " class=\"startofrange\" xml:id=\"" + id + "\"";
324 attrs += " class=\"endofrange\" startref=\"" + id + "\"";
328 // Handle the index terms (including the specific index for this entry).
329 xs << xml::StartTag("indexterm", attrs);
330 if (terms.size() > 0) { // hasEndRange has no content.
331 xs << xml::StartTag("primary");
333 xs << xml::EndTag("primary");
335 if (terms.size() > 1) {
336 xs << xml::StartTag("secondary");
338 xs << xml::EndTag("secondary");
340 if (terms.size() > 2) {
341 xs << xml::StartTag("tertiary");
343 xs << xml::EndTag("tertiary");
346 // Handle see and see also.
348 xs << xml::StartTag("see");
350 xs << xml::EndTag("see");
353 if (!seeAlsoes.empty()) {
354 for (auto & entry : seeAlsoes) {
355 xs << xml::StartTag("seealso");
357 xs << xml::EndTag("seealso");
362 xs << xml::EndTag("indexterm");
367 docstring InsetIndex::xhtml(XMLStream & xs, OutputParams const &) const
369 // we just print an anchor, taking the paragraph ID from
370 // our own interior paragraph, which doesn't get printed
371 std::string const magic = paragraphs().front().magicLabel();
372 std::string const attr = "id='" + magic + "'";
373 xs << xml::CompTag("a", attr);
378 bool InsetIndex::showInsetDialog(BufferView * bv) const
380 bv->showDialog("index", params2string(params_),
381 const_cast<InsetIndex *>(this));
386 void InsetIndex::doDispatch(Cursor & cur, FuncRequest & cmd)
388 switch (cmd.action()) {
390 case LFUN_INSET_MODIFY: {
391 if (cmd.getArg(0) == "changetype") {
392 cur.recordUndoInset(this);
393 params_.index = from_utf8(cmd.getArg(1));
396 InsetIndexParams params;
397 InsetIndex::string2params(to_utf8(cmd.argument()), params);
398 cur.recordUndoInset(this);
399 params_.index = params.index;
400 // what we really want here is a TOC update, but that means
401 // a full buffer update
402 cur.forceBufferUpdate();
406 case LFUN_INSET_DIALOG_UPDATE:
407 cur.bv().updateDialog("index", params2string(params_));
411 InsetCollapsible::doDispatch(cur, cmd);
417 bool InsetIndex::getStatus(Cursor & cur, FuncRequest const & cmd,
418 FuncStatus & flag) const
420 switch (cmd.action()) {
422 case LFUN_INSET_MODIFY:
423 if (cmd.getArg(0) == "changetype") {
424 docstring const newtype = from_utf8(cmd.getArg(1));
425 Buffer const & realbuffer = *buffer().masterBuffer();
426 IndicesList const & indiceslist = realbuffer.params().indiceslist();
427 Index const * index = indiceslist.findShortcut(newtype);
428 flag.setEnabled(index != 0);
430 from_utf8(cmd.getArg(1)) == params_.index);
433 return InsetCollapsible::getStatus(cur, cmd, flag);
435 case LFUN_INSET_DIALOG_UPDATE: {
436 Buffer const & realbuffer = *buffer().masterBuffer();
437 flag.setEnabled(realbuffer.params().use_indices);
442 return InsetCollapsible::getStatus(cur, cmd, flag);
447 ColorCode InsetIndex::labelColor() const
449 if (params_.index.empty() || params_.index == from_ascii("idx"))
450 return InsetCollapsible::labelColor();
452 ColorCode c = lcolor.getFromLyXName(to_utf8(params_.index));
454 c = InsetCollapsible::labelColor();
459 docstring InsetIndex::toolTip(BufferView const &, int, int) const
461 docstring tip = _("Index Entry");
462 if (buffer().params().use_indices && !params_.index.empty()) {
463 Buffer const & realbuffer = *buffer().masterBuffer();
464 IndicesList const & indiceslist = realbuffer.params().indiceslist();
466 Index const * index = indiceslist.findShortcut(params_.index);
468 tip += _("unknown type!");
470 tip += index->index();
474 return toolTipText(tip);
478 docstring const InsetIndex::buttonLabel(BufferView const & bv) const
480 InsetLayout const & il = getLayout();
481 docstring label = translateIfPossible(il.labelstring());
483 if (buffer().params().use_indices && !params_.index.empty()) {
484 Buffer const & realbuffer = *buffer().masterBuffer();
485 IndicesList const & indiceslist = realbuffer.params().indiceslist();
487 Index const * index = indiceslist.findShortcut(params_.index);
489 label += _("unknown type!");
491 label += index->index();
495 if (!il.contentaslabel() || geometry(bv) != ButtonOnly)
497 return getNewLabel(label);
501 void InsetIndex::write(ostream & os) const
503 os << to_utf8(layoutName());
505 InsetCollapsible::write(os);
509 void InsetIndex::read(Lexer & lex)
512 InsetCollapsible::read(lex);
516 string InsetIndex::params2string(InsetIndexParams const & params)
525 void InsetIndex::string2params(string const & in, InsetIndexParams & params)
527 params = InsetIndexParams();
531 istringstream data(in);
534 lex.setContext("InsetIndex::string2params");
540 void InsetIndex::addToToc(DocIterator const & cpit, bool output_active,
541 UpdateType utype, TocBackend & backend) const
543 DocIterator pit = cpit;
544 pit.push_back(CursorSlice(const_cast<InsetIndex &>(*this)));
546 string type = "index";
547 if (buffer().masterBuffer()->params().use_indices)
548 type += ":" + to_utf8(params_.index);
549 // this is unlikely to be terribly long
550 text().forOutliner(str, INT_MAX);
551 TocBuilder & b = backend.builder(type);
552 b.pushItem(pit, str, output_active);
553 // Proceed with the rest of the inset.
554 InsetCollapsible::addToToc(cpit, output_active, utype, backend);
559 void InsetIndex::validate(LaTeXFeatures & features) const
561 if (buffer().masterBuffer()->params().use_indices
562 && !params_.index.empty()
563 && params_.index != "idx")
564 features.require("splitidx");
565 InsetCollapsible::validate(features);
569 string InsetIndex::contextMenuName() const
571 return "context-index";
575 bool InsetIndex::hasSettings() const
577 return buffer().masterBuffer()->params().use_indices;
583 /////////////////////////////////////////////////////////////////////
587 ///////////////////////////////////////////////////////////////////////
590 void InsetIndexParams::write(ostream & os) const
594 os << to_utf8(index);
601 void InsetIndexParams::read(Lexer & lex)
604 index = lex.getDocString();
606 index = from_ascii("idx");
610 /////////////////////////////////////////////////////////////////////
614 ///////////////////////////////////////////////////////////////////////
616 InsetPrintIndex::InsetPrintIndex(Buffer * buf, InsetCommandParams const & p)
617 : InsetCommand(buf, p)
621 ParamInfo const & InsetPrintIndex::findInfo(string const & /* cmdName */)
623 static ParamInfo param_info_;
624 if (param_info_.empty()) {
625 param_info_.add("type", ParamInfo::LATEX_OPTIONAL,
626 ParamInfo::HANDLING_ESCAPE);
627 param_info_.add("name", ParamInfo::LATEX_OPTIONAL,
628 ParamInfo::HANDLING_LATEXIFY);
629 param_info_.add("literal", ParamInfo::LYX_INTERNAL);
635 docstring InsetPrintIndex::screenLabel() const
637 bool const printall = suffixIs(getCmdName(), '*');
638 bool const multind = buffer().masterBuffer()->params().use_indices;
640 && getParam("type") == from_ascii("idx"))
641 || (getParam("type").empty() && !printall))
643 Buffer const & realbuffer = *buffer().masterBuffer();
644 IndicesList const & indiceslist = realbuffer.params().indiceslist();
645 Index const * index = indiceslist.findShortcut(getParam("type"));
646 if (!index && !printall)
647 return _("Unknown index type!");
648 docstring res = printall ? _("All indexes") : index->index();
650 res += " (" + _("non-active") + ")";
651 else if (contains(getCmdName(), "printsubindex"))
652 res += " (" + _("subindex") + ")";
657 bool InsetPrintIndex::isCompatibleCommand(string const & s)
659 return s == "printindex" || s == "printsubindex"
660 || s == "printindex*" || s == "printsubindex*";
664 void InsetPrintIndex::doDispatch(Cursor & cur, FuncRequest & cmd)
666 switch (cmd.action()) {
668 case LFUN_INSET_MODIFY: {
669 if (cmd.argument() == from_ascii("toggle-subindex")) {
670 string scmd = getCmdName();
671 if (contains(scmd, "printindex"))
672 scmd = subst(scmd, "printindex", "printsubindex");
674 scmd = subst(scmd, "printsubindex", "printindex");
678 } else if (cmd.argument() == from_ascii("check-printindex*")) {
679 string scmd = getCmdName();
680 if (suffixIs(scmd, '*'))
684 setParam("type", docstring());
688 InsetCommandParams p(INDEX_PRINT_CODE);
690 InsetCommand::string2params(to_utf8(cmd.argument()), p);
691 if (p.getCmdName().empty()) {
692 cur.noScreenUpdate();
701 InsetCommand::doDispatch(cur, cmd);
707 bool InsetPrintIndex::getStatus(Cursor & cur, FuncRequest const & cmd,
708 FuncStatus & status) const
710 switch (cmd.action()) {
712 case LFUN_INSET_MODIFY: {
713 if (cmd.argument() == from_ascii("toggle-subindex")) {
714 status.setEnabled(buffer().masterBuffer()->params().use_indices);
715 status.setOnOff(contains(getCmdName(), "printsubindex"));
717 } else if (cmd.argument() == from_ascii("check-printindex*")) {
718 status.setEnabled(buffer().masterBuffer()->params().use_indices);
719 status.setOnOff(suffixIs(getCmdName(), '*'));
721 } if (cmd.getArg(0) == "index_print"
722 && cmd.getArg(1) == "CommandInset") {
723 InsetCommandParams p(INDEX_PRINT_CODE);
724 InsetCommand::string2params(to_utf8(cmd.argument()), p);
725 if (suffixIs(p.getCmdName(), '*')) {
726 status.setEnabled(true);
727 status.setOnOff(false);
730 Buffer const & realbuffer = *buffer().masterBuffer();
731 IndicesList const & indiceslist =
732 realbuffer.params().indiceslist();
733 Index const * index = indiceslist.findShortcut(p["type"]);
734 status.setEnabled(index != 0);
735 status.setOnOff(p["type"] == getParam("type"));
738 return InsetCommand::getStatus(cur, cmd, status);
741 case LFUN_INSET_DIALOG_UPDATE: {
742 status.setEnabled(buffer().masterBuffer()->params().use_indices);
747 return InsetCommand::getStatus(cur, cmd, status);
752 void InsetPrintIndex::updateBuffer(ParIterator const &, UpdateType, bool const /*deleted*/)
754 Index const * index =
755 buffer().masterParams().indiceslist().findShortcut(getParam("type"));
757 setParam("name", index->index());
761 void InsetPrintIndex::latex(otexstream & os, OutputParams const & runparams_in) const
763 if (!buffer().masterBuffer()->params().use_indices) {
764 if (getParam("type") == from_ascii("idx"))
765 os << "\\printindex" << termcmd;
768 OutputParams runparams = runparams_in;
769 os << getCommand(runparams);
773 void InsetPrintIndex::validate(LaTeXFeatures & features) const
775 features.require("makeidx");
776 if (buffer().masterBuffer()->params().use_indices)
777 features.require("splitidx");
778 InsetCommand::validate(features);
782 string InsetPrintIndex::contextMenuName() const
784 return buffer().masterBuffer()->params().use_indices ?
785 "context-indexprint" : string();
789 bool InsetPrintIndex::hasSettings() const
791 return buffer().masterBuffer()->params().use_indices;
797 void parseItem(docstring & s, bool for_output)
799 // this does not yet check for escaped things
800 size_type loc = s.find(from_ascii("@"));
801 if (loc != string::npos) {
807 loc = s.find(from_ascii("|"));
808 if (loc != string::npos)
813 void extractSubentries(docstring const & entry, docstring & main,
814 docstring & sub1, docstring & sub2)
818 size_type const loc = entry.find(from_ascii(" ! "));
819 if (loc == string::npos)
822 main = trim(entry.substr(0, loc));
823 size_t const locend = loc + 3;
824 size_type const loc2 = entry.find(from_ascii(" ! "), locend);
825 if (loc2 == string::npos) {
826 sub1 = trim(entry.substr(locend));
828 sub1 = trim(entry.substr(locend, loc2 - locend));
829 sub2 = trim(entry.substr(loc2 + 3));
840 IndexEntry(docstring const & s, DocIterator const & d)
843 extractSubentries(s, main, sub, subsub);
844 parseItem(main, false);
845 parseItem(sub, false);
846 parseItem(subsub, false);
849 bool equal(IndexEntry const & rhs) const
851 return main == rhs.main && sub == rhs.sub && subsub == rhs.subsub;
854 bool same_sub(IndexEntry const & rhs) const
856 return main == rhs.main && sub == rhs.sub;
859 bool same_main(IndexEntry const & rhs) const
861 return main == rhs.main;
870 bool operator<(IndexEntry const & lhs, IndexEntry const & rhs)
872 int comp = compare_no_case(lhs.main, rhs.main);
874 comp = compare_no_case(lhs.sub, rhs.sub);
876 comp = compare_no_case(lhs.subsub, rhs.subsub);
883 docstring InsetPrintIndex::xhtml(XMLStream &, OutputParams const & op) const
885 BufferParams const & bp = buffer().masterBuffer()->params();
887 // we do not presently support multiple indices, so we refuse to print
888 // anything but the main index, so as not to generate multiple indices.
889 // NOTE Multiple index support would require some work. The reason
890 // is that the TOC does not know about multiple indices. Either it would
891 // need to be told about them (not a bad idea), or else the index entries
892 // would need to be collected differently, say, during validation.
893 if (bp.use_indices && getParam("type") != from_ascii("idx"))
896 shared_ptr<Toc const> toc = buffer().tocBackend().toc("index");
900 // Collect the index entries in a form we can use them.
901 Toc::const_iterator it = toc->begin();
902 Toc::const_iterator const en = toc->end();
903 vector<IndexEntry> entries;
904 for (; it != en; ++it)
906 entries.push_back(IndexEntry(it->str(), it->dit()));
909 // not very likely that all the index entries are in notes or
913 stable_sort(entries.begin(), entries.end());
915 Layout const & lay = bp.documentClass().htmlTOCLayout();
916 string const & tocclass = lay.defaultCSSClass();
917 string const tocattr = "class='index " + tocclass + "'";
919 // we'll use our own stream, because we are going to defer everything.
920 // that's how we deal with the fact that we're probably inside a standard
921 // paragraph, and we don't want to be.
922 odocstringstream ods;
925 xs << xml::StartTag("div", tocattr);
926 xs << xml::StartTag(lay.htmltag(), lay.htmlattr())
927 << translateIfPossible(from_ascii("Index"),
928 op.local_font->language()->lang())
929 << xml::EndTag(lay.htmltag());
930 xs << xml::StartTag("ul", "class='main'");
933 vector<IndexEntry>::const_iterator eit = entries.begin();
934 vector<IndexEntry>::const_iterator const een = entries.end();
935 // tracks whether we are already inside a main entry (1),
936 // a sub-entry (2), or a sub-sub-entry (3). see below for the
939 // the last one we saw
941 int entry_number = -1;
942 for (; eit != een; ++eit) {
943 Paragraph const & par = eit->dit.innerParagraph();
944 if (entry_number == -1 || !eit->equal(last)) {
945 if (entry_number != -1) {
946 // not the first time through the loop, so
947 // close last entry or entries, depending.
949 // close this sub-sub-entry
950 xs << xml::EndTag("li") << xml::CR();
951 // is this another sub-sub-entry within the same sub-entry?
952 if (!eit->same_sub(last)) {
954 xs << xml::EndTag("ul") << xml::CR();
958 // the point of the second test here is that we might get
959 // here two ways: (i) by falling through from above; (ii) because,
960 // though the sub-entry hasn't changed, the sub-sub-entry has,
961 // which means that it is the first sub-sub-entry within this
962 // sub-entry. In that case, we do not want to close anything.
963 if (level == 2 && !eit->same_sub(last)) {
965 xs << xml::EndTag("li") << xml::CR();
966 // is this another sub-entry with the same main entry?
967 if (!eit->same_main(last)) {
969 xs << xml::EndTag("ul") << xml::CR();
973 // again, we can get here two ways: from above, or because we have
974 // found the first sub-entry. in the latter case, we do not want to
976 if (level == 1 && !eit->same_main(last)) {
978 xs << xml::EndTag("li") << xml::CR();
982 // we'll be starting new entries
985 // We need to use our own stream, since we will have to
986 // modify what we get back.
987 odocstringstream ent;
988 XMLStream entstream(ent);
989 OutputParams ours = op;
991 par.simpleLyXHTMLOnePar(buffer(), entstream, ours, dummy);
993 // these will contain XHTML versions of the main entry, etc
994 // remember that everything will already have been escaped,
995 // so we'll need to use NextRaw() during output.
999 extractSubentries(ent.str(), main, sub, subsub);
1000 parseItem(main, true);
1001 parseItem(sub, true);
1002 parseItem(subsub, true);
1005 // another subsubentry
1006 xs << xml::StartTag("li", "class='subsubentry'")
1007 << XMLStream::ESCAPE_NONE << subsub;
1008 } else if (level == 2) {
1009 // there are two ways we can be here:
1010 // (i) we can actually be inside a sub-entry already and be about
1011 // to output the first sub-sub-entry. in this case, our sub
1012 // and the last sub will be the same.
1013 // (ii) we can just have closed a sub-entry, possibly after also
1014 // closing a list of sub-sub-entries. here our sub and the last
1015 // sub are different.
1016 // only in the latter case do we need to output the new sub-entry.
1017 // note that in this case, too, though, the sub-entry might already
1018 // have a sub-sub-entry.
1019 if (eit->sub != last.sub)
1020 xs << xml::StartTag("li", "class='subentry'")
1021 << XMLStream::ESCAPE_NONE << sub;
1022 if (!subsub.empty()) {
1023 // it's actually a subsubentry, so we need to start that list
1025 << xml::StartTag("ul", "class='subsubentry'")
1026 << xml::StartTag("li", "class='subsubentry'")
1027 << XMLStream::ESCAPE_NONE << subsub;
1031 // there are also two ways we can be here:
1032 // (i) we can actually be inside an entry already and be about
1033 // to output the first sub-entry. in this case, our main
1034 // and the last main will be the same.
1035 // (ii) we can just have closed an entry, possibly after also
1036 // closing a list of sub-entries. here our main and the last
1037 // main are different.
1038 // only in the latter case do we need to output the new main entry.
1039 // note that in this case, too, though, the main entry might already
1040 // have a sub-entry, or even a sub-sub-entry.
1041 if (eit->main != last.main)
1042 xs << xml::StartTag("li", "class='main'") << main;
1044 // there's a sub-entry, too
1046 << xml::StartTag("ul", "class='subentry'")
1047 << xml::StartTag("li", "class='subentry'")
1048 << XMLStream::ESCAPE_NONE << sub;
1050 if (!subsub.empty()) {
1051 // and a sub-sub-entry
1053 << xml::StartTag("ul", "class='subsubentry'")
1054 << xml::StartTag("li", "class='subsubentry'")
1055 << XMLStream::ESCAPE_NONE << subsub;
1061 // finally, then, we can output the index link itself
1062 string const parattr = "href='#" + par.magicLabel() + "'";
1063 xs << (entry_number == 0 ? ":" : ",");
1064 xs << " " << xml::StartTag("a", parattr)
1065 << ++entry_number << xml::EndTag("a");
1068 // now we have to close all the open levels
1070 xs << xml::EndTag("li") << xml::EndTag("ul") << xml::CR();
1073 xs << xml::EndTag("div") << xml::CR();