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"
19 #include "DispatchResult.h"
21 #include "FuncRequest.h"
22 #include "FuncStatus.h"
23 #include "IndicesList.h"
24 #include "LaTeXFeatures.h"
26 #include "output_latex.h"
27 #include "output_xhtml.h"
29 #include "TocBackend.h"
31 #include "support/debug.h"
32 #include "support/docstream.h"
33 #include "support/gettext.h"
34 #include "support/lstrings.h"
36 #include "frontends/alert.h"
41 using namespace lyx::support;
45 /////////////////////////////////////////////////////////////////////
49 ///////////////////////////////////////////////////////////////////////
52 InsetIndex::InsetIndex(Buffer * buf, InsetIndexParams const & params)
53 : InsetCollapsable(buf), params_(params)
57 int InsetIndex::latex(odocstream & os,
58 OutputParams const & runparams_in) const
60 OutputParams runparams(runparams_in);
61 runparams.inIndexEntry = true;
63 if (buffer().masterBuffer()->params().use_indices && !params_.index.empty()
64 && params_.index != "idx") {
74 // get contents of InsetText as LaTeX and plaintext
75 odocstringstream ourlatex;
76 InsetText::latex(ourlatex, runparams);
77 odocstringstream ourplain;
78 InsetText::plaintext(ourplain, runparams);
79 docstring latexstr = ourlatex.str();
80 docstring plainstr = ourplain.str();
82 // this will get what follows | if anything does
85 // check for the | separator
86 // FIXME This would go wrong on an escaped "|", but
87 // how far do we want to go here?
88 size_t pos = latexstr.find(from_ascii("|"));
89 if (pos != docstring::npos) {
90 // put the bit after "|" into cmd...
91 cmd = latexstr.substr(pos + 1);
92 // ...and erase that stuff from latexstr
93 latexstr = latexstr.erase(pos);
94 // ...and similarly from plainstr
95 size_t ppos = plainstr.find(from_ascii("|"));
96 if (ppos < plainstr.size())
99 LYXERR0("The `|' separator was not found in the plaintext version!");
102 // Separate the entires and subentries, i.e., split on "!"
103 // FIXME This would do the wrong thing with escaped ! characters
104 std::vector<docstring> const levels =
105 getVectorFromString(latexstr, from_ascii("!"), true);
106 std::vector<docstring> const levels_plain =
107 getVectorFromString(plainstr, from_ascii("!"), true);
109 vector<docstring>::const_iterator it = levels.begin();
110 vector<docstring>::const_iterator end = levels.end();
111 vector<docstring>::const_iterator it2 = levels_plain.begin();
113 for (; it != end; ++it) {
114 // write the separator except the first time
120 // correctly sort macros and formatted strings
121 // if we do find a command, prepend a plain text
122 // version of the content to get sorting right,
123 // e.g. \index{LyX@\LyX}, \index{text@\textbf{text}}
124 // Don't do that if the user entered '@' himself, though.
125 if (contains(*it, '\\') && !contains(*it, '@')) {
126 // Plaintext might return nothing (e.g. for ERTs)
127 docstring const spart =
128 (it2 < levels_plain.end() && !(*it2).empty())
130 // Now we need to validate that all characters in
131 // the sorting part are representable in the current
132 // encoding. If not try the LaTeX macro which might
133 // or might not be a good choice, and issue a warning.
135 for (size_t n = 0; n < spart.size(); ++n) {
137 spart2 += runparams.encoding->latexChar(spart[n]);
138 } catch (EncodingException & /* e */) {
139 LYXERR0("Uncodable character in index entry. Sorting might be wrong!");
142 if (spart != spart2 && !runparams.dryrun) {
143 // FIXME: warning should be passed to the error dialog
144 frontend::Alert::warning(_("Index sorting failed"),
145 bformat(_("LyX's automatic index sorting algorithm faced\n"
146 "problems with the entry '%1$s'.\n"
147 "Please specify the sorting of this entry manually, as\n"
148 "explained in the User Guide."), spart));
150 // remove remaining \'s for the sorting part
151 docstring const ppart =
152 subst(spart2, from_ascii("\\"), docstring());
155 i += count_char(ppart, '\n');
157 docstring const tpart = *it;
159 i += count_char(tpart, '\n');
160 if (it2 < levels_plain.end())
163 // write the bit that followed "|"
166 i += count_char(cmd, '\n');
173 int InsetIndex::docbook(odocstream & os, OutputParams const & runparams) const
175 os << "<indexterm><primary>";
176 int const i = InsetText::docbook(os, runparams);
177 os << "</primary></indexterm>";
182 docstring InsetIndex::xhtml(XHTMLStream & xs, OutputParams const &) const
184 // we just print an anchor, taking the paragraph ID from
185 // our own interior paragraph, which doesn't get printed
186 std::string const magic = paragraphs().front().magicLabel();
187 std::string const attr = "id='" + magic + "'";
188 xs << html::CompTag("a", attr);
193 bool InsetIndex::showInsetDialog(BufferView * bv) const
195 bv->showDialog("index", params2string(params_),
196 const_cast<InsetIndex *>(this));
201 void InsetIndex::doDispatch(Cursor & cur, FuncRequest & cmd)
203 switch (cmd.action()) {
205 case LFUN_INSET_MODIFY: {
206 if (cmd.getArg(0) == "changetype") {
207 params_.index = from_utf8(cmd.getArg(1));
210 InsetIndexParams params;
211 InsetIndex::string2params(to_utf8(cmd.argument()), params);
212 params_.index = params.index;
216 case LFUN_INSET_DIALOG_UPDATE:
217 cur.bv().updateDialog("index", params2string(params_));
221 InsetCollapsable::doDispatch(cur, cmd);
227 bool InsetIndex::getStatus(Cursor & cur, FuncRequest const & cmd,
228 FuncStatus & flag) const
230 switch (cmd.action()) {
232 case LFUN_INSET_MODIFY:
233 if (cmd.getArg(0) == "changetype") {
234 docstring const newtype = from_utf8(cmd.getArg(1));
235 Buffer const & realbuffer = *buffer().masterBuffer();
236 IndicesList const & indiceslist = realbuffer.params().indiceslist();
237 Index const * index = indiceslist.findShortcut(newtype);
238 flag.setEnabled(index != 0);
240 from_utf8(cmd.getArg(1)) == params_.index);
243 flag.setEnabled(true);
246 case LFUN_INSET_DIALOG_UPDATE: {
247 Buffer const & realbuffer = *buffer().masterBuffer();
248 flag.setEnabled(realbuffer.params().use_indices);
253 return InsetCollapsable::getStatus(cur, cmd, flag);
258 ColorCode InsetIndex::labelColor() const
260 if (params_.index.empty() || params_.index == from_ascii("idx"))
261 return InsetCollapsable::labelColor();
263 ColorCode c = lcolor.getFromLyXName(to_utf8(params_.index));
265 c = InsetCollapsable::labelColor();
270 docstring InsetIndex::toolTip(BufferView const &, int, int) const
272 docstring tip = _("Index Entry");
273 if (buffer().params().use_indices && !params_.index.empty()) {
274 Buffer const & realbuffer = *buffer().masterBuffer();
275 IndicesList const & indiceslist = realbuffer.params().indiceslist();
277 Index const * index = indiceslist.findShortcut(params_.index);
279 tip += _("unknown type!");
281 tip += index->index();
285 OutputParams rp(&buffer().params().encoding());
286 odocstringstream ods;
287 InsetText::plaintext(ods, rp);
289 return wrapParas(tip);
293 docstring const InsetIndex::buttonLabel(BufferView const & bv) const
295 InsetLayout const & il = getLayout();
296 docstring label = translateIfPossible(il.labelstring());
298 if (buffer().params().use_indices && !params_.index.empty()) {
299 Buffer const & realbuffer = *buffer().masterBuffer();
300 IndicesList const & indiceslist = realbuffer.params().indiceslist();
302 Index const * index = indiceslist.findShortcut(params_.index);
304 label += _("unknown type!");
306 label += index->index();
310 if (!il.contentaslabel() || geometry(bv) != ButtonOnly)
312 return getNewLabel(label);
316 void InsetIndex::write(ostream & os) const
318 os << to_utf8(name());
320 InsetCollapsable::write(os);
324 void InsetIndex::read(Lexer & lex)
327 InsetCollapsable::read(lex);
331 string InsetIndex::params2string(InsetIndexParams const & params)
340 void InsetIndex::string2params(string const & in, InsetIndexParams & params)
342 params = InsetIndexParams();
346 istringstream data(in);
349 lex.setContext("InsetIndex::string2params");
355 void InsetIndex::addToToc(DocIterator const & cpit)
357 DocIterator pit = cpit;
358 pit.push_back(CursorSlice(*this));
359 docstring const item = text().asString(0, 1, AS_STR_LABEL | AS_STR_INSETS);
360 buffer().tocBackend().toc("index").push_back(TocItem(pit, 0, item));
361 // Proceed with the rest of the inset.
362 InsetCollapsable::addToToc(cpit);
366 void InsetIndex::validate(LaTeXFeatures & features) const
368 if (buffer().masterBuffer()->params().use_indices
369 && !params_.index.empty()
370 && params_.index != "idx")
371 features.require("splitidx");
375 docstring InsetIndex::contextMenu(BufferView const &, int, int) const
377 return from_ascii("context-index");
381 bool InsetIndex::hasSettings() const
383 return buffer().masterBuffer()->params().use_indices;
389 /////////////////////////////////////////////////////////////////////
393 ///////////////////////////////////////////////////////////////////////
396 void InsetIndexParams::write(ostream & os) const
400 os << to_utf8(index);
407 void InsetIndexParams::read(Lexer & lex)
410 index = lex.getDocString();
412 index = from_ascii("idx");
416 /////////////////////////////////////////////////////////////////////
420 ///////////////////////////////////////////////////////////////////////
422 InsetPrintIndex::InsetPrintIndex(Buffer * buf, InsetCommandParams const & p)
423 : InsetCommand(buf, p, "index_print")
427 ParamInfo const & InsetPrintIndex::findInfo(string const & /* cmdName */)
429 static ParamInfo param_info_;
430 if (param_info_.empty()) {
431 param_info_.add("type", ParamInfo::LATEX_OPTIONAL);
432 param_info_.add("name", ParamInfo::LATEX_REQUIRED);
438 docstring InsetPrintIndex::screenLabel() const
440 bool const printall = suffixIs(getCmdName(), '*');
441 bool const multind = buffer().masterBuffer()->params().use_indices;
443 && getParam("type") == from_ascii("idx"))
444 || (getParam("type").empty() && !printall))
446 Buffer const & realbuffer = *buffer().masterBuffer();
447 IndicesList const & indiceslist = realbuffer.params().indiceslist();
448 Index const * index = indiceslist.findShortcut(getParam("type"));
449 if (!index && !printall)
450 return _("Unknown index type!");
451 docstring res = printall ? _("All indices") : index->index();
453 res += " (" + _("non-active") + ")";
454 else if (contains(getCmdName(), "printsubindex"))
455 res += " (" + _("subindex") + ")";
460 bool InsetPrintIndex::isCompatibleCommand(string const & s)
462 return s == "printindex" || s == "printsubindex"
463 || s == "printindex*" || s == "printsubindex*";
467 void InsetPrintIndex::doDispatch(Cursor & cur, FuncRequest & cmd)
469 switch (cmd.action()) {
471 case LFUN_INSET_MODIFY: {
472 if (cmd.argument() == from_ascii("toggle-subindex")) {
473 string cmd = getCmdName();
474 if (contains(cmd, "printindex"))
475 cmd = subst(cmd, "printindex", "printsubindex");
477 cmd = subst(cmd, "printsubindex", "printindex");
480 } else if (cmd.argument() == from_ascii("check-printindex*")) {
481 string cmd = getCmdName();
482 if (suffixIs(cmd, '*'))
485 setParam("type", docstring());
489 InsetCommandParams p(INDEX_PRINT_CODE);
491 InsetCommand::string2params("index_print",
492 to_utf8(cmd.argument()), p);
493 if (p.getCmdName().empty()) {
502 InsetCommand::doDispatch(cur, cmd);
508 bool InsetPrintIndex::getStatus(Cursor & cur, FuncRequest const & cmd,
509 FuncStatus & status) const
511 switch (cmd.action()) {
513 case LFUN_INSET_MODIFY: {
514 if (cmd.argument() == from_ascii("toggle-subindex")) {
515 status.setEnabled(buffer().masterBuffer()->params().use_indices);
516 status.setOnOff(contains(getCmdName(), "printsubindex"));
518 } else if (cmd.argument() == from_ascii("check-printindex*")) {
519 status.setEnabled(buffer().masterBuffer()->params().use_indices);
520 status.setOnOff(suffixIs(getCmdName(), '*'));
522 } if (cmd.getArg(0) == "index_print"
523 && cmd.getArg(1) == "CommandInset") {
524 InsetCommandParams p(INDEX_PRINT_CODE);
525 InsetCommand::string2params("index_print",
526 to_utf8(cmd.argument()), p);
527 if (suffixIs(p.getCmdName(), '*')) {
528 status.setEnabled(true);
529 status.setOnOff(false);
532 Buffer const & realbuffer = *buffer().masterBuffer();
533 IndicesList const & indiceslist =
534 realbuffer.params().indiceslist();
535 Index const * index = indiceslist.findShortcut(p["type"]);
536 status.setEnabled(index != 0);
537 status.setOnOff(p["type"] == getParam("type"));
540 return InsetCommand::getStatus(cur, cmd, status);
543 case LFUN_INSET_DIALOG_UPDATE: {
544 status.setEnabled(buffer().masterBuffer()->params().use_indices);
549 return InsetCommand::getStatus(cur, cmd, status);
554 int InsetPrintIndex::latex(odocstream & os, OutputParams const & runparams_in) const
556 if (!buffer().masterBuffer()->params().use_indices) {
557 if (getParam("type") == from_ascii("idx"))
558 os << "\\printindex{}";
561 OutputParams runparams = runparams_in;
562 os << getCommand(runparams);
567 void InsetPrintIndex::validate(LaTeXFeatures & features) const
569 features.require("makeidx");
570 if (buffer().masterBuffer()->params().use_indices)
571 features.require("splitidx");
575 docstring InsetPrintIndex::contextMenu(BufferView const &, int, int) const
577 return buffer().masterBuffer()->params().use_indices ?
578 from_ascii("context-indexprint") : docstring();
582 bool InsetPrintIndex::hasSettings() const
584 return buffer().masterBuffer()->params().use_indices;
590 void parseItem(docstring & s, bool for_output)
592 // this does not yet check for escaped things
593 size_type loc = s.find(from_ascii("@"));
594 if (loc != string::npos) {
600 loc = s.find(from_ascii("|"));
601 if (loc != string::npos)
606 void extractSubentries(docstring const & entry, docstring & main,
607 docstring & sub1, docstring & sub2)
611 size_type const loc = entry.find(from_ascii(" ! "));
612 if (loc == string::npos)
615 main = trim(entry.substr(0, loc));
616 size_t const locend = loc + 3;
617 size_type const loc2 = entry.find(from_ascii(" ! "), locend);
618 if (loc2 == string::npos) {
619 sub1 = trim(entry.substr(locend));
621 sub1 = trim(entry.substr(locend, loc2 - locend));
622 sub2 = trim(entry.substr(loc2 + 3));
633 IndexEntry(docstring const & s, DocIterator const & d)
636 extractSubentries(s, main, sub, subsub);
637 parseItem(main, false);
638 parseItem(sub, false);
639 parseItem(subsub, false);
642 bool equal(IndexEntry const & rhs) const
644 return main == rhs.main && sub == rhs.sub && subsub == rhs.subsub;
647 bool same_sub(IndexEntry const & rhs) const
649 return main == rhs.main && sub == rhs.sub;
652 bool same_main(IndexEntry const & rhs) const
654 return main == rhs.main;
663 bool operator<(IndexEntry const & lhs, IndexEntry const & rhs)
665 return lhs.main < rhs.main
666 || (lhs.main == rhs.main && lhs.sub < rhs.sub)
667 || (lhs.main == rhs.main && lhs.sub == rhs.sub && lhs.subsub < rhs.subsub);
673 docstring InsetPrintIndex::xhtml(XHTMLStream &, OutputParams const & op) const
675 BufferParams const & bp = buffer().masterBuffer()->params();
677 // we do not presently support multiple indices, so we refuse to print
678 // anything but the main index, so as not to generate multiple indices.
679 // NOTE Multiple index support would require some work. The reason
680 // is that the TOC does not know about multiple indices. Either it would
681 // need to be told about them (not a bad idea), or else the index entries
682 // would need to be collected differently, say, during validation.
683 if (bp.use_indices && getParam("type") != from_ascii("idx"))
686 Toc const & toc = buffer().tocBackend().toc("index");
690 // Collection the index entries in a form we can use them.
691 Toc::const_iterator it = toc.begin();
692 Toc::const_iterator const en = toc.end();
693 vector<IndexEntry> entries;
694 for (; it != en; ++it)
695 entries.push_back(IndexEntry(it->str(), it->dit()));
696 stable_sort(entries.begin(), entries.end());
698 Layout const & lay = bp.documentClass().htmlTOCLayout();
699 string const & tocclass = lay.defaultCSSClass();
700 string const tocattr = "class='tochead " + tocclass + "'";
702 // we'll use our own stream, because we are going to defer everything.
703 // that's how we deal with the fact that we're probably inside a standard
704 // paragraph, and we don't want to be.
705 odocstringstream ods;
708 xs << html::StartTag("div", "class='index'");
709 xs << html::StartTag(lay.htmltag(), lay.htmlattr())
711 << html::EndTag(lay.htmltag());
712 xs << html::StartTag("ul", "class='main'");
715 vector<IndexEntry>::const_iterator eit = entries.begin();
716 vector<IndexEntry>::const_iterator const een = entries.end();
717 // tracks whether we are already inside a main entry (1),
718 // a sub-entry (2), or a sub-sub-entry (3). see below for the
721 // the last one we saw
723 int entry_number = -1;
724 for (; eit != een; ++eit) {
725 Paragraph const & par = eit->dit.innerParagraph();
726 if (entry_number == -1 || !eit->equal(last)) {
727 if (entry_number != -1) {
728 // not the first time through the loop, so
729 // close last entry or entries, depending.
731 // close this sub-sub-entry
732 xs << html::EndTag("li");
734 // is this another sub-sub-entry within the same sub-entry?
735 if (!eit->same_sub(last)) {
737 xs << html::EndTag("ul");
742 // the point of the second test here is that we might get
743 // here two ways: (i) by falling through from above; (ii) because,
744 // though the sub-entry hasn't changed, the sub-sub-entry has,
745 // which means that it is the first sub-sub-entry within this
746 // sub-entry. In that case, we do not want to close anything.
747 if (level == 2 && !eit->same_sub(last)) {
749 xs << html::EndTag("li");
751 // is this another sub-entry with the same main entry?
752 if (!eit->same_main(last)) {
754 xs << html::EndTag("ul");
759 // again, we can get here two ways: from above, or because we have
760 // found the first sub-entry. in the latter case, we do not want to
762 if (level == 1 && !eit->same_main(last)) {
764 xs << html::EndTag("li");
769 // we'll be starting new entries
772 // We need to use our own stream, since we will have to
773 // modify what we get back.
774 odocstringstream ent;
775 XHTMLStream entstream(ent);
776 OutputParams ours = op;
778 par.simpleLyXHTMLOnePar(buffer(), entstream, ours, dummy);
780 // these will contain XHTML versions of the main entry, etc
781 // remember that everything will already have been escaped,
782 // so we'll need to use NextRaw() during output.
786 extractSubentries(ent.str(), main, sub, subsub);
787 parseItem(main, true);
788 parseItem(sub, true);
789 parseItem(subsub, true);
792 // another subsubentry
793 xs << html::StartTag("li", "class='subsubentry'")
794 << XHTMLStream::NextRaw() << subsub;
795 } else if (level == 2) {
796 // there are two ways we can be here:
797 // (i) we can actually be inside a sub-entry already and be about
798 // to output the first sub-sub-entry. in this case, our sub
799 // and the last sub will be the same.
800 // (ii) we can just have closed a sub-entry, possibly after also
801 // closing a list of sub-sub-entries. here our sub and the last
802 // sub are different.
803 // only in the latter case do we need to output the new sub-entry.
804 // note that in this case, too, though, the sub-entry might already
805 // have a sub-sub-entry.
806 if (eit->sub != last.sub)
807 xs << html::StartTag("li", "class='subentry'")
808 << XHTMLStream::NextRaw() << sub;
809 if (!subsub.empty()) {
810 // it's actually a subsubentry, so we need to start that list
812 xs << html::StartTag("ul", "class='subsubentry'")
813 << html::StartTag("li", "class='subsubentry'")
814 << XHTMLStream::NextRaw() << subsub;
818 // there are also two ways we can be here:
819 // (i) we can actually be inside an entry already and be about
820 // to output the first sub-entry. in this case, our main
821 // and the last main will be the same.
822 // (ii) we can just have closed an entry, possibly after also
823 // closing a list of sub-entries. here our main and the last
824 // main are different.
825 // only in the latter case do we need to output the new main entry.
826 // note that in this case, too, though, the main entry might already
827 // have a sub-entry, or even a sub-sub-entry.
828 if (eit->main != last.main)
829 xs << html::StartTag("li", "class='main'") << main;
831 // there's a sub-entry, too
833 xs << html::StartTag("ul", "class='subentry'")
834 << html::StartTag("li", "class='subentry'")
835 << XHTMLStream::NextRaw() << sub;
837 if (!subsub.empty()) {
838 // and a sub-sub-entry
840 xs << html::StartTag("ul", "class='subsubentry'")
841 << html::StartTag("li", "class='subsubentry'")
842 << XHTMLStream::NextRaw() << subsub;
848 // finally, then, we can output the index link itself
849 string const parattr = "href='#" + par.magicLabel() + "'";
850 xs << (entry_number == 0 ? ":" : ",");
851 xs << " " << html::StartTag("a", parattr)
852 << ++entry_number << html::EndTag("a");
855 // now we have to close all the open levels
857 xs << html::EndTag("li") << html::EndTag("ul");
861 xs << html::EndTag("div");