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"
20 #include "DispatchResult.h"
22 #include "FuncRequest.h"
23 #include "FuncStatus.h"
24 #include "IndicesList.h"
26 #include "LaTeXFeatures.h"
28 #include "output_latex.h"
29 #include "output_xhtml.h"
31 #include "texstream.h"
32 #include "TextClass.h"
33 #include "TocBackend.h"
35 #include "support/debug.h"
36 #include "support/docstream.h"
37 #include "support/gettext.h"
38 #include "support/lstrings.h"
40 #include "frontends/alert.h"
46 using namespace lyx::support;
50 /////////////////////////////////////////////////////////////////////
54 ///////////////////////////////////////////////////////////////////////
57 InsetIndex::InsetIndex(Buffer * buf, InsetIndexParams const & params)
58 : InsetCollapsable(buf), params_(params)
62 void InsetIndex::latex(otexstream & os, OutputParams const & runparams_in) const
64 OutputParams runparams(runparams_in);
65 runparams.inIndexEntry = true;
67 if (buffer().masterBuffer()->params().use_indices && !params_.index.empty()
68 && params_.index != "idx") {
70 os << escape(params_.index);
77 // get contents of InsetText as LaTeX and plaintext
78 odocstringstream ourlatex;
79 // FIXME: do Tex/Row correspondence (I don't currently understand what is
80 // being generated from latexstr below)
81 otexstream ots(ourlatex);
82 InsetText::latex(ots, runparams);
83 odocstringstream ourplain;
84 InsetText::plaintext(ourplain, runparams);
85 docstring latexstr = ourlatex.str();
86 docstring plainstr = ourplain.str();
88 // this will get what follows | if anything does
91 // check for the | separator
92 // FIXME This would go wrong on an escaped "|", but
93 // how far do we want to go here?
94 size_t pos = latexstr.find(from_ascii("|"));
95 if (pos != docstring::npos) {
96 // put the bit after "|" into cmd...
97 cmd = latexstr.substr(pos + 1);
98 // ...and erase that stuff from latexstr
99 latexstr = latexstr.erase(pos);
100 // ...and similarly from plainstr
101 size_t ppos = plainstr.find(from_ascii("|"));
102 if (ppos < plainstr.size())
103 plainstr.erase(ppos);
105 LYXERR0("The `|' separator was not found in the plaintext version!");
108 // Separate the entires and subentries, i.e., split on "!"
109 // FIXME This would do the wrong thing with escaped ! characters
110 std::vector<docstring> const levels =
111 getVectorFromString(latexstr, from_ascii("!"), true);
112 std::vector<docstring> const levels_plain =
113 getVectorFromString(plainstr, from_ascii("!"), true);
115 vector<docstring>::const_iterator it = levels.begin();
116 vector<docstring>::const_iterator end = levels.end();
117 vector<docstring>::const_iterator it2 = levels_plain.begin();
119 for (; it != end; ++it) {
120 // write the separator except the first time
126 // correctly sort macros and formatted strings
127 // if we do find a command, prepend a plain text
128 // version of the content to get sorting right,
129 // e.g. \index{LyX@\LyX}, \index{text@\textbf{text}}
130 // Don't do that if the user entered '@' himself, though.
131 if (contains(*it, '\\') && !contains(*it, '@')) {
132 // Plaintext might return nothing (e.g. for ERTs)
133 docstring const spart =
134 (it2 < levels_plain.end() && !(*it2).empty())
136 // Now we need to validate that all characters in
137 // the sorting part are representable in the current
138 // encoding. If not try the LaTeX macro which might
139 // or might not be a good choice, and issue a warning.
140 pair<docstring, docstring> spart_latexed =
141 runparams.encoding->latexString(spart, runparams.dryrun);
142 if (!spart_latexed.second.empty())
143 LYXERR0("Uncodable character in index entry. Sorting might be wrong!");
144 if (spart != spart_latexed.first && !runparams.dryrun) {
145 // FIXME: warning should be passed to the error dialog
146 frontend::Alert::warning(_("Index sorting failed"),
147 bformat(_("LyX's automatic index sorting algorithm faced\n"
148 "problems with the entry '%1$s'.\n"
149 "Please specify the sorting of this entry manually, as\n"
150 "explained in the User Guide."), spart));
152 // remove remaining \'s for the sorting part
153 docstring const ppart =
154 subst(spart_latexed.first, from_ascii("\\"), docstring());
158 docstring const tpart = *it;
160 if (it2 < levels_plain.end())
163 // write the bit that followed "|"
171 int InsetIndex::docbook(odocstream & os, OutputParams const & runparams) const
173 os << "<indexterm><primary>";
174 int const i = InsetText::docbook(os, runparams);
175 os << "</primary></indexterm>";
180 docstring InsetIndex::xhtml(XHTMLStream & xs, OutputParams const &) const
182 // we just print an anchor, taking the paragraph ID from
183 // our own interior paragraph, which doesn't get printed
184 std::string const magic = paragraphs().front().magicLabel();
185 std::string const attr = "id='" + magic + "'";
186 xs << html::CompTag("a", attr);
191 bool InsetIndex::showInsetDialog(BufferView * bv) const
193 bv->showDialog("index", params2string(params_),
194 const_cast<InsetIndex *>(this));
199 void InsetIndex::doDispatch(Cursor & cur, FuncRequest & cmd)
201 switch (cmd.action()) {
203 case LFUN_INSET_MODIFY: {
204 if (cmd.getArg(0) == "changetype") {
205 cur.recordUndoInset(this);
206 params_.index = from_utf8(cmd.getArg(1));
209 InsetIndexParams params;
210 InsetIndex::string2params(to_utf8(cmd.argument()), params);
211 cur.recordUndoInset(this);
212 params_.index = params.index;
213 // what we really want here is a TOC update, but that means
214 // a full buffer update
215 cur.forceBufferUpdate();
219 case LFUN_INSET_DIALOG_UPDATE:
220 cur.bv().updateDialog("index", params2string(params_));
224 InsetCollapsable::doDispatch(cur, cmd);
230 bool InsetIndex::getStatus(Cursor & cur, FuncRequest const & cmd,
231 FuncStatus & flag) const
233 switch (cmd.action()) {
235 case LFUN_INSET_MODIFY:
236 if (cmd.getArg(0) == "changetype") {
237 docstring const newtype = from_utf8(cmd.getArg(1));
238 Buffer const & realbuffer = *buffer().masterBuffer();
239 IndicesList const & indiceslist = realbuffer.params().indiceslist();
240 Index const * index = indiceslist.findShortcut(newtype);
241 flag.setEnabled(index != 0);
243 from_utf8(cmd.getArg(1)) == params_.index);
246 return InsetCollapsable::getStatus(cur, cmd, flag);
248 case LFUN_INSET_DIALOG_UPDATE: {
249 Buffer const & realbuffer = *buffer().masterBuffer();
250 flag.setEnabled(realbuffer.params().use_indices);
255 return InsetCollapsable::getStatus(cur, cmd, flag);
260 ColorCode InsetIndex::labelColor() const
262 if (params_.index.empty() || params_.index == from_ascii("idx"))
263 return InsetCollapsable::labelColor();
265 ColorCode c = lcolor.getFromLyXName(to_utf8(params_.index));
267 c = InsetCollapsable::labelColor();
272 docstring InsetIndex::toolTip(BufferView const &, int, int) const
274 docstring tip = _("Index Entry");
275 if (buffer().params().use_indices && !params_.index.empty()) {
276 Buffer const & realbuffer = *buffer().masterBuffer();
277 IndicesList const & indiceslist = realbuffer.params().indiceslist();
279 Index const * index = indiceslist.findShortcut(params_.index);
281 tip += _("unknown type!");
283 tip += index->index();
287 return toolTipText(tip);
291 docstring const InsetIndex::buttonLabel(BufferView const & bv) const
293 InsetLayout const & il = getLayout();
294 docstring label = translateIfPossible(il.labelstring());
296 if (buffer().params().use_indices && !params_.index.empty()) {
297 Buffer const & realbuffer = *buffer().masterBuffer();
298 IndicesList const & indiceslist = realbuffer.params().indiceslist();
300 Index const * index = indiceslist.findShortcut(params_.index);
302 label += _("unknown type!");
304 label += index->index();
308 if (!il.contentaslabel() || geometry(bv) != ButtonOnly)
310 return getNewLabel(label);
314 void InsetIndex::write(ostream & os) const
316 os << to_utf8(layoutName());
318 InsetCollapsable::write(os);
322 void InsetIndex::read(Lexer & lex)
325 InsetCollapsable::read(lex);
329 string InsetIndex::params2string(InsetIndexParams const & params)
338 void InsetIndex::string2params(string const & in, InsetIndexParams & params)
340 params = InsetIndexParams();
344 istringstream data(in);
347 lex.setContext("InsetIndex::string2params");
353 void InsetIndex::addToToc(DocIterator const & cpit, bool output_active,
354 UpdateType utype) const
356 DocIterator pit = cpit;
357 pit.push_back(CursorSlice(const_cast<InsetIndex &>(*this)));
359 string type = "index";
360 if (buffer().masterBuffer()->params().use_indices)
361 type += ":" + to_utf8(params_.index);
362 // this is unlikely to be terribly long
363 text().forOutliner(str, INT_MAX);
364 buffer().tocBackend().toc(type)->push_back(TocItem(pit, 0, str, output_active));
365 // Proceed with the rest of the inset.
366 InsetCollapsable::addToToc(cpit, output_active, utype);
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 string InsetIndex::contextMenuName() const
382 return "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 ParamInfo::HANDLING_ESCAPE);
438 param_info_.add("name", ParamInfo::LATEX_REQUIRED);
444 docstring InsetPrintIndex::screenLabel() const
446 bool const printall = suffixIs(getCmdName(), '*');
447 bool const multind = buffer().masterBuffer()->params().use_indices;
449 && getParam("type") == from_ascii("idx"))
450 || (getParam("type").empty() && !printall))
452 Buffer const & realbuffer = *buffer().masterBuffer();
453 IndicesList const & indiceslist = realbuffer.params().indiceslist();
454 Index const * index = indiceslist.findShortcut(getParam("type"));
455 if (!index && !printall)
456 return _("Unknown index type!");
457 docstring res = printall ? _("All indexes") : index->index();
459 res += " (" + _("non-active") + ")";
460 else if (contains(getCmdName(), "printsubindex"))
461 res += " (" + _("subindex") + ")";
466 bool InsetPrintIndex::isCompatibleCommand(string const & s)
468 return s == "printindex" || s == "printsubindex"
469 || s == "printindex*" || s == "printsubindex*";
473 void InsetPrintIndex::doDispatch(Cursor & cur, FuncRequest & cmd)
475 switch (cmd.action()) {
477 case LFUN_INSET_MODIFY: {
478 if (cmd.argument() == from_ascii("toggle-subindex")) {
479 string cmd = getCmdName();
480 if (contains(cmd, "printindex"))
481 cmd = subst(cmd, "printindex", "printsubindex");
483 cmd = subst(cmd, "printsubindex", "printindex");
487 } else if (cmd.argument() == from_ascii("check-printindex*")) {
488 string cmd = getCmdName();
489 if (suffixIs(cmd, '*'))
493 setParam("type", docstring());
497 InsetCommandParams p(INDEX_PRINT_CODE);
499 InsetCommand::string2params(to_utf8(cmd.argument()), p);
500 if (p.getCmdName().empty()) {
501 cur.noScreenUpdate();
510 InsetCommand::doDispatch(cur, cmd);
516 bool InsetPrintIndex::getStatus(Cursor & cur, FuncRequest const & cmd,
517 FuncStatus & status) const
519 switch (cmd.action()) {
521 case LFUN_INSET_MODIFY: {
522 if (cmd.argument() == from_ascii("toggle-subindex")) {
523 status.setEnabled(buffer().masterBuffer()->params().use_indices);
524 status.setOnOff(contains(getCmdName(), "printsubindex"));
526 } else if (cmd.argument() == from_ascii("check-printindex*")) {
527 status.setEnabled(buffer().masterBuffer()->params().use_indices);
528 status.setOnOff(suffixIs(getCmdName(), '*'));
530 } if (cmd.getArg(0) == "index_print"
531 && cmd.getArg(1) == "CommandInset") {
532 InsetCommandParams p(INDEX_PRINT_CODE);
533 InsetCommand::string2params(to_utf8(cmd.argument()), p);
534 if (suffixIs(p.getCmdName(), '*')) {
535 status.setEnabled(true);
536 status.setOnOff(false);
539 Buffer const & realbuffer = *buffer().masterBuffer();
540 IndicesList const & indiceslist =
541 realbuffer.params().indiceslist();
542 Index const * index = indiceslist.findShortcut(p["type"]);
543 status.setEnabled(index != 0);
544 status.setOnOff(p["type"] == getParam("type"));
547 return InsetCommand::getStatus(cur, cmd, status);
550 case LFUN_INSET_DIALOG_UPDATE: {
551 status.setEnabled(buffer().masterBuffer()->params().use_indices);
556 return InsetCommand::getStatus(cur, cmd, status);
561 void InsetPrintIndex::latex(otexstream & os, OutputParams const & runparams_in) const
563 if (!buffer().masterBuffer()->params().use_indices) {
564 if (getParam("type") == from_ascii("idx"))
565 os << "\\printindex" << termcmd;
568 OutputParams runparams = runparams_in;
569 os << getCommand(runparams);
573 void InsetPrintIndex::validate(LaTeXFeatures & features) const
575 features.require("makeidx");
576 if (buffer().masterBuffer()->params().use_indices)
577 features.require("splitidx");
581 string InsetPrintIndex::contextMenuName() const
583 return buffer().masterBuffer()->params().use_indices ?
584 "context-indexprint" : string();
588 bool InsetPrintIndex::hasSettings() const
590 return buffer().masterBuffer()->params().use_indices;
596 void parseItem(docstring & s, bool for_output)
598 // this does not yet check for escaped things
599 size_type loc = s.find(from_ascii("@"));
600 if (loc != string::npos) {
606 loc = s.find(from_ascii("|"));
607 if (loc != string::npos)
612 void extractSubentries(docstring const & entry, docstring & main,
613 docstring & sub1, docstring & sub2)
617 size_type const loc = entry.find(from_ascii(" ! "));
618 if (loc == string::npos)
621 main = trim(entry.substr(0, loc));
622 size_t const locend = loc + 3;
623 size_type const loc2 = entry.find(from_ascii(" ! "), locend);
624 if (loc2 == string::npos) {
625 sub1 = trim(entry.substr(locend));
627 sub1 = trim(entry.substr(locend, loc2 - locend));
628 sub2 = trim(entry.substr(loc2 + 3));
639 IndexEntry(docstring const & s, DocIterator const & d)
642 extractSubentries(s, main, sub, subsub);
643 parseItem(main, false);
644 parseItem(sub, false);
645 parseItem(subsub, false);
648 bool equal(IndexEntry const & rhs) const
650 return main == rhs.main && sub == rhs.sub && subsub == rhs.subsub;
653 bool same_sub(IndexEntry const & rhs) const
655 return main == rhs.main && sub == rhs.sub;
658 bool same_main(IndexEntry const & rhs) const
660 return main == rhs.main;
669 bool operator<(IndexEntry const & lhs, IndexEntry const & rhs)
671 int comp = compare_no_case(lhs.main, rhs.main);
673 comp = compare_no_case(lhs.sub, rhs.sub);
675 comp = compare_no_case(lhs.subsub, rhs.subsub);
682 docstring InsetPrintIndex::xhtml(XHTMLStream &, OutputParams const & op) const
684 BufferParams const & bp = buffer().masterBuffer()->params();
686 // we do not presently support multiple indices, so we refuse to print
687 // anything but the main index, so as not to generate multiple indices.
688 // NOTE Multiple index support would require some work. The reason
689 // is that the TOC does not know about multiple indices. Either it would
690 // need to be told about them (not a bad idea), or else the index entries
691 // would need to be collected differently, say, during validation.
692 if (bp.use_indices && getParam("type") != from_ascii("idx"))
695 shared_ptr<Toc const> toc = buffer().tocBackend().toc("index");
699 // Collect the index entries in a form we can use them.
700 Toc::const_iterator it = toc->begin();
701 Toc::const_iterator const en = toc->end();
702 vector<IndexEntry> entries;
703 for (; it != en; ++it)
705 entries.push_back(IndexEntry(it->str(), it->dit()));
708 // not very likely that all the index entries are in notes or
712 stable_sort(entries.begin(), entries.end());
714 Layout const & lay = bp.documentClass().htmlTOCLayout();
715 string const & tocclass = lay.defaultCSSClass();
716 string const tocattr = "class='index " + tocclass + "'";
718 // we'll use our own stream, because we are going to defer everything.
719 // that's how we deal with the fact that we're probably inside a standard
720 // paragraph, and we don't want to be.
721 odocstringstream ods;
724 xs << html::StartTag("div", tocattr);
725 xs << html::StartTag(lay.htmltag(), lay.htmlattr())
726 << translateIfPossible(from_ascii("Index"),
727 op.local_font->language()->lang())
728 << html::EndTag(lay.htmltag());
729 xs << html::StartTag("ul", "class='main'");
732 vector<IndexEntry>::const_iterator eit = entries.begin();
733 vector<IndexEntry>::const_iterator const een = entries.end();
734 // tracks whether we are already inside a main entry (1),
735 // a sub-entry (2), or a sub-sub-entry (3). see below for the
738 // the last one we saw
740 int entry_number = -1;
741 for (; eit != een; ++eit) {
742 Paragraph const & par = eit->dit.innerParagraph();
743 if (entry_number == -1 || !eit->equal(last)) {
744 if (entry_number != -1) {
745 // not the first time through the loop, so
746 // close last entry or entries, depending.
748 // close this sub-sub-entry
749 xs << html::EndTag("li") << html::CR();
750 // is this another sub-sub-entry within the same sub-entry?
751 if (!eit->same_sub(last)) {
753 xs << html::EndTag("ul") << html::CR();
757 // the point of the second test here is that we might get
758 // here two ways: (i) by falling through from above; (ii) because,
759 // though the sub-entry hasn't changed, the sub-sub-entry has,
760 // which means that it is the first sub-sub-entry within this
761 // sub-entry. In that case, we do not want to close anything.
762 if (level == 2 && !eit->same_sub(last)) {
764 xs << html::EndTag("li") << html::CR();
765 // is this another sub-entry with the same main entry?
766 if (!eit->same_main(last)) {
768 xs << html::EndTag("ul") << html::CR();
772 // again, we can get here two ways: from above, or because we have
773 // found the first sub-entry. in the latter case, we do not want to
775 if (level == 1 && !eit->same_main(last)) {
777 xs << html::EndTag("li") << html::CR();
781 // we'll be starting new entries
784 // We need to use our own stream, since we will have to
785 // modify what we get back.
786 odocstringstream ent;
787 XHTMLStream entstream(ent);
788 OutputParams ours = op;
790 par.simpleLyXHTMLOnePar(buffer(), entstream, ours, dummy);
792 // these will contain XHTML versions of the main entry, etc
793 // remember that everything will already have been escaped,
794 // so we'll need to use NextRaw() during output.
798 extractSubentries(ent.str(), main, sub, subsub);
799 parseItem(main, true);
800 parseItem(sub, true);
801 parseItem(subsub, true);
804 // another subsubentry
805 xs << html::StartTag("li", "class='subsubentry'")
806 << XHTMLStream::ESCAPE_NONE << subsub;
807 } else if (level == 2) {
808 // there are two ways we can be here:
809 // (i) we can actually be inside a sub-entry already and be about
810 // to output the first sub-sub-entry. in this case, our sub
811 // and the last sub will be the same.
812 // (ii) we can just have closed a sub-entry, possibly after also
813 // closing a list of sub-sub-entries. here our sub and the last
814 // sub are different.
815 // only in the latter case do we need to output the new sub-entry.
816 // note that in this case, too, though, the sub-entry might already
817 // have a sub-sub-entry.
818 if (eit->sub != last.sub)
819 xs << html::StartTag("li", "class='subentry'")
820 << XHTMLStream::ESCAPE_NONE << sub;
821 if (!subsub.empty()) {
822 // it's actually a subsubentry, so we need to start that list
824 << html::StartTag("ul", "class='subsubentry'")
825 << html::StartTag("li", "class='subsubentry'")
826 << XHTMLStream::ESCAPE_NONE << subsub;
830 // there are also two ways we can be here:
831 // (i) we can actually be inside an entry already and be about
832 // to output the first sub-entry. in this case, our main
833 // and the last main will be the same.
834 // (ii) we can just have closed an entry, possibly after also
835 // closing a list of sub-entries. here our main and the last
836 // main are different.
837 // only in the latter case do we need to output the new main entry.
838 // note that in this case, too, though, the main entry might already
839 // have a sub-entry, or even a sub-sub-entry.
840 if (eit->main != last.main)
841 xs << html::StartTag("li", "class='main'") << main;
843 // there's a sub-entry, too
845 << html::StartTag("ul", "class='subentry'")
846 << html::StartTag("li", "class='subentry'")
847 << XHTMLStream::ESCAPE_NONE << sub;
849 if (!subsub.empty()) {
850 // and a sub-sub-entry
852 << html::StartTag("ul", "class='subsubentry'")
853 << html::StartTag("li", "class='subsubentry'")
854 << XHTMLStream::ESCAPE_NONE << subsub;
860 // finally, then, we can output the index link itself
861 string const parattr = "href='#" + par.magicLabel() + "'";
862 xs << (entry_number == 0 ? ":" : ",");
863 xs << " " << html::StartTag("a", parattr)
864 << ++entry_number << html::EndTag("a");
867 // now we have to close all the open levels
869 xs << html::EndTag("li") << html::EndTag("ul") << html::CR();
872 xs << html::EndTag("div") << html::CR();