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 "MetricsInfo.h"
27 #include "output_latex.h"
28 #include "output_xhtml.h"
30 #include "TocBackend.h"
32 #include "support/debug.h"
33 #include "support/docstream.h"
34 #include "support/gettext.h"
35 #include "support/lstrings.h"
37 #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());
157 docstring const tpart = *it;
159 if (it2 < levels_plain.end())
162 // write the bit that followed "|"
170 int InsetIndex::docbook(odocstream & os, OutputParams const & runparams) const
172 os << "<indexterm><primary>";
173 int const i = InsetText::docbook(os, runparams);
174 os << "</primary></indexterm>";
179 docstring InsetIndex::xhtml(XHTMLStream & xs, OutputParams const &) const
181 // we just print an anchor, taking the paragraph ID from
182 // our own interior paragraph, which doesn't get printed
183 std::string const magic = paragraphs().front().magicLabel();
184 std::string const attr = "id='" + magic + "'";
185 xs << html::CompTag("a", attr);
190 bool InsetIndex::showInsetDialog(BufferView * bv) const
192 bv->showDialog("index", params2string(params_),
193 const_cast<InsetIndex *>(this));
198 void InsetIndex::doDispatch(Cursor & cur, FuncRequest & cmd)
200 switch (cmd.action) {
202 case LFUN_INSET_MODIFY: {
203 if (cmd.getArg(0) == "changetype") {
204 params_.index = from_utf8(cmd.getArg(1));
207 InsetIndexParams params;
208 InsetIndex::string2params(to_utf8(cmd.argument()), params);
209 params_.index = params.index;
213 case LFUN_INSET_DIALOG_UPDATE:
214 cur.bv().updateDialog("index", params2string(params_));
218 InsetCollapsable::doDispatch(cur, cmd);
224 bool InsetIndex::getStatus(Cursor & cur, FuncRequest const & cmd,
225 FuncStatus & flag) const
227 switch (cmd.action) {
229 case LFUN_INSET_MODIFY:
230 if (cmd.getArg(0) == "changetype") {
231 docstring const newtype = from_utf8(cmd.getArg(1));
232 Buffer const & realbuffer = *buffer().masterBuffer();
233 IndicesList const & indiceslist = realbuffer.params().indiceslist();
234 Index const * index = indiceslist.findShortcut(newtype);
235 flag.setEnabled(index != 0);
237 from_utf8(cmd.getArg(1)) == params_.index);
240 flag.setEnabled(true);
243 case LFUN_INSET_DIALOG_UPDATE: {
244 Buffer const & realbuffer = *buffer().masterBuffer();
245 flag.setEnabled(realbuffer.params().use_indices);
250 return InsetCollapsable::getStatus(cur, cmd, flag);
255 ColorCode InsetIndex::labelColor() const
257 if (params_.index.empty() || params_.index == from_ascii("idx"))
258 return InsetCollapsable::labelColor();
260 ColorCode c = lcolor.getFromLyXName(to_utf8(params_.index));
262 c = InsetCollapsable::labelColor();
267 docstring InsetIndex::toolTip(BufferView const &, int, int) const
269 docstring tip = _("Index Entry");
270 if (buffer().params().use_indices && !params_.index.empty()) {
271 Buffer const & realbuffer = *buffer().masterBuffer();
272 IndicesList const & indiceslist = realbuffer.params().indiceslist();
274 Index const * index = indiceslist.findShortcut(params_.index);
276 tip += _("unknown type!");
278 tip += index->index();
282 OutputParams rp(&buffer().params().encoding());
283 odocstringstream ods;
284 InsetText::plaintext(ods, rp);
286 return wrapParas(tip);
290 docstring const InsetIndex::buttonLabel(BufferView const & bv) const
292 InsetLayout const & il = getLayout();
293 docstring label = translateIfPossible(il.labelstring());
295 if (buffer().params().use_indices && !params_.index.empty()) {
296 Buffer const & realbuffer = *buffer().masterBuffer();
297 IndicesList const & indiceslist = realbuffer.params().indiceslist();
299 Index const * index = indiceslist.findShortcut(params_.index);
301 label += _("unknown type!");
303 label += index->index();
307 if (!il.contentaslabel() || geometry(bv) != ButtonOnly)
309 return getNewLabel(label);
313 void InsetIndex::write(ostream & os) const
315 os << to_utf8(name());
317 InsetCollapsable::write(os);
321 void InsetIndex::read(Lexer & lex)
324 InsetCollapsable::read(lex);
328 string InsetIndex::params2string(InsetIndexParams const & params)
337 void InsetIndex::string2params(string const & in, InsetIndexParams & params)
339 params = InsetIndexParams();
343 istringstream data(in);
346 lex.setContext("InsetIndex::string2params");
352 void InsetIndex::addToToc(DocIterator const & cpit)
354 DocIterator pit = cpit;
355 pit.push_back(CursorSlice(*this));
356 docstring const item = text().asString(0, 1, AS_STR_LABEL | AS_STR_INSETS);
357 buffer().tocBackend().toc("index").push_back(TocItem(pit, 0, item));
358 // Proceed with the rest of the inset.
359 InsetCollapsable::addToToc(cpit);
363 void InsetIndex::validate(LaTeXFeatures & features) const
365 if (buffer().masterBuffer()->params().use_indices
366 && !params_.index.empty()
367 && params_.index != "idx")
368 features.require("splitidx");
372 docstring InsetIndex::contextMenu(BufferView const &, int, int) const
374 return from_ascii("context-index");
378 bool InsetIndex::hasSettings() const
380 return buffer().masterBuffer()->params().use_indices;
386 /////////////////////////////////////////////////////////////////////
390 ///////////////////////////////////////////////////////////////////////
393 void InsetIndexParams::write(ostream & os) const
397 os << to_utf8(index);
404 void InsetIndexParams::read(Lexer & lex)
407 index = lex.getDocString();
409 index = from_ascii("idx");
413 /////////////////////////////////////////////////////////////////////
417 ///////////////////////////////////////////////////////////////////////
419 InsetPrintIndex::InsetPrintIndex(Buffer * buf, InsetCommandParams const & p)
420 : InsetCommand(buf, p, "index_print")
424 ParamInfo const & InsetPrintIndex::findInfo(string const & /* cmdName */)
426 static ParamInfo param_info_;
427 if (param_info_.empty()) {
428 param_info_.add("type", ParamInfo::LATEX_OPTIONAL);
429 param_info_.add("name", ParamInfo::LATEX_REQUIRED);
435 docstring InsetPrintIndex::screenLabel() const
437 bool const printall = suffixIs(getCmdName(), '*');
438 bool const multind = buffer().masterBuffer()->params().use_indices;
440 && getParam("type") == from_ascii("idx"))
441 || (getParam("type").empty() && !printall))
443 Buffer const & realbuffer = *buffer().masterBuffer();
444 IndicesList const & indiceslist = realbuffer.params().indiceslist();
445 Index const * index = indiceslist.findShortcut(getParam("type"));
446 if (!index && !printall)
447 return _("Unknown index type!");
448 docstring res = printall ? _("All indices") : index->index();
450 res += " (" + _("non-active") + ")";
451 else if (contains(getCmdName(), "printsubindex"))
452 res += " (" + _("subindex") + ")";
457 bool InsetPrintIndex::isCompatibleCommand(string const & s)
459 return s == "printindex" || s == "printsubindex"
460 || s == "printindex*" || s == "printsubindex*";
464 void InsetPrintIndex::doDispatch(Cursor & cur, FuncRequest & cmd)
466 switch (cmd.action) {
468 case LFUN_INSET_MODIFY: {
469 if (cmd.argument() == from_ascii("toggle-subindex")) {
470 string cmd = getCmdName();
471 if (contains(cmd, "printindex"))
472 cmd = subst(cmd, "printindex", "printsubindex");
474 cmd = subst(cmd, "printsubindex", "printindex");
477 } else if (cmd.argument() == from_ascii("check-printindex*")) {
478 string cmd = getCmdName();
479 if (suffixIs(cmd, '*'))
482 setParam("type", docstring());
486 InsetCommandParams p(INDEX_PRINT_CODE);
488 InsetCommand::string2params("index_print",
489 to_utf8(cmd.argument()), p);
490 if (p.getCmdName().empty()) {
499 InsetCommand::doDispatch(cur, cmd);
505 bool InsetPrintIndex::getStatus(Cursor & cur, FuncRequest const & cmd,
506 FuncStatus & status) const
508 switch (cmd.action) {
510 case LFUN_INSET_MODIFY: {
511 if (cmd.argument() == from_ascii("toggle-subindex")) {
512 status.setEnabled(buffer().masterBuffer()->params().use_indices);
513 status.setOnOff(contains(getCmdName(), "printsubindex"));
515 } else if (cmd.argument() == from_ascii("check-printindex*")) {
516 status.setEnabled(buffer().masterBuffer()->params().use_indices);
517 status.setOnOff(suffixIs(getCmdName(), '*'));
519 } if (cmd.getArg(0) == "index_print"
520 && cmd.getArg(1) == "CommandInset") {
521 InsetCommandParams p(INDEX_PRINT_CODE);
522 InsetCommand::string2params("index_print",
523 to_utf8(cmd.argument()), p);
524 if (suffixIs(p.getCmdName(), '*')) {
525 status.setEnabled(true);
526 status.setOnOff(false);
529 Buffer const & realbuffer = *buffer().masterBuffer();
530 IndicesList const & indiceslist =
531 realbuffer.params().indiceslist();
532 Index const * index = indiceslist.findShortcut(p["type"]);
533 status.setEnabled(index != 0);
534 status.setOnOff(p["type"] == getParam("type"));
537 return InsetCommand::getStatus(cur, cmd, status);
540 case LFUN_INSET_DIALOG_UPDATE: {
541 status.setEnabled(buffer().masterBuffer()->params().use_indices);
546 return InsetCommand::getStatus(cur, cmd, status);
551 int InsetPrintIndex::latex(odocstream & os, OutputParams const &) const
553 if (!buffer().masterBuffer()->params().use_indices) {
554 if (getParam("type") == from_ascii("idx"))
555 os << "\\printindex{}";
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");