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;
214 // what we really want here is a TOC update, but that means
215 // a full buffer update
216 cur.forceBufferUpdate();
220 case LFUN_INSET_DIALOG_UPDATE:
221 cur.bv().updateDialog("index", params2string(params_));
225 InsetCollapsable::doDispatch(cur, cmd);
231 bool InsetIndex::getStatus(Cursor & cur, FuncRequest const & cmd,
232 FuncStatus & flag) const
234 switch (cmd.action()) {
236 case LFUN_INSET_MODIFY:
237 if (cmd.getArg(0) == "changetype") {
238 docstring const newtype = from_utf8(cmd.getArg(1));
239 Buffer const & realbuffer = *buffer().masterBuffer();
240 IndicesList const & indiceslist = realbuffer.params().indiceslist();
241 Index const * index = indiceslist.findShortcut(newtype);
242 flag.setEnabled(index != 0);
244 from_utf8(cmd.getArg(1)) == params_.index);
247 flag.setEnabled(true);
250 case LFUN_INSET_DIALOG_UPDATE: {
251 Buffer const & realbuffer = *buffer().masterBuffer();
252 flag.setEnabled(realbuffer.params().use_indices);
257 return InsetCollapsable::getStatus(cur, cmd, flag);
262 ColorCode InsetIndex::labelColor() const
264 if (params_.index.empty() || params_.index == from_ascii("idx"))
265 return InsetCollapsable::labelColor();
267 ColorCode c = lcolor.getFromLyXName(to_utf8(params_.index));
269 c = InsetCollapsable::labelColor();
274 docstring InsetIndex::toolTip(BufferView const &, int, int) const
276 docstring tip = _("Index Entry");
277 if (buffer().params().use_indices && !params_.index.empty()) {
278 Buffer const & realbuffer = *buffer().masterBuffer();
279 IndicesList const & indiceslist = realbuffer.params().indiceslist();
281 Index const * index = indiceslist.findShortcut(params_.index);
283 tip += _("unknown type!");
285 tip += index->index();
289 OutputParams rp(&buffer().params().encoding());
290 odocstringstream ods;
291 InsetText::plaintext(ods, rp);
293 return wrapParas(tip);
297 docstring const InsetIndex::buttonLabel(BufferView const & bv) const
299 InsetLayout const & il = getLayout();
300 docstring label = translateIfPossible(il.labelstring());
302 if (buffer().params().use_indices && !params_.index.empty()) {
303 Buffer const & realbuffer = *buffer().masterBuffer();
304 IndicesList const & indiceslist = realbuffer.params().indiceslist();
306 Index const * index = indiceslist.findShortcut(params_.index);
308 label += _("unknown type!");
310 label += index->index();
314 if (!il.contentaslabel() || geometry(bv) != ButtonOnly)
316 return getNewLabel(label);
320 void InsetIndex::write(ostream & os) const
322 os << to_utf8(name());
324 InsetCollapsable::write(os);
328 void InsetIndex::read(Lexer & lex)
331 InsetCollapsable::read(lex);
335 string InsetIndex::params2string(InsetIndexParams const & params)
344 void InsetIndex::string2params(string const & in, InsetIndexParams & params)
346 params = InsetIndexParams();
350 istringstream data(in);
353 lex.setContext("InsetIndex::string2params");
359 void InsetIndex::addToToc(DocIterator const & cpit)
361 DocIterator pit = cpit;
362 pit.push_back(CursorSlice(*this));
363 docstring const item = text().asString(0, 1, AS_STR_LABEL | AS_STR_INSETS);
364 buffer().tocBackend().toc("index").push_back(TocItem(pit, 0, item));
365 // Proceed with the rest of the inset.
366 InsetCollapsable::addToToc(cpit);
370 void InsetIndex::validate(LaTeXFeatures & features) const
372 if (buffer().masterBuffer()->params().use_indices
373 && !params_.index.empty()
374 && params_.index != "idx")
375 features.require("splitidx");
376 InsetCollapsable::validate(features);
380 docstring InsetIndex::contextMenu(BufferView const &, int, int) const
382 return from_ascii("context-index");
386 bool InsetIndex::hasSettings() const
388 return buffer().masterBuffer()->params().use_indices;
394 /////////////////////////////////////////////////////////////////////
398 ///////////////////////////////////////////////////////////////////////
401 void InsetIndexParams::write(ostream & os) const
405 os << to_utf8(index);
412 void InsetIndexParams::read(Lexer & lex)
415 index = lex.getDocString();
417 index = from_ascii("idx");
421 /////////////////////////////////////////////////////////////////////
425 ///////////////////////////////////////////////////////////////////////
427 InsetPrintIndex::InsetPrintIndex(Buffer * buf, InsetCommandParams const & p)
428 : InsetCommand(buf, p)
432 ParamInfo const & InsetPrintIndex::findInfo(string const & /* cmdName */)
434 static ParamInfo param_info_;
435 if (param_info_.empty()) {
436 param_info_.add("type", ParamInfo::LATEX_OPTIONAL);
437 param_info_.add("name", ParamInfo::LATEX_REQUIRED);
443 docstring InsetPrintIndex::screenLabel() const
445 bool const printall = suffixIs(getCmdName(), '*');
446 bool const multind = buffer().masterBuffer()->params().use_indices;
448 && getParam("type") == from_ascii("idx"))
449 || (getParam("type").empty() && !printall))
451 Buffer const & realbuffer = *buffer().masterBuffer();
452 IndicesList const & indiceslist = realbuffer.params().indiceslist();
453 Index const * index = indiceslist.findShortcut(getParam("type"));
454 if (!index && !printall)
455 return _("Unknown index type!");
456 docstring res = printall ? _("All indices") : index->index();
458 res += " (" + _("non-active") + ")";
459 else if (contains(getCmdName(), "printsubindex"))
460 res += " (" + _("subindex") + ")";
465 bool InsetPrintIndex::isCompatibleCommand(string const & s)
467 return s == "printindex" || s == "printsubindex"
468 || s == "printindex*" || s == "printsubindex*";
472 void InsetPrintIndex::doDispatch(Cursor & cur, FuncRequest & cmd)
474 switch (cmd.action()) {
476 case LFUN_INSET_MODIFY: {
477 if (cmd.argument() == from_ascii("toggle-subindex")) {
478 string cmd = getCmdName();
479 if (contains(cmd, "printindex"))
480 cmd = subst(cmd, "printindex", "printsubindex");
482 cmd = subst(cmd, "printsubindex", "printindex");
485 } else if (cmd.argument() == from_ascii("check-printindex*")) {
486 string cmd = getCmdName();
487 if (suffixIs(cmd, '*'))
490 setParam("type", docstring());
494 InsetCommandParams p(INDEX_PRINT_CODE);
496 InsetCommand::string2params(to_utf8(cmd.argument()), p);
497 if (p.getCmdName().empty()) {
498 cur.noScreenUpdate();
506 InsetCommand::doDispatch(cur, cmd);
512 bool InsetPrintIndex::getStatus(Cursor & cur, FuncRequest const & cmd,
513 FuncStatus & status) const
515 switch (cmd.action()) {
517 case LFUN_INSET_MODIFY: {
518 if (cmd.argument() == from_ascii("toggle-subindex")) {
519 status.setEnabled(buffer().masterBuffer()->params().use_indices);
520 status.setOnOff(contains(getCmdName(), "printsubindex"));
522 } else if (cmd.argument() == from_ascii("check-printindex*")) {
523 status.setEnabled(buffer().masterBuffer()->params().use_indices);
524 status.setOnOff(suffixIs(getCmdName(), '*'));
526 } if (cmd.getArg(0) == "index_print"
527 && cmd.getArg(1) == "CommandInset") {
528 InsetCommandParams p(INDEX_PRINT_CODE);
529 InsetCommand::string2params(to_utf8(cmd.argument()), p);
530 if (suffixIs(p.getCmdName(), '*')) {
531 status.setEnabled(true);
532 status.setOnOff(false);
535 Buffer const & realbuffer = *buffer().masterBuffer();
536 IndicesList const & indiceslist =
537 realbuffer.params().indiceslist();
538 Index const * index = indiceslist.findShortcut(p["type"]);
539 status.setEnabled(index != 0);
540 status.setOnOff(p["type"] == getParam("type"));
543 return InsetCommand::getStatus(cur, cmd, status);
546 case LFUN_INSET_DIALOG_UPDATE: {
547 status.setEnabled(buffer().masterBuffer()->params().use_indices);
552 return InsetCommand::getStatus(cur, cmd, status);
557 int InsetPrintIndex::latex(odocstream & os, OutputParams const & runparams_in) const
559 if (!buffer().masterBuffer()->params().use_indices) {
560 if (getParam("type") == from_ascii("idx"))
561 os << "\\printindex{}";
564 OutputParams runparams = runparams_in;
565 os << getCommand(runparams);
570 void InsetPrintIndex::validate(LaTeXFeatures & features) const
572 features.require("makeidx");
573 if (buffer().masterBuffer()->params().use_indices)
574 features.require("splitidx");
578 docstring InsetPrintIndex::contextMenu(BufferView const &, int, int) const
580 return buffer().masterBuffer()->params().use_indices ?
581 from_ascii("context-indexprint") : docstring();
585 bool InsetPrintIndex::hasSettings() const
587 return buffer().masterBuffer()->params().use_indices;
593 void parseItem(docstring & s, bool for_output)
595 // this does not yet check for escaped things
596 size_type loc = s.find(from_ascii("@"));
597 if (loc != string::npos) {
603 loc = s.find(from_ascii("|"));
604 if (loc != string::npos)
609 void extractSubentries(docstring const & entry, docstring & main,
610 docstring & sub1, docstring & sub2)
614 size_type const loc = entry.find(from_ascii(" ! "));
615 if (loc == string::npos)
618 main = trim(entry.substr(0, loc));
619 size_t const locend = loc + 3;
620 size_type const loc2 = entry.find(from_ascii(" ! "), locend);
621 if (loc2 == string::npos) {
622 sub1 = trim(entry.substr(locend));
624 sub1 = trim(entry.substr(locend, loc2 - locend));
625 sub2 = trim(entry.substr(loc2 + 3));
636 IndexEntry(docstring const & s, DocIterator const & d)
639 extractSubentries(s, main, sub, subsub);
640 parseItem(main, false);
641 parseItem(sub, false);
642 parseItem(subsub, false);
645 bool equal(IndexEntry const & rhs) const
647 return main == rhs.main && sub == rhs.sub && subsub == rhs.subsub;
650 bool same_sub(IndexEntry const & rhs) const
652 return main == rhs.main && sub == rhs.sub;
655 bool same_main(IndexEntry const & rhs) const
657 return main == rhs.main;
666 bool operator<(IndexEntry const & lhs, IndexEntry const & rhs)
668 return lhs.main < rhs.main
669 || (lhs.main == rhs.main && lhs.sub < rhs.sub)
670 || (lhs.main == rhs.main && lhs.sub == rhs.sub && lhs.subsub < rhs.subsub);
676 docstring InsetPrintIndex::xhtml(XHTMLStream &, OutputParams const & op) const
678 BufferParams const & bp = buffer().masterBuffer()->params();
680 // we do not presently support multiple indices, so we refuse to print
681 // anything but the main index, so as not to generate multiple indices.
682 // NOTE Multiple index support would require some work. The reason
683 // is that the TOC does not know about multiple indices. Either it would
684 // need to be told about them (not a bad idea), or else the index entries
685 // would need to be collected differently, say, during validation.
686 if (bp.use_indices && getParam("type") != from_ascii("idx"))
689 Toc const & toc = buffer().tocBackend().toc("index");
693 // Collection the index entries in a form we can use them.
694 Toc::const_iterator it = toc.begin();
695 Toc::const_iterator const en = toc.end();
696 vector<IndexEntry> entries;
697 for (; it != en; ++it)
698 entries.push_back(IndexEntry(it->str(), it->dit()));
699 stable_sort(entries.begin(), entries.end());
701 Layout const & lay = bp.documentClass().htmlTOCLayout();
702 string const & tocclass = lay.defaultCSSClass();
703 string const tocattr = "class='tochead " + tocclass + "'";
705 // we'll use our own stream, because we are going to defer everything.
706 // that's how we deal with the fact that we're probably inside a standard
707 // paragraph, and we don't want to be.
708 odocstringstream ods;
711 xs << html::StartTag("div", "class='index'");
712 xs << html::StartTag(lay.htmltag(), lay.htmlattr())
714 << html::EndTag(lay.htmltag());
715 xs << html::StartTag("ul", "class='main'");
718 vector<IndexEntry>::const_iterator eit = entries.begin();
719 vector<IndexEntry>::const_iterator const een = entries.end();
720 // tracks whether we are already inside a main entry (1),
721 // a sub-entry (2), or a sub-sub-entry (3). see below for the
724 // the last one we saw
726 int entry_number = -1;
727 for (; eit != een; ++eit) {
728 Paragraph const & par = eit->dit.innerParagraph();
729 if (entry_number == -1 || !eit->equal(last)) {
730 if (entry_number != -1) {
731 // not the first time through the loop, so
732 // close last entry or entries, depending.
734 // close this sub-sub-entry
735 xs << html::EndTag("li");
737 // is this another sub-sub-entry within the same sub-entry?
738 if (!eit->same_sub(last)) {
740 xs << html::EndTag("ul");
745 // the point of the second test here is that we might get
746 // here two ways: (i) by falling through from above; (ii) because,
747 // though the sub-entry hasn't changed, the sub-sub-entry has,
748 // which means that it is the first sub-sub-entry within this
749 // sub-entry. In that case, we do not want to close anything.
750 if (level == 2 && !eit->same_sub(last)) {
752 xs << html::EndTag("li");
754 // is this another sub-entry with the same main entry?
755 if (!eit->same_main(last)) {
757 xs << html::EndTag("ul");
762 // again, we can get here two ways: from above, or because we have
763 // found the first sub-entry. in the latter case, we do not want to
765 if (level == 1 && !eit->same_main(last)) {
767 xs << html::EndTag("li");
772 // we'll be starting new entries
775 // We need to use our own stream, since we will have to
776 // modify what we get back.
777 odocstringstream ent;
778 XHTMLStream entstream(ent);
779 OutputParams ours = op;
781 par.simpleLyXHTMLOnePar(buffer(), entstream, ours, dummy);
783 // these will contain XHTML versions of the main entry, etc
784 // remember that everything will already have been escaped,
785 // so we'll need to use NextRaw() during output.
789 extractSubentries(ent.str(), main, sub, subsub);
790 parseItem(main, true);
791 parseItem(sub, true);
792 parseItem(subsub, true);
795 // another subsubentry
796 xs << html::StartTag("li", "class='subsubentry'")
797 << XHTMLStream::NextRaw() << subsub;
798 } else if (level == 2) {
799 // there are two ways we can be here:
800 // (i) we can actually be inside a sub-entry already and be about
801 // to output the first sub-sub-entry. in this case, our sub
802 // and the last sub will be the same.
803 // (ii) we can just have closed a sub-entry, possibly after also
804 // closing a list of sub-sub-entries. here our sub and the last
805 // sub are different.
806 // only in the latter case do we need to output the new sub-entry.
807 // note that in this case, too, though, the sub-entry might already
808 // have a sub-sub-entry.
809 if (eit->sub != last.sub)
810 xs << html::StartTag("li", "class='subentry'")
811 << XHTMLStream::NextRaw() << sub;
812 if (!subsub.empty()) {
813 // it's actually a subsubentry, so we need to start that list
815 xs << html::StartTag("ul", "class='subsubentry'")
816 << html::StartTag("li", "class='subsubentry'")
817 << XHTMLStream::NextRaw() << subsub;
821 // there are also two ways we can be here:
822 // (i) we can actually be inside an entry already and be about
823 // to output the first sub-entry. in this case, our main
824 // and the last main will be the same.
825 // (ii) we can just have closed an entry, possibly after also
826 // closing a list of sub-entries. here our main and the last
827 // main are different.
828 // only in the latter case do we need to output the new main entry.
829 // note that in this case, too, though, the main entry might already
830 // have a sub-entry, or even a sub-sub-entry.
831 if (eit->main != last.main)
832 xs << html::StartTag("li", "class='main'") << main;
834 // there's a sub-entry, too
836 xs << html::StartTag("ul", "class='subentry'")
837 << html::StartTag("li", "class='subentry'")
838 << XHTMLStream::NextRaw() << sub;
840 if (!subsub.empty()) {
841 // and a sub-sub-entry
843 xs << html::StartTag("ul", "class='subsubentry'")
844 << html::StartTag("li", "class='subsubentry'")
845 << XHTMLStream::NextRaw() << subsub;
851 // finally, then, we can output the index link itself
852 string const parattr = "href='#" + par.magicLabel() + "'";
853 xs << (entry_number == 0 ? ":" : ",");
854 xs << " " << html::StartTag("a", parattr)
855 << ++entry_number << html::EndTag("a");
858 // now we have to close all the open levels
860 xs << html::EndTag("li") << html::EndTag("ul");
864 xs << html::EndTag("div");