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"
42 using namespace lyx::support;
46 /////////////////////////////////////////////////////////////////////
50 ///////////////////////////////////////////////////////////////////////
53 InsetIndex::InsetIndex(Buffer * buf, InsetIndexParams const & params)
54 : InsetCollapsable(buf), params_(params)
58 int InsetIndex::latex(odocstream & os,
59 OutputParams const & runparams_in) const
61 OutputParams runparams(runparams_in);
62 runparams.inIndexEntry = true;
64 if (buffer().masterBuffer()->params().use_indices && !params_.index.empty()
65 && params_.index != "idx") {
75 // get contents of InsetText as LaTeX and plaintext
76 odocstringstream ourlatex;
77 InsetText::latex(ourlatex, runparams);
78 odocstringstream ourplain;
79 InsetText::plaintext(ourplain, runparams);
80 docstring latexstr = ourlatex.str();
81 docstring plainstr = ourplain.str();
83 // this will get what follows | if anything does
86 // check for the | separator
87 // FIXME This would go wrong on an escaped "|", but
88 // how far do we want to go here?
89 size_t pos = latexstr.find(from_ascii("|"));
90 if (pos != docstring::npos) {
91 // put the bit after "|" into cmd...
92 cmd = latexstr.substr(pos + 1);
93 // ...and erase that stuff from latexstr
94 latexstr = latexstr.erase(pos);
95 // ...and similarly from plainstr
96 size_t ppos = plainstr.find(from_ascii("|"));
97 if (ppos < plainstr.size())
100 LYXERR0("The `|' separator was not found in the plaintext version!");
103 // Separate the entires and subentries, i.e., split on "!"
104 // FIXME This would do the wrong thing with escaped ! characters
105 std::vector<docstring> const levels =
106 getVectorFromString(latexstr, from_ascii("!"), true);
107 std::vector<docstring> const levels_plain =
108 getVectorFromString(plainstr, from_ascii("!"), true);
110 vector<docstring>::const_iterator it = levels.begin();
111 vector<docstring>::const_iterator end = levels.end();
112 vector<docstring>::const_iterator it2 = levels_plain.begin();
114 for (; it != end; ++it) {
115 // write the separator except the first time
121 // correctly sort macros and formatted strings
122 // if we do find a command, prepend a plain text
123 // version of the content to get sorting right,
124 // e.g. \index{LyX@\LyX}, \index{text@\textbf{text}}
125 // Don't do that if the user entered '@' himself, though.
126 if (contains(*it, '\\') && !contains(*it, '@')) {
127 // Plaintext might return nothing (e.g. for ERTs)
128 docstring const spart =
129 (it2 < levels_plain.end() && !(*it2).empty())
131 // Now we need to validate that all characters in
132 // the sorting part are representable in the current
133 // encoding. If not try the LaTeX macro which might
134 // or might not be a good choice, and issue a warning.
136 for (size_t n = 0; n < spart.size(); ++n) {
138 spart2 += runparams.encoding->latexChar(spart[n]);
139 } catch (EncodingException & /* e */) {
140 LYXERR0("Uncodable character in index entry. Sorting might be wrong!");
143 if (spart != spart2 && !runparams.dryrun) {
144 // FIXME: warning should be passed to the error dialog
145 frontend::Alert::warning(_("Index sorting failed"),
146 bformat(_("LyX's automatic index sorting algorithm faced\n"
147 "problems with the entry '%1$s'.\n"
148 "Please specify the sorting of this entry manually, as\n"
149 "explained in the User Guide."), spart));
151 // remove remaining \'s for the sorting part
152 docstring const ppart =
153 subst(spart2, from_ascii("\\"), docstring());
156 i += count_char(ppart, '\n');
158 docstring const tpart = *it;
160 i += count_char(tpart, '\n');
161 if (it2 < levels_plain.end())
164 // write the bit that followed "|"
167 i += count_char(cmd, '\n');
174 int InsetIndex::docbook(odocstream & os, OutputParams const & runparams) const
176 os << "<indexterm><primary>";
177 int const i = InsetText::docbook(os, runparams);
178 os << "</primary></indexterm>";
183 docstring InsetIndex::xhtml(XHTMLStream & xs, OutputParams const &) const
185 // we just print an anchor, taking the paragraph ID from
186 // our own interior paragraph, which doesn't get printed
187 std::string const magic = paragraphs().front().magicLabel();
188 std::string const attr = "id='" + magic + "'";
189 xs << html::CompTag("a", attr);
194 bool InsetIndex::showInsetDialog(BufferView * bv) const
196 bv->showDialog("index", params2string(params_),
197 const_cast<InsetIndex *>(this));
202 void InsetIndex::doDispatch(Cursor & cur, FuncRequest & cmd)
204 switch (cmd.action()) {
206 case LFUN_INSET_MODIFY: {
207 if (cmd.getArg(0) == "changetype") {
208 params_.index = from_utf8(cmd.getArg(1));
211 InsetIndexParams params;
212 InsetIndex::string2params(to_utf8(cmd.argument()), params);
213 params_.index = params.index;
217 case LFUN_INSET_DIALOG_UPDATE:
218 cur.bv().updateDialog("index", params2string(params_));
222 InsetCollapsable::doDispatch(cur, cmd);
228 bool InsetIndex::getStatus(Cursor & cur, FuncRequest const & cmd,
229 FuncStatus & flag) const
231 switch (cmd.action()) {
233 case LFUN_INSET_MODIFY:
234 if (cmd.getArg(0) == "changetype") {
235 docstring const newtype = from_utf8(cmd.getArg(1));
236 Buffer const & realbuffer = *buffer().masterBuffer();
237 IndicesList const & indiceslist = realbuffer.params().indiceslist();
238 Index const * index = indiceslist.findShortcut(newtype);
239 flag.setEnabled(index != 0);
241 from_utf8(cmd.getArg(1)) == params_.index);
244 flag.setEnabled(true);
247 case LFUN_INSET_DIALOG_UPDATE: {
248 Buffer const & realbuffer = *buffer().masterBuffer();
249 flag.setEnabled(realbuffer.params().use_indices);
254 return InsetCollapsable::getStatus(cur, cmd, flag);
259 ColorCode InsetIndex::labelColor() const
261 if (params_.index.empty() || params_.index == from_ascii("idx"))
262 return InsetCollapsable::labelColor();
264 ColorCode c = lcolor.getFromLyXName(to_utf8(params_.index));
266 c = InsetCollapsable::labelColor();
271 docstring InsetIndex::toolTip(BufferView const &, int, int) const
273 docstring tip = _("Index Entry");
274 if (buffer().params().use_indices && !params_.index.empty()) {
275 Buffer const & realbuffer = *buffer().masterBuffer();
276 IndicesList const & indiceslist = realbuffer.params().indiceslist();
278 Index const * index = indiceslist.findShortcut(params_.index);
280 tip += _("unknown type!");
282 tip += index->index();
286 OutputParams rp(&buffer().params().encoding());
287 odocstringstream ods;
288 InsetText::plaintext(ods, rp);
290 return wrapParas(tip);
294 docstring const InsetIndex::buttonLabel(BufferView const & bv) const
296 InsetLayout const & il = getLayout();
297 docstring label = translateIfPossible(il.labelstring());
299 if (buffer().params().use_indices && !params_.index.empty()) {
300 Buffer const & realbuffer = *buffer().masterBuffer();
301 IndicesList const & indiceslist = realbuffer.params().indiceslist();
303 Index const * index = indiceslist.findShortcut(params_.index);
305 label += _("unknown type!");
307 label += index->index();
311 if (!il.contentaslabel() || geometry(bv) != ButtonOnly)
313 return getNewLabel(label);
317 void InsetIndex::write(ostream & os) const
319 os << to_utf8(name());
321 InsetCollapsable::write(os);
325 void InsetIndex::read(Lexer & lex)
328 InsetCollapsable::read(lex);
332 string InsetIndex::params2string(InsetIndexParams const & params)
341 void InsetIndex::string2params(string const & in, InsetIndexParams & params)
343 params = InsetIndexParams();
347 istringstream data(in);
350 lex.setContext("InsetIndex::string2params");
356 void InsetIndex::addToToc(DocIterator const & cpit)
358 DocIterator pit = cpit;
359 pit.push_back(CursorSlice(*this));
360 docstring const item = text().asString(0, 1, AS_STR_LABEL | AS_STR_INSETS);
361 buffer().tocBackend().toc("index").push_back(TocItem(pit, 0, item));
362 // Proceed with the rest of the inset.
363 InsetCollapsable::addToToc(cpit);
367 void InsetIndex::validate(LaTeXFeatures & features) const
369 if (buffer().masterBuffer()->params().use_indices
370 && !params_.index.empty()
371 && params_.index != "idx")
372 features.require("splitidx");
376 docstring InsetIndex::contextMenu(BufferView const &, int, int) const
378 return from_ascii("context-index");
382 bool InsetIndex::hasSettings() const
384 return buffer().masterBuffer()->params().use_indices;
390 /////////////////////////////////////////////////////////////////////
394 ///////////////////////////////////////////////////////////////////////
397 void InsetIndexParams::write(ostream & os) const
401 os << to_utf8(index);
408 void InsetIndexParams::read(Lexer & lex)
411 index = lex.getDocString();
413 index = from_ascii("idx");
417 /////////////////////////////////////////////////////////////////////
421 ///////////////////////////////////////////////////////////////////////
423 InsetPrintIndex::InsetPrintIndex(Buffer * buf, InsetCommandParams const & p)
424 : InsetCommand(buf, p, "index_print")
428 ParamInfo const & InsetPrintIndex::findInfo(string const & /* cmdName */)
430 static ParamInfo param_info_;
431 if (param_info_.empty()) {
432 param_info_.add("type", ParamInfo::LATEX_OPTIONAL);
433 param_info_.add("name", ParamInfo::LATEX_REQUIRED);
439 docstring InsetPrintIndex::screenLabel() const
441 bool const printall = suffixIs(getCmdName(), '*');
442 bool const multind = buffer().masterBuffer()->params().use_indices;
444 && getParam("type") == from_ascii("idx"))
445 || (getParam("type").empty() && !printall))
447 Buffer const & realbuffer = *buffer().masterBuffer();
448 IndicesList const & indiceslist = realbuffer.params().indiceslist();
449 Index const * index = indiceslist.findShortcut(getParam("type"));
450 if (!index && !printall)
451 return _("Unknown index type!");
452 docstring res = printall ? _("All indices") : index->index();
454 res += " (" + _("non-active") + ")";
455 else if (contains(getCmdName(), "printsubindex"))
456 res += " (" + _("subindex") + ")";
461 bool InsetPrintIndex::isCompatibleCommand(string const & s)
463 return s == "printindex" || s == "printsubindex"
464 || s == "printindex*" || s == "printsubindex*";
468 void InsetPrintIndex::doDispatch(Cursor & cur, FuncRequest & cmd)
470 switch (cmd.action()) {
472 case LFUN_INSET_MODIFY: {
473 if (cmd.argument() == from_ascii("toggle-subindex")) {
474 string cmd = getCmdName();
475 if (contains(cmd, "printindex"))
476 cmd = subst(cmd, "printindex", "printsubindex");
478 cmd = subst(cmd, "printsubindex", "printindex");
481 } else if (cmd.argument() == from_ascii("check-printindex*")) {
482 string cmd = getCmdName();
483 if (suffixIs(cmd, '*'))
486 setParam("type", docstring());
490 InsetCommandParams p(INDEX_PRINT_CODE);
492 InsetCommand::string2params("index_print",
493 to_utf8(cmd.argument()), p);
494 if (p.getCmdName().empty()) {
503 InsetCommand::doDispatch(cur, cmd);
509 bool InsetPrintIndex::getStatus(Cursor & cur, FuncRequest const & cmd,
510 FuncStatus & status) const
512 switch (cmd.action()) {
514 case LFUN_INSET_MODIFY: {
515 if (cmd.argument() == from_ascii("toggle-subindex")) {
516 status.setEnabled(buffer().masterBuffer()->params().use_indices);
517 status.setOnOff(contains(getCmdName(), "printsubindex"));
519 } else if (cmd.argument() == from_ascii("check-printindex*")) {
520 status.setEnabled(buffer().masterBuffer()->params().use_indices);
521 status.setOnOff(suffixIs(getCmdName(), '*'));
523 } if (cmd.getArg(0) == "index_print"
524 && cmd.getArg(1) == "CommandInset") {
525 InsetCommandParams p(INDEX_PRINT_CODE);
526 InsetCommand::string2params("index_print",
527 to_utf8(cmd.argument()), p);
528 if (suffixIs(p.getCmdName(), '*')) {
529 status.setEnabled(true);
530 status.setOnOff(false);
533 Buffer const & realbuffer = *buffer().masterBuffer();
534 IndicesList const & indiceslist =
535 realbuffer.params().indiceslist();
536 Index const * index = indiceslist.findShortcut(p["type"]);
537 status.setEnabled(index != 0);
538 status.setOnOff(p["type"] == getParam("type"));
541 return InsetCommand::getStatus(cur, cmd, status);
544 case LFUN_INSET_DIALOG_UPDATE: {
545 status.setEnabled(buffer().masterBuffer()->params().use_indices);
550 return InsetCommand::getStatus(cur, cmd, status);
555 int InsetPrintIndex::latex(odocstream & os, OutputParams const & runparams_in) const
557 if (!buffer().masterBuffer()->params().use_indices) {
558 if (getParam("type") == from_ascii("idx"))
559 os << "\\printindex{}";
562 OutputParams runparams = runparams_in;
563 os << getCommand(runparams);
568 void InsetPrintIndex::validate(LaTeXFeatures & features) const
570 features.require("makeidx");
571 if (buffer().masterBuffer()->params().use_indices)
572 features.require("splitidx");
576 docstring InsetPrintIndex::contextMenu(BufferView const &, int, int) const
578 return buffer().masterBuffer()->params().use_indices ?
579 from_ascii("context-indexprint") : docstring();
583 bool InsetPrintIndex::hasSettings() const
585 return buffer().masterBuffer()->params().use_indices;
591 void parseItem(docstring & s, bool for_output)
593 // this does not yet check for escaped things
594 size_type loc = s.find(from_ascii("@"));
595 if (loc != string::npos) {
601 loc = s.find(from_ascii("|"));
602 if (loc != string::npos)
607 void extractSubentries(docstring const & entry, docstring & main,
608 docstring & sub1, docstring & sub2)
612 size_type const loc = entry.find(from_ascii(" ! "));
613 if (loc == string::npos)
616 main = trim(entry.substr(0, loc));
617 size_t const locend = loc + 3;
618 size_type const loc2 = entry.find(from_ascii(" ! "), locend);
619 if (loc2 == string::npos) {
620 sub1 = trim(entry.substr(locend));
622 sub1 = trim(entry.substr(locend, loc2 - locend));
623 sub2 = trim(entry.substr(loc2 + 3));
634 IndexEntry(docstring const & s, DocIterator const & d)
637 extractSubentries(s, main, sub, subsub);
638 parseItem(main, false);
639 parseItem(sub, false);
640 parseItem(subsub, false);
643 bool equal(IndexEntry const & rhs) const
645 return main == rhs.main && sub == rhs.sub && subsub == rhs.subsub;
648 bool same_sub(IndexEntry const & rhs) const
650 return main == rhs.main && sub == rhs.sub;
653 bool same_main(IndexEntry const & rhs) const
655 return main == rhs.main;
664 bool operator<(IndexEntry const & lhs, IndexEntry const & rhs)
666 return lhs.main < rhs.main
667 || (lhs.main == rhs.main && lhs.sub < rhs.sub)
668 || (lhs.main == rhs.main && lhs.sub == rhs.sub && lhs.subsub < rhs.subsub);
674 docstring InsetPrintIndex::xhtml(XHTMLStream &, OutputParams const & op) const
676 BufferParams const & bp = buffer().masterBuffer()->params();
678 // we do not presently support multiple indices, so we refuse to print
679 // anything but the main index, so as not to generate multiple indices.
680 // NOTE Multiple index support would require some work. The reason
681 // is that the TOC does not know about multiple indices. Either it would
682 // need to be told about them (not a bad idea), or else the index entries
683 // would need to be collected differently, say, during validation.
684 if (bp.use_indices && getParam("type") != from_ascii("idx"))
687 Toc const & toc = buffer().tocBackend().toc("index");
691 // Collection the index entries in a form we can use them.
692 Toc::const_iterator it = toc.begin();
693 Toc::const_iterator const en = toc.end();
694 vector<IndexEntry> entries;
695 for (; it != en; ++it)
696 entries.push_back(IndexEntry(it->str(), it->dit()));
697 stable_sort(entries.begin(), entries.end());
699 Layout const & lay = bp.documentClass().htmlTOCLayout();
700 string const & tocclass = lay.defaultCSSClass();
701 string const tocattr = "class='tochead " + tocclass + "'";
703 // we'll use our own stream, because we are going to defer everything.
704 // that's how we deal with the fact that we're probably inside a standard
705 // paragraph, and we don't want to be.
706 odocstringstream ods;
709 xs << html::StartTag("div", "class='index'");
710 xs << html::StartTag(lay.htmltag(), lay.htmlattr())
712 << html::EndTag(lay.htmltag());
713 xs << html::StartTag("ul", "class='main'");
716 vector<IndexEntry>::const_iterator eit = entries.begin();
717 vector<IndexEntry>::const_iterator const een = entries.end();
718 // tracks whether we are already inside a main entry (1),
719 // a sub-entry (2), or a sub-sub-entry (3). see below for the
722 // the last one we saw
724 int entry_number = -1;
725 for (; eit != een; ++eit) {
726 Paragraph const & par = eit->dit.innerParagraph();
727 if (entry_number == -1 || !eit->equal(last)) {
728 if (entry_number != -1) {
729 // not the first time through the loop, so
730 // close last entry or entries, depending.
732 // close this sub-sub-entry
733 xs << html::EndTag("li");
735 // is this another sub-sub-entry within the same sub-entry?
736 if (!eit->same_sub(last)) {
738 xs << html::EndTag("ul");
743 // the point of the second test here is that we might get
744 // here two ways: (i) by falling through from above; (ii) because,
745 // though the sub-entry hasn't changed, the sub-sub-entry has,
746 // which means that it is the first sub-sub-entry within this
747 // sub-entry. In that case, we do not want to close anything.
748 if (level == 2 && !eit->same_sub(last)) {
750 xs << html::EndTag("li");
752 // is this another sub-entry with the same main entry?
753 if (!eit->same_main(last)) {
755 xs << html::EndTag("ul");
760 // again, we can get here two ways: from above, or because we have
761 // found the first sub-entry. in the latter case, we do not want to
763 if (level == 1 && !eit->same_main(last)) {
765 xs << html::EndTag("li");
770 // we'll be starting new entries
773 // We need to use our own stream, since we will have to
774 // modify what we get back.
775 odocstringstream ent;
776 XHTMLStream entstream(ent);
777 OutputParams ours = op;
779 par.simpleLyXHTMLOnePar(buffer(), entstream, ours, dummy);
781 // these will contain XHTML versions of the main entry, etc
782 // remember that everything will already have been escaped,
783 // so we'll need to use NextRaw() during output.
787 extractSubentries(ent.str(), main, sub, subsub);
788 parseItem(main, true);
789 parseItem(sub, true);
790 parseItem(subsub, true);
793 // another subsubentry
794 xs << html::StartTag("li", "class='subsubentry'")
795 << XHTMLStream::NextRaw() << subsub;
796 } else if (level == 2) {
797 // there are two ways we can be here:
798 // (i) we can actually be inside a sub-entry already and be about
799 // to output the first sub-sub-entry. in this case, our sub
800 // and the last sub will be the same.
801 // (ii) we can just have closed a sub-entry, possibly after also
802 // closing a list of sub-sub-entries. here our sub and the last
803 // sub are different.
804 // only in the latter case do we need to output the new sub-entry.
805 // note that in this case, too, though, the sub-entry might already
806 // have a sub-sub-entry.
807 if (eit->sub != last.sub)
808 xs << html::StartTag("li", "class='subentry'")
809 << XHTMLStream::NextRaw() << sub;
810 if (!subsub.empty()) {
811 // it's actually a subsubentry, so we need to start that list
813 xs << html::StartTag("ul", "class='subsubentry'")
814 << html::StartTag("li", "class='subsubentry'")
815 << XHTMLStream::NextRaw() << subsub;
819 // there are also two ways we can be here:
820 // (i) we can actually be inside an entry already and be about
821 // to output the first sub-entry. in this case, our main
822 // and the last main will be the same.
823 // (ii) we can just have closed an entry, possibly after also
824 // closing a list of sub-entries. here our main and the last
825 // main are different.
826 // only in the latter case do we need to output the new main entry.
827 // note that in this case, too, though, the main entry might already
828 // have a sub-entry, or even a sub-sub-entry.
829 if (eit->main != last.main)
830 xs << html::StartTag("li", "class='main'") << main;
832 // there's a sub-entry, too
834 xs << html::StartTag("ul", "class='subentry'")
835 << html::StartTag("li", "class='subentry'")
836 << XHTMLStream::NextRaw() << sub;
838 if (!subsub.empty()) {
839 // and a sub-sub-entry
841 xs << html::StartTag("ul", "class='subsubentry'")
842 << html::StartTag("li", "class='subsubentry'")
843 << XHTMLStream::NextRaw() << subsub;
849 // finally, then, we can output the index link itself
850 string const parattr = "href='#" + par.magicLabel() + "'";
851 xs << (entry_number == 0 ? ":" : ",");
852 xs << " " << html::StartTag("a", parattr)
853 << ++entry_number << html::EndTag("a");
856 // now we have to close all the open levels
858 xs << html::EndTag("li") << html::EndTag("ul");
862 xs << html::EndTag("div");