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());
156 docstring const tpart = *it;
158 if (it2 < levels_plain.end())
161 // write the bit that followed "|"
169 int InsetIndex::docbook(odocstream & os, OutputParams const & runparams) const
171 os << "<indexterm><primary>";
172 int const i = InsetText::docbook(os, runparams);
173 os << "</primary></indexterm>";
178 docstring InsetIndex::xhtml(XHTMLStream & xs, OutputParams const &) const
180 // we just print an anchor, taking the paragraph ID from
181 // our own interior paragraph, which doesn't get printed
182 std::string const magic = paragraphs().front().magicLabel();
183 std::string const attr = "id='" + magic + "'";
184 xs << html::CompTag("a", attr);
189 bool InsetIndex::showInsetDialog(BufferView * bv) const
191 bv->showDialog("index", params2string(params_),
192 const_cast<InsetIndex *>(this));
197 void InsetIndex::doDispatch(Cursor & cur, FuncRequest & cmd)
199 switch (cmd.action) {
201 case LFUN_INSET_MODIFY: {
202 if (cmd.getArg(0) == "changetype") {
203 params_.index = from_utf8(cmd.getArg(1));
206 InsetIndexParams params;
207 InsetIndex::string2params(to_utf8(cmd.argument()), params);
208 params_.index = params.index;
212 case LFUN_INSET_DIALOG_UPDATE:
213 cur.bv().updateDialog("index", params2string(params_));
217 InsetCollapsable::doDispatch(cur, cmd);
223 bool InsetIndex::getStatus(Cursor & cur, FuncRequest const & cmd,
224 FuncStatus & flag) const
226 switch (cmd.action) {
228 case LFUN_INSET_MODIFY:
229 if (cmd.getArg(0) == "changetype") {
230 docstring const newtype = from_utf8(cmd.getArg(1));
231 Buffer const & realbuffer = *buffer().masterBuffer();
232 IndicesList const & indiceslist = realbuffer.params().indiceslist();
233 Index const * index = indiceslist.findShortcut(newtype);
234 flag.setEnabled(index != 0);
236 from_utf8(cmd.getArg(1)) == params_.index);
239 flag.setEnabled(true);
242 case LFUN_INSET_DIALOG_UPDATE: {
243 Buffer const & realbuffer = *buffer().masterBuffer();
244 flag.setEnabled(realbuffer.params().use_indices);
249 return InsetCollapsable::getStatus(cur, cmd, flag);
254 ColorCode InsetIndex::labelColor() const
256 if (params_.index.empty() || params_.index == from_ascii("idx"))
257 return InsetCollapsable::labelColor();
259 ColorCode c = lcolor.getFromLyXName(to_utf8(params_.index));
261 c = InsetCollapsable::labelColor();
266 docstring InsetIndex::toolTip(BufferView const &, int, int) const
268 docstring tip = _("Index Entry");
269 if (buffer().params().use_indices && !params_.index.empty()) {
270 Buffer const & realbuffer = *buffer().masterBuffer();
271 IndicesList const & indiceslist = realbuffer.params().indiceslist();
273 Index const * index = indiceslist.findShortcut(params_.index);
275 tip += _("unknown type!");
277 tip += index->index();
281 OutputParams rp(&buffer().params().encoding());
282 odocstringstream ods;
283 InsetText::plaintext(ods, rp);
285 return wrapParas(tip);
289 docstring const InsetIndex::buttonLabel(BufferView const & bv) const
291 InsetLayout const & il = getLayout();
292 docstring label = translateIfPossible(il.labelstring());
294 if (buffer().params().use_indices && !params_.index.empty()) {
295 Buffer const & realbuffer = *buffer().masterBuffer();
296 IndicesList const & indiceslist = realbuffer.params().indiceslist();
298 Index const * index = indiceslist.findShortcut(params_.index);
300 label += _("unknown type!");
302 label += index->index();
306 if (!il.contentaslabel() || geometry(bv) != ButtonOnly)
308 return getNewLabel(label);
312 void InsetIndex::write(ostream & os) const
314 os << to_utf8(name());
316 InsetCollapsable::write(os);
320 void InsetIndex::read(Lexer & lex)
323 InsetCollapsable::read(lex);
327 string InsetIndex::params2string(InsetIndexParams const & params)
336 void InsetIndex::string2params(string const & in, InsetIndexParams & params)
338 params = InsetIndexParams();
342 istringstream data(in);
345 lex.setContext("InsetIndex::string2params");
351 void InsetIndex::addToToc(DocIterator const & cpit)
353 DocIterator pit = cpit;
354 pit.push_back(CursorSlice(*this));
355 docstring const item = text().asString(0, 1, AS_STR_LABEL | AS_STR_INSETS);
356 buffer().tocBackend().toc("index").push_back(TocItem(pit, 0, item));
357 // Proceed with the rest of the inset.
358 InsetCollapsable::addToToc(cpit);
362 void InsetIndex::validate(LaTeXFeatures & features) const
364 if (buffer().masterBuffer()->params().use_indices
365 && !params_.index.empty()
366 && params_.index != "idx")
367 features.require("splitidx");
371 docstring InsetIndex::contextMenu(BufferView const &, int, int) const
373 return from_ascii("context-index");
377 bool InsetIndex::hasSettings() const
379 return buffer().masterBuffer()->params().use_indices;
385 /////////////////////////////////////////////////////////////////////
389 ///////////////////////////////////////////////////////////////////////
392 void InsetIndexParams::write(ostream & os) const
396 os << to_utf8(index);
403 void InsetIndexParams::read(Lexer & lex)
406 index = lex.getDocString();
408 index = from_ascii("idx");
412 /////////////////////////////////////////////////////////////////////
416 ///////////////////////////////////////////////////////////////////////
418 InsetPrintIndex::InsetPrintIndex(Buffer * buf, InsetCommandParams const & p)
419 : InsetCommand(buf, p, "index_print")
423 ParamInfo const & InsetPrintIndex::findInfo(string const & /* cmdName */)
425 static ParamInfo param_info_;
426 if (param_info_.empty()) {
427 param_info_.add("type", ParamInfo::LATEX_OPTIONAL);
428 param_info_.add("name", ParamInfo::LATEX_REQUIRED);
434 docstring InsetPrintIndex::screenLabel() const
436 bool const printall = suffixIs(getCmdName(), '*');
437 bool const multind = buffer().masterBuffer()->params().use_indices;
439 && getParam("type") == from_ascii("idx"))
440 || (getParam("type").empty() && !printall))
442 Buffer const & realbuffer = *buffer().masterBuffer();
443 IndicesList const & indiceslist = realbuffer.params().indiceslist();
444 Index const * index = indiceslist.findShortcut(getParam("type"));
445 if (!index && !printall)
446 return _("Unknown index type!");
447 docstring res = printall ? _("All indices") : index->index();
449 res += " (" + _("non-active") + ")";
450 else if (contains(getCmdName(), "printsubindex"))
451 res += " (" + _("subindex") + ")";
456 bool InsetPrintIndex::isCompatibleCommand(string const & s)
458 return s == "printindex" || s == "printsubindex"
459 || s == "printindex*" || s == "printsubindex*";
463 void InsetPrintIndex::doDispatch(Cursor & cur, FuncRequest & cmd)
465 switch (cmd.action) {
467 case LFUN_INSET_MODIFY: {
468 if (cmd.argument() == from_ascii("toggle-subindex")) {
469 string cmd = getCmdName();
470 if (contains(cmd, "printindex"))
471 cmd = subst(cmd, "printindex", "printsubindex");
473 cmd = subst(cmd, "printsubindex", "printindex");
476 } else if (cmd.argument() == from_ascii("check-printindex*")) {
477 string cmd = getCmdName();
478 if (suffixIs(cmd, '*'))
481 setParam("type", docstring());
485 InsetCommandParams p(INDEX_PRINT_CODE);
487 InsetCommand::string2params("index_print",
488 to_utf8(cmd.argument()), p);
489 if (p.getCmdName().empty()) {
498 InsetCommand::doDispatch(cur, cmd);
504 bool InsetPrintIndex::getStatus(Cursor & cur, FuncRequest const & cmd,
505 FuncStatus & status) const
507 switch (cmd.action) {
509 case LFUN_INSET_MODIFY: {
510 if (cmd.argument() == from_ascii("toggle-subindex")) {
511 status.setEnabled(buffer().masterBuffer()->params().use_indices);
512 status.setOnOff(contains(getCmdName(), "printsubindex"));
514 } else if (cmd.argument() == from_ascii("check-printindex*")) {
515 status.setEnabled(buffer().masterBuffer()->params().use_indices);
516 status.setOnOff(suffixIs(getCmdName(), '*'));
518 } if (cmd.getArg(0) == "index_print"
519 && cmd.getArg(1) == "CommandInset") {
520 InsetCommandParams p(INDEX_PRINT_CODE);
521 InsetCommand::string2params("index_print",
522 to_utf8(cmd.argument()), p);
523 if (suffixIs(p.getCmdName(), '*')) {
524 status.setEnabled(true);
525 status.setOnOff(false);
528 Buffer const & realbuffer = *buffer().masterBuffer();
529 IndicesList const & indiceslist =
530 realbuffer.params().indiceslist();
531 Index const * index = indiceslist.findShortcut(p["type"]);
532 status.setEnabled(index != 0);
533 status.setOnOff(p["type"] == getParam("type"));
536 return InsetCommand::getStatus(cur, cmd, status);
539 case LFUN_INSET_DIALOG_UPDATE: {
540 status.setEnabled(buffer().masterBuffer()->params().use_indices);
545 return InsetCommand::getStatus(cur, cmd, status);
550 int InsetPrintIndex::latex(odocstream & os, OutputParams const & runparams_in) const
552 if (!buffer().masterBuffer()->params().use_indices) {
553 if (getParam("type") == from_ascii("idx"))
554 os << "\\printindex{}";
557 OutputParams runparams = runparams_in;
558 os << getCommand(runparams);
563 void InsetPrintIndex::validate(LaTeXFeatures & features) const
565 features.require("makeidx");
566 if (buffer().masterBuffer()->params().use_indices)
567 features.require("splitidx");
571 docstring InsetPrintIndex::contextMenu(BufferView const &, int, int) const
573 return buffer().masterBuffer()->params().use_indices ?
574 from_ascii("context-indexprint") : docstring();
578 bool InsetPrintIndex::hasSettings() const
580 return buffer().masterBuffer()->params().use_indices;
586 void parseItem(docstring & s, bool for_output)
588 // this does not yet check for escaped things
589 size_type loc = s.find(from_ascii("@"));
590 if (loc != string::npos) {
596 loc = s.find(from_ascii("|"));
597 if (loc != string::npos)
602 void extractSubentries(docstring const & entry, docstring & main,
603 docstring & sub1, docstring & sub2)
607 size_type const loc = entry.find(from_ascii(" ! "));
608 if (loc == string::npos)
611 main = trim(entry.substr(0, loc));
612 size_t const locend = loc + 3;
613 size_type const loc2 = entry.find(from_ascii(" ! "), locend);
614 if (loc2 == string::npos) {
615 sub1 = trim(entry.substr(locend));
617 sub1 = trim(entry.substr(locend, loc2 - locend));
618 sub2 = trim(entry.substr(loc2 + 3));
629 IndexEntry(docstring const & s, DocIterator const & d)
632 extractSubentries(s, main, sub, subsub);
633 parseItem(main, false);
634 parseItem(sub, false);
635 parseItem(subsub, false);
638 bool equal(IndexEntry const & rhs) const
640 return main == rhs.main && sub == rhs.sub && subsub == rhs.subsub;
643 bool same_sub(IndexEntry const & rhs) const
645 return main == rhs.main && sub == rhs.sub;
648 bool same_main(IndexEntry const & rhs) const
650 return main == rhs.main;
659 bool operator<(IndexEntry const & lhs, IndexEntry const & rhs)
661 return lhs.main < rhs.main
662 || (lhs.main == rhs.main && lhs.sub < rhs.sub)
663 || (lhs.main == rhs.main && lhs.sub == rhs.sub && lhs.subsub < rhs.subsub);
669 docstring InsetPrintIndex::xhtml(XHTMLStream &, OutputParams const & op) const
671 BufferParams const & bp = buffer().masterBuffer()->params();
673 // we do not presently support multiple indices, so we refuse to print
674 // anything but the main index, so as not to generate multiple indices.
675 // NOTE Multiple index support would require some work. The reason
676 // is that the TOC does not know about multiple indices. Either it would
677 // need to be told about them (not a bad idea), or else the index entries
678 // would need to be collected differently, say, during validation.
679 if (bp.use_indices && getParam("type") != from_ascii("idx"))
682 Toc const & toc = buffer().tocBackend().toc("index");
686 // Collection the index entries in a form we can use them.
687 Toc::const_iterator it = toc.begin();
688 Toc::const_iterator const en = toc.end();
689 vector<IndexEntry> entries;
690 for (; it != en; ++it)
691 entries.push_back(IndexEntry(it->str(), it->dit()));
692 stable_sort(entries.begin(), entries.end());
694 Layout const & lay = bp.documentClass().htmlTOCLayout();
695 string const & tocclass = lay.defaultCSSClass();
696 string const tocattr = "class='tochead " + tocclass + "'";
698 // we'll use our own stream, because we are going to defer everything.
699 // that's how we deal with the fact that we're probably inside a standard
700 // paragraph, and we don't want to be.
701 odocstringstream ods;
704 xs << html::StartTag("div", "class='index'");
705 xs << html::StartTag(lay.htmltag(), lay.htmlattr())
707 << html::EndTag(lay.htmltag());
708 xs << html::StartTag("ul", "class='main'");
711 vector<IndexEntry>::const_iterator eit = entries.begin();
712 vector<IndexEntry>::const_iterator const een = entries.end();
713 // tracks whether we are already inside a main entry (1),
714 // a sub-entry (2), or a sub-sub-entry (3). see below for the
717 // the last one we saw
719 int entry_number = -1;
720 for (; eit != een; ++eit) {
721 Paragraph const & par = eit->dit.innerParagraph();
722 if (entry_number == -1 || !eit->equal(last)) {
723 if (entry_number != -1) {
724 // not the first time through the loop, so
725 // close last entry or entries, depending.
727 // close this sub-sub-entry
728 xs << html::EndTag("li");
730 // is this another sub-sub-entry within the same sub-entry?
731 if (!eit->same_sub(last)) {
733 xs << html::EndTag("ul");
738 // the point of the second test here is that we might get
739 // here two ways: (i) by falling through from above; (ii) because,
740 // though the sub-entry hasn't changed, the sub-sub-entry has,
741 // which means that it is the first sub-sub-entry within this
742 // sub-entry. In that case, we do not want to close anything.
743 if (level == 2 && !eit->same_sub(last)) {
745 xs << html::EndTag("li");
747 // is this another sub-entry with the same main entry?
748 if (!eit->same_main(last)) {
750 xs << html::EndTag("ul");
755 // again, we can get here two ways: from above, or because we have
756 // found the first sub-entry. in the latter case, we do not want to
758 if (level == 1 && !eit->same_main(last)) {
760 xs << html::EndTag("li");
765 // we'll be starting new entries
768 // We need to use our own stream, since we will have to
769 // modify what we get back.
770 odocstringstream ent;
771 XHTMLStream entstream(ent);
772 OutputParams ours = op;
774 par.simpleLyXHTMLOnePar(buffer(), entstream, ours, dummy);
776 // these will contain XHTML versions of the main entry, etc
777 // remember that everything will already have been escaped,
778 // so we'll need to use NextRaw() during output.
782 extractSubentries(ent.str(), main, sub, subsub);
783 parseItem(main, true);
784 parseItem(sub, true);
785 parseItem(subsub, true);
788 // another subsubentry
789 xs << html::StartTag("li", "class='subsubentry'")
790 << XHTMLStream::NextRaw() << subsub;
791 } else if (level == 2) {
792 // there are two ways we can be here:
793 // (i) we can actually be inside a sub-entry already and be about
794 // to output the first sub-sub-entry. in this case, our sub
795 // and the last sub will be the same.
796 // (ii) we can just have closed a sub-entry, possibly after also
797 // closing a list of sub-sub-entries. here our sub and the last
798 // sub are different.
799 // only in the latter case do we need to output the new sub-entry.
800 // note that in this case, too, though, the sub-entry might already
801 // have a sub-sub-entry.
802 if (eit->sub != last.sub)
803 xs << html::StartTag("li", "class='subentry'")
804 << XHTMLStream::NextRaw() << sub;
805 if (!subsub.empty()) {
806 // it's actually a subsubentry, so we need to start that list
808 xs << html::StartTag("ul", "class='subsubentry'")
809 << html::StartTag("li", "class='subsubentry'")
810 << XHTMLStream::NextRaw() << subsub;
814 // there are also two ways we can be here:
815 // (i) we can actually be inside an entry already and be about
816 // to output the first sub-entry. in this case, our main
817 // and the last main will be the same.
818 // (ii) we can just have closed an entry, possibly after also
819 // closing a list of sub-entries. here our main and the last
820 // main are different.
821 // only in the latter case do we need to output the new main entry.
822 // note that in this case, too, though, the main entry might already
823 // have a sub-entry, or even a sub-sub-entry.
824 if (eit->main != last.main)
825 xs << html::StartTag("li", "class='main'") << main;
827 // there's a sub-entry, too
829 xs << html::StartTag("ul", "class='subentry'")
830 << html::StartTag("li", "class='subentry'")
831 << XHTMLStream::NextRaw() << sub;
833 if (!subsub.empty()) {
834 // and a sub-sub-entry
836 xs << html::StartTag("ul", "class='subsubentry'")
837 << html::StartTag("li", "class='subsubentry'")
838 << XHTMLStream::NextRaw() << subsub;
844 // finally, then, we can output the index link itself
845 string const parattr = "href='#" + par.magicLabel() + "'";
846 xs << (entry_number == 0 ? ":" : ",");
847 xs << " " << html::StartTag("a", parattr)
848 << ++entry_number << html::EndTag("a");
851 // now we have to close all the open levels
853 xs << html::EndTag("li") << html::EndTag("ul");
857 xs << html::EndTag("div");