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 using namespace lyx::support;
50 /////////////////////////////////////////////////////////////////////
54 ///////////////////////////////////////////////////////////////////////
57 InsetIndex::InsetIndex(Buffer * buf, InsetIndexParams const & params)
58 : InsetCollapsible(buf), params_(params)
62 void InsetIndex::latex(otexstream & os, OutputParams const & runparams_in) const
64 OutputParams runparams(runparams_in);
65 runparams.inIndexEntry = true;
67 if (buffer().masterBuffer()->params().use_indices && !params_.index.empty()
68 && params_.index != "idx") {
70 os << escape(params_.index);
77 odocstringstream ourlatex;
78 otexstream ots(ourlatex);
79 InsetText::latex(ots, runparams);
80 if (runparams.for_search) {
81 // No need for special handling, if we are only searching for some patterns
82 os << ourlatex.str() << "}";
85 // get contents of InsetText as LaTeX and plaintext
86 odocstringstream ourplain;
87 InsetText::plaintext(ourplain, runparams);
88 // FIXME: do Tex/Row correspondence (I don't currently understand what is
89 // being generated from latexstr below)
90 docstring latexstr = ourlatex.str();
91 docstring plainstr = ourplain.str();
93 // this will get what follows | if anything does
96 // check for the | separator
97 // FIXME This would go wrong on an escaped "|", but
98 // how far do we want to go here?
99 size_t pos = latexstr.find(from_ascii("|"));
100 if (pos != docstring::npos) {
101 // put the bit after "|" into cmd...
102 cmd = latexstr.substr(pos + 1);
103 // ...and erase that stuff from latexstr
104 latexstr = latexstr.erase(pos);
105 // ...and similarly from plainstr
106 size_t ppos = plainstr.find(from_ascii("|"));
107 if (ppos < plainstr.size())
108 plainstr.erase(ppos);
110 LYXERR0("The `|' separator was not found in the plaintext version!");
113 // Separate the entires and subentries, i.e., split on "!"
114 // FIXME This would do the wrong thing with escaped ! characters
115 std::vector<docstring> const levels =
116 getVectorFromString(latexstr, from_ascii("!"), true);
117 std::vector<docstring> const levels_plain =
118 getVectorFromString(plainstr, from_ascii("!"), true);
120 vector<docstring>::const_iterator it = levels.begin();
121 vector<docstring>::const_iterator end = levels.end();
122 vector<docstring>::const_iterator it2 = levels_plain.begin();
124 for (; it != end; ++it) {
125 // write the separator except the first time
131 // correctly sort macros and formatted strings
132 // if we do find a command, prepend a plain text
133 // version of the content to get sorting right,
134 // e.g. \index{LyX@\LyX}, \index{text@\textbf{text}}
135 // Don't do that if the user entered '@' himself, though.
136 if (contains(*it, '\\') && !contains(*it, '@')) {
137 // Plaintext might return nothing (e.g. for ERTs)
138 docstring const spart =
139 (it2 < levels_plain.end() && !(*it2).empty())
141 // Now we need to validate that all characters in
142 // the sorting part are representable in the current
143 // encoding. If not try the LaTeX macro which might
144 // or might not be a good choice, and issue a warning.
145 pair<docstring, docstring> spart_latexed =
146 runparams.encoding->latexString(spart, runparams.dryrun);
147 if (!spart_latexed.second.empty())
148 LYXERR0("Uncodable character in index entry. Sorting might be wrong!");
149 if (spart != spart_latexed.first && !runparams.dryrun) {
150 // FIXME: warning should be passed to the error dialog
151 frontend::Alert::warning(_("Index sorting failed"),
152 bformat(_("LyX's automatic index sorting algorithm faced\n"
153 "problems with the entry '%1$s'.\n"
154 "Please specify the sorting of this entry manually, as\n"
155 "explained in the User Guide."), spart));
157 // remove remaining \'s for the sorting part
158 docstring const ppart =
159 subst(spart_latexed.first, from_ascii("\\"), docstring());
163 docstring const tpart = *it;
165 if (it2 < levels_plain.end())
168 // write the bit that followed "|"
176 int InsetIndex::docbook(odocstream & os, OutputParams const & runparams) const
178 os << "<indexterm><primary>";
179 int const i = InsetText::docbook(os, runparams);
180 os << "</primary></indexterm>";
185 docstring InsetIndex::xhtml(XHTMLStream & xs, OutputParams const &) const
187 // we just print an anchor, taking the paragraph ID from
188 // our own interior paragraph, which doesn't get printed
189 std::string const magic = paragraphs().front().magicLabel();
190 std::string const attr = "id='" + magic + "'";
191 xs << html::CompTag("a", attr);
196 bool InsetIndex::showInsetDialog(BufferView * bv) const
198 bv->showDialog("index", params2string(params_),
199 const_cast<InsetIndex *>(this));
204 void InsetIndex::doDispatch(Cursor & cur, FuncRequest & cmd)
206 switch (cmd.action()) {
208 case LFUN_INSET_MODIFY: {
209 if (cmd.getArg(0) == "changetype") {
210 cur.recordUndoInset(this);
211 params_.index = from_utf8(cmd.getArg(1));
214 InsetIndexParams params;
215 InsetIndex::string2params(to_utf8(cmd.argument()), params);
216 cur.recordUndoInset(this);
217 params_.index = params.index;
218 // what we really want here is a TOC update, but that means
219 // a full buffer update
220 cur.forceBufferUpdate();
224 case LFUN_INSET_DIALOG_UPDATE:
225 cur.bv().updateDialog("index", params2string(params_));
229 InsetCollapsible::doDispatch(cur, cmd);
235 bool InsetIndex::getStatus(Cursor & cur, FuncRequest const & cmd,
236 FuncStatus & flag) const
238 switch (cmd.action()) {
240 case LFUN_INSET_MODIFY:
241 if (cmd.getArg(0) == "changetype") {
242 docstring const newtype = from_utf8(cmd.getArg(1));
243 Buffer const & realbuffer = *buffer().masterBuffer();
244 IndicesList const & indiceslist = realbuffer.params().indiceslist();
245 Index const * index = indiceslist.findShortcut(newtype);
246 flag.setEnabled(index != 0);
248 from_utf8(cmd.getArg(1)) == params_.index);
251 return InsetCollapsible::getStatus(cur, cmd, flag);
253 case LFUN_INSET_DIALOG_UPDATE: {
254 Buffer const & realbuffer = *buffer().masterBuffer();
255 flag.setEnabled(realbuffer.params().use_indices);
260 return InsetCollapsible::getStatus(cur, cmd, flag);
265 ColorCode InsetIndex::labelColor() const
267 if (params_.index.empty() || params_.index == from_ascii("idx"))
268 return InsetCollapsible::labelColor();
270 ColorCode c = lcolor.getFromLyXName(to_utf8(params_.index));
272 c = InsetCollapsible::labelColor();
277 docstring InsetIndex::toolTip(BufferView const &, int, int) const
279 docstring tip = _("Index Entry");
280 if (buffer().params().use_indices && !params_.index.empty()) {
281 Buffer const & realbuffer = *buffer().masterBuffer();
282 IndicesList const & indiceslist = realbuffer.params().indiceslist();
284 Index const * index = indiceslist.findShortcut(params_.index);
286 tip += _("unknown type!");
288 tip += index->index();
292 return toolTipText(tip);
296 docstring const InsetIndex::buttonLabel(BufferView const & bv) const
298 InsetLayout const & il = getLayout();
299 docstring label = translateIfPossible(il.labelstring());
301 if (buffer().params().use_indices && !params_.index.empty()) {
302 Buffer const & realbuffer = *buffer().masterBuffer();
303 IndicesList const & indiceslist = realbuffer.params().indiceslist();
305 Index const * index = indiceslist.findShortcut(params_.index);
307 label += _("unknown type!");
309 label += index->index();
313 if (!il.contentaslabel() || geometry(bv) != ButtonOnly)
315 return getNewLabel(label);
319 void InsetIndex::write(ostream & os) const
321 os << to_utf8(layoutName());
323 InsetCollapsible::write(os);
327 void InsetIndex::read(Lexer & lex)
330 InsetCollapsible::read(lex);
334 string InsetIndex::params2string(InsetIndexParams const & params)
343 void InsetIndex::string2params(string const & in, InsetIndexParams & params)
345 params = InsetIndexParams();
349 istringstream data(in);
352 lex.setContext("InsetIndex::string2params");
358 void InsetIndex::addToToc(DocIterator const & cpit, bool output_active,
359 UpdateType utype, TocBackend & backend) const
361 DocIterator pit = cpit;
362 pit.push_back(CursorSlice(const_cast<InsetIndex &>(*this)));
364 string type = "index";
365 if (buffer().masterBuffer()->params().use_indices)
366 type += ":" + to_utf8(params_.index);
367 // this is unlikely to be terribly long
368 text().forOutliner(str, INT_MAX);
369 TocBuilder & b = backend.builder(type);
370 b.pushItem(pit, str, output_active);
371 // Proceed with the rest of the inset.
372 InsetCollapsible::addToToc(cpit, output_active, utype, backend);
377 void InsetIndex::validate(LaTeXFeatures & features) const
379 if (buffer().masterBuffer()->params().use_indices
380 && !params_.index.empty()
381 && params_.index != "idx")
382 features.require("splitidx");
383 InsetCollapsible::validate(features);
387 string InsetIndex::contextMenuName() const
389 return "context-index";
393 bool InsetIndex::hasSettings() const
395 return buffer().masterBuffer()->params().use_indices;
401 /////////////////////////////////////////////////////////////////////
405 ///////////////////////////////////////////////////////////////////////
408 void InsetIndexParams::write(ostream & os) const
412 os << to_utf8(index);
419 void InsetIndexParams::read(Lexer & lex)
422 index = lex.getDocString();
424 index = from_ascii("idx");
428 /////////////////////////////////////////////////////////////////////
432 ///////////////////////////////////////////////////////////////////////
434 InsetPrintIndex::InsetPrintIndex(Buffer * buf, InsetCommandParams const & p)
435 : InsetCommand(buf, p)
439 ParamInfo const & InsetPrintIndex::findInfo(string const & /* cmdName */)
441 static ParamInfo param_info_;
442 if (param_info_.empty()) {
443 param_info_.add("type", ParamInfo::LATEX_OPTIONAL,
444 ParamInfo::HANDLING_ESCAPE);
445 param_info_.add("name", ParamInfo::LATEX_OPTIONAL,
446 ParamInfo::HANDLING_LATEXIFY);
447 param_info_.add("literal", ParamInfo::LYX_INTERNAL);
453 docstring InsetPrintIndex::screenLabel() const
455 bool const printall = suffixIs(getCmdName(), '*');
456 bool const multind = buffer().masterBuffer()->params().use_indices;
458 && getParam("type") == from_ascii("idx"))
459 || (getParam("type").empty() && !printall))
461 Buffer const & realbuffer = *buffer().masterBuffer();
462 IndicesList const & indiceslist = realbuffer.params().indiceslist();
463 Index const * index = indiceslist.findShortcut(getParam("type"));
464 if (!index && !printall)
465 return _("Unknown index type!");
466 docstring res = printall ? _("All indexes") : index->index();
468 res += " (" + _("non-active") + ")";
469 else if (contains(getCmdName(), "printsubindex"))
470 res += " (" + _("subindex") + ")";
475 bool InsetPrintIndex::isCompatibleCommand(string const & s)
477 return s == "printindex" || s == "printsubindex"
478 || s == "printindex*" || s == "printsubindex*";
482 void InsetPrintIndex::doDispatch(Cursor & cur, FuncRequest & cmd)
484 switch (cmd.action()) {
486 case LFUN_INSET_MODIFY: {
487 if (cmd.argument() == from_ascii("toggle-subindex")) {
488 string scmd = getCmdName();
489 if (contains(scmd, "printindex"))
490 scmd = subst(scmd, "printindex", "printsubindex");
492 scmd = subst(scmd, "printsubindex", "printindex");
496 } else if (cmd.argument() == from_ascii("check-printindex*")) {
497 string scmd = getCmdName();
498 if (suffixIs(scmd, '*'))
502 setParam("type", docstring());
506 InsetCommandParams p(INDEX_PRINT_CODE);
508 InsetCommand::string2params(to_utf8(cmd.argument()), p);
509 if (p.getCmdName().empty()) {
510 cur.noScreenUpdate();
519 InsetCommand::doDispatch(cur, cmd);
525 bool InsetPrintIndex::getStatus(Cursor & cur, FuncRequest const & cmd,
526 FuncStatus & status) const
528 switch (cmd.action()) {
530 case LFUN_INSET_MODIFY: {
531 if (cmd.argument() == from_ascii("toggle-subindex")) {
532 status.setEnabled(buffer().masterBuffer()->params().use_indices);
533 status.setOnOff(contains(getCmdName(), "printsubindex"));
535 } else if (cmd.argument() == from_ascii("check-printindex*")) {
536 status.setEnabled(buffer().masterBuffer()->params().use_indices);
537 status.setOnOff(suffixIs(getCmdName(), '*'));
539 } if (cmd.getArg(0) == "index_print"
540 && cmd.getArg(1) == "CommandInset") {
541 InsetCommandParams p(INDEX_PRINT_CODE);
542 InsetCommand::string2params(to_utf8(cmd.argument()), p);
543 if (suffixIs(p.getCmdName(), '*')) {
544 status.setEnabled(true);
545 status.setOnOff(false);
548 Buffer const & realbuffer = *buffer().masterBuffer();
549 IndicesList const & indiceslist =
550 realbuffer.params().indiceslist();
551 Index const * index = indiceslist.findShortcut(p["type"]);
552 status.setEnabled(index != 0);
553 status.setOnOff(p["type"] == getParam("type"));
556 return InsetCommand::getStatus(cur, cmd, status);
559 case LFUN_INSET_DIALOG_UPDATE: {
560 status.setEnabled(buffer().masterBuffer()->params().use_indices);
565 return InsetCommand::getStatus(cur, cmd, status);
570 void InsetPrintIndex::updateBuffer(ParIterator const &, UpdateType)
572 Index const * index =
573 buffer().masterParams().indiceslist().findShortcut(getParam("type"));
575 setParam("name", index->index());
579 void InsetPrintIndex::latex(otexstream & os, OutputParams const & runparams_in) const
581 if (!buffer().masterBuffer()->params().use_indices) {
582 if (getParam("type") == from_ascii("idx"))
583 os << "\\printindex" << termcmd;
586 OutputParams runparams = runparams_in;
587 os << getCommand(runparams);
591 void InsetPrintIndex::validate(LaTeXFeatures & features) const
593 features.require("makeidx");
594 if (buffer().masterBuffer()->params().use_indices)
595 features.require("splitidx");
596 InsetCommand::validate(features);
600 string InsetPrintIndex::contextMenuName() const
602 return buffer().masterBuffer()->params().use_indices ?
603 "context-indexprint" : string();
607 bool InsetPrintIndex::hasSettings() const
609 return buffer().masterBuffer()->params().use_indices;
615 void parseItem(docstring & s, bool for_output)
617 // this does not yet check for escaped things
618 size_type loc = s.find(from_ascii("@"));
619 if (loc != string::npos) {
625 loc = s.find(from_ascii("|"));
626 if (loc != string::npos)
631 void extractSubentries(docstring const & entry, docstring & main,
632 docstring & sub1, docstring & sub2)
636 size_type const loc = entry.find(from_ascii(" ! "));
637 if (loc == string::npos)
640 main = trim(entry.substr(0, loc));
641 size_t const locend = loc + 3;
642 size_type const loc2 = entry.find(from_ascii(" ! "), locend);
643 if (loc2 == string::npos) {
644 sub1 = trim(entry.substr(locend));
646 sub1 = trim(entry.substr(locend, loc2 - locend));
647 sub2 = trim(entry.substr(loc2 + 3));
658 IndexEntry(docstring const & s, DocIterator const & d)
661 extractSubentries(s, main, sub, subsub);
662 parseItem(main, false);
663 parseItem(sub, false);
664 parseItem(subsub, false);
667 bool equal(IndexEntry const & rhs) const
669 return main == rhs.main && sub == rhs.sub && subsub == rhs.subsub;
672 bool same_sub(IndexEntry const & rhs) const
674 return main == rhs.main && sub == rhs.sub;
677 bool same_main(IndexEntry const & rhs) const
679 return main == rhs.main;
688 bool operator<(IndexEntry const & lhs, IndexEntry const & rhs)
690 int comp = compare_no_case(lhs.main, rhs.main);
692 comp = compare_no_case(lhs.sub, rhs.sub);
694 comp = compare_no_case(lhs.subsub, rhs.subsub);
701 docstring InsetPrintIndex::xhtml(XHTMLStream &, OutputParams const & op) const
703 BufferParams const & bp = buffer().masterBuffer()->params();
705 // we do not presently support multiple indices, so we refuse to print
706 // anything but the main index, so as not to generate multiple indices.
707 // NOTE Multiple index support would require some work. The reason
708 // is that the TOC does not know about multiple indices. Either it would
709 // need to be told about them (not a bad idea), or else the index entries
710 // would need to be collected differently, say, during validation.
711 if (bp.use_indices && getParam("type") != from_ascii("idx"))
714 shared_ptr<Toc const> toc = buffer().tocBackend().toc("index");
718 // Collect the index entries in a form we can use them.
719 Toc::const_iterator it = toc->begin();
720 Toc::const_iterator const en = toc->end();
721 vector<IndexEntry> entries;
722 for (; it != en; ++it)
724 entries.push_back(IndexEntry(it->str(), it->dit()));
727 // not very likely that all the index entries are in notes or
731 stable_sort(entries.begin(), entries.end());
733 Layout const & lay = bp.documentClass().htmlTOCLayout();
734 string const & tocclass = lay.defaultCSSClass();
735 string const tocattr = "class='index " + tocclass + "'";
737 // we'll use our own stream, because we are going to defer everything.
738 // that's how we deal with the fact that we're probably inside a standard
739 // paragraph, and we don't want to be.
740 odocstringstream ods;
743 xs << html::StartTag("div", tocattr);
744 xs << html::StartTag(lay.htmltag(), lay.htmlattr())
745 << translateIfPossible(from_ascii("Index"),
746 op.local_font->language()->lang())
747 << html::EndTag(lay.htmltag());
748 xs << html::StartTag("ul", "class='main'");
751 vector<IndexEntry>::const_iterator eit = entries.begin();
752 vector<IndexEntry>::const_iterator const een = entries.end();
753 // tracks whether we are already inside a main entry (1),
754 // a sub-entry (2), or a sub-sub-entry (3). see below for the
757 // the last one we saw
759 int entry_number = -1;
760 for (; eit != een; ++eit) {
761 Paragraph const & par = eit->dit.innerParagraph();
762 if (entry_number == -1 || !eit->equal(last)) {
763 if (entry_number != -1) {
764 // not the first time through the loop, so
765 // close last entry or entries, depending.
767 // close this sub-sub-entry
768 xs << html::EndTag("li") << html::CR();
769 // is this another sub-sub-entry within the same sub-entry?
770 if (!eit->same_sub(last)) {
772 xs << html::EndTag("ul") << html::CR();
776 // the point of the second test here is that we might get
777 // here two ways: (i) by falling through from above; (ii) because,
778 // though the sub-entry hasn't changed, the sub-sub-entry has,
779 // which means that it is the first sub-sub-entry within this
780 // sub-entry. In that case, we do not want to close anything.
781 if (level == 2 && !eit->same_sub(last)) {
783 xs << html::EndTag("li") << html::CR();
784 // is this another sub-entry with the same main entry?
785 if (!eit->same_main(last)) {
787 xs << html::EndTag("ul") << html::CR();
791 // again, we can get here two ways: from above, or because we have
792 // found the first sub-entry. in the latter case, we do not want to
794 if (level == 1 && !eit->same_main(last)) {
796 xs << html::EndTag("li") << html::CR();
800 // we'll be starting new entries
803 // We need to use our own stream, since we will have to
804 // modify what we get back.
805 odocstringstream ent;
806 XHTMLStream entstream(ent);
807 OutputParams ours = op;
809 par.simpleLyXHTMLOnePar(buffer(), entstream, ours, dummy);
811 // these will contain XHTML versions of the main entry, etc
812 // remember that everything will already have been escaped,
813 // so we'll need to use NextRaw() during output.
817 extractSubentries(ent.str(), main, sub, subsub);
818 parseItem(main, true);
819 parseItem(sub, true);
820 parseItem(subsub, true);
823 // another subsubentry
824 xs << html::StartTag("li", "class='subsubentry'")
825 << XHTMLStream::ESCAPE_NONE << subsub;
826 } else if (level == 2) {
827 // there are two ways we can be here:
828 // (i) we can actually be inside a sub-entry already and be about
829 // to output the first sub-sub-entry. in this case, our sub
830 // and the last sub will be the same.
831 // (ii) we can just have closed a sub-entry, possibly after also
832 // closing a list of sub-sub-entries. here our sub and the last
833 // sub are different.
834 // only in the latter case do we need to output the new sub-entry.
835 // note that in this case, too, though, the sub-entry might already
836 // have a sub-sub-entry.
837 if (eit->sub != last.sub)
838 xs << html::StartTag("li", "class='subentry'")
839 << XHTMLStream::ESCAPE_NONE << sub;
840 if (!subsub.empty()) {
841 // it's actually a subsubentry, so we need to start that list
843 << html::StartTag("ul", "class='subsubentry'")
844 << html::StartTag("li", "class='subsubentry'")
845 << XHTMLStream::ESCAPE_NONE << subsub;
849 // there are also two ways we can be here:
850 // (i) we can actually be inside an entry already and be about
851 // to output the first sub-entry. in this case, our main
852 // and the last main will be the same.
853 // (ii) we can just have closed an entry, possibly after also
854 // closing a list of sub-entries. here our main and the last
855 // main are different.
856 // only in the latter case do we need to output the new main entry.
857 // note that in this case, too, though, the main entry might already
858 // have a sub-entry, or even a sub-sub-entry.
859 if (eit->main != last.main)
860 xs << html::StartTag("li", "class='main'") << main;
862 // there's a sub-entry, too
864 << html::StartTag("ul", "class='subentry'")
865 << html::StartTag("li", "class='subentry'")
866 << XHTMLStream::ESCAPE_NONE << sub;
868 if (!subsub.empty()) {
869 // and a sub-sub-entry
871 << html::StartTag("ul", "class='subsubentry'")
872 << html::StartTag("li", "class='subsubentry'")
873 << XHTMLStream::ESCAPE_NONE << subsub;
879 // finally, then, we can output the index link itself
880 string const parattr = "href='#" + par.magicLabel() + "'";
881 xs << (entry_number == 0 ? ":" : ",");
882 xs << " " << html::StartTag("a", parattr)
883 << ++entry_number << html::EndTag("a");
886 // now we have to close all the open levels
888 xs << html::EndTag("li") << html::EndTag("ul") << html::CR();
891 xs << html::EndTag("div") << html::CR();