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, TocBackend & backend) 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 TocBuilder & b = backend.builder(type);
365 b.pushItem(pit, str, output_active);
366 // Proceed with the rest of the inset.
367 InsetCollapsable::addToToc(cpit, output_active, utype, backend);
372 void InsetIndex::validate(LaTeXFeatures & features) const
374 if (buffer().masterBuffer()->params().use_indices
375 && !params_.index.empty()
376 && params_.index != "idx")
377 features.require("splitidx");
378 InsetCollapsable::validate(features);
382 string InsetIndex::contextMenuName() const
384 return "context-index";
388 bool InsetIndex::hasSettings() const
390 return buffer().masterBuffer()->params().use_indices;
396 /////////////////////////////////////////////////////////////////////
400 ///////////////////////////////////////////////////////////////////////
403 void InsetIndexParams::write(ostream & os) const
407 os << to_utf8(index);
414 void InsetIndexParams::read(Lexer & lex)
417 index = lex.getDocString();
419 index = from_ascii("idx");
423 /////////////////////////////////////////////////////////////////////
427 ///////////////////////////////////////////////////////////////////////
429 InsetPrintIndex::InsetPrintIndex(Buffer * buf, InsetCommandParams const & p)
430 : InsetCommand(buf, p)
434 ParamInfo const & InsetPrintIndex::findInfo(string const & /* cmdName */)
436 static ParamInfo param_info_;
437 if (param_info_.empty()) {
438 param_info_.add("type", ParamInfo::LATEX_OPTIONAL,
439 ParamInfo::HANDLING_ESCAPE);
440 param_info_.add("name", ParamInfo::LATEX_OPTIONAL,
441 ParamInfo::HANDLING_LATEXIFY);
442 param_info_.add("literal", ParamInfo::LYX_INTERNAL);
448 docstring InsetPrintIndex::screenLabel() const
450 bool const printall = suffixIs(getCmdName(), '*');
451 bool const multind = buffer().masterBuffer()->params().use_indices;
453 && getParam("type") == from_ascii("idx"))
454 || (getParam("type").empty() && !printall))
456 Buffer const & realbuffer = *buffer().masterBuffer();
457 IndicesList const & indiceslist = realbuffer.params().indiceslist();
458 Index const * index = indiceslist.findShortcut(getParam("type"));
459 if (!index && !printall)
460 return _("Unknown index type!");
461 docstring res = printall ? _("All indexes") : index->index();
463 res += " (" + _("non-active") + ")";
464 else if (contains(getCmdName(), "printsubindex"))
465 res += " (" + _("subindex") + ")";
470 bool InsetPrintIndex::isCompatibleCommand(string const & s)
472 return s == "printindex" || s == "printsubindex"
473 || s == "printindex*" || s == "printsubindex*";
477 void InsetPrintIndex::doDispatch(Cursor & cur, FuncRequest & cmd)
479 switch (cmd.action()) {
481 case LFUN_INSET_MODIFY: {
482 if (cmd.argument() == from_ascii("toggle-subindex")) {
483 string cmd = getCmdName();
484 if (contains(cmd, "printindex"))
485 cmd = subst(cmd, "printindex", "printsubindex");
487 cmd = subst(cmd, "printsubindex", "printindex");
491 } else if (cmd.argument() == from_ascii("check-printindex*")) {
492 string cmd = getCmdName();
493 if (suffixIs(cmd, '*'))
497 setParam("type", docstring());
501 InsetCommandParams p(INDEX_PRINT_CODE);
503 InsetCommand::string2params(to_utf8(cmd.argument()), p);
504 if (p.getCmdName().empty()) {
505 cur.noScreenUpdate();
514 InsetCommand::doDispatch(cur, cmd);
520 bool InsetPrintIndex::getStatus(Cursor & cur, FuncRequest const & cmd,
521 FuncStatus & status) const
523 switch (cmd.action()) {
525 case LFUN_INSET_MODIFY: {
526 if (cmd.argument() == from_ascii("toggle-subindex")) {
527 status.setEnabled(buffer().masterBuffer()->params().use_indices);
528 status.setOnOff(contains(getCmdName(), "printsubindex"));
530 } else if (cmd.argument() == from_ascii("check-printindex*")) {
531 status.setEnabled(buffer().masterBuffer()->params().use_indices);
532 status.setOnOff(suffixIs(getCmdName(), '*'));
534 } if (cmd.getArg(0) == "index_print"
535 && cmd.getArg(1) == "CommandInset") {
536 InsetCommandParams p(INDEX_PRINT_CODE);
537 InsetCommand::string2params(to_utf8(cmd.argument()), p);
538 if (suffixIs(p.getCmdName(), '*')) {
539 status.setEnabled(true);
540 status.setOnOff(false);
543 Buffer const & realbuffer = *buffer().masterBuffer();
544 IndicesList const & indiceslist =
545 realbuffer.params().indiceslist();
546 Index const * index = indiceslist.findShortcut(p["type"]);
547 status.setEnabled(index != 0);
548 status.setOnOff(p["type"] == getParam("type"));
551 return InsetCommand::getStatus(cur, cmd, status);
554 case LFUN_INSET_DIALOG_UPDATE: {
555 status.setEnabled(buffer().masterBuffer()->params().use_indices);
560 return InsetCommand::getStatus(cur, cmd, status);
565 void InsetPrintIndex::updateBuffer(ParIterator const &, UpdateType)
567 Index const * index =
568 buffer().masterParams().indiceslist().findShortcut(getParam("type"));
570 setParam("name", index->index());
574 void InsetPrintIndex::latex(otexstream & os, OutputParams const & runparams_in) const
576 if (!buffer().masterBuffer()->params().use_indices) {
577 if (getParam("type") == from_ascii("idx"))
578 os << "\\printindex" << termcmd;
581 OutputParams runparams = runparams_in;
582 os << getCommand(runparams);
586 void InsetPrintIndex::validate(LaTeXFeatures & features) const
588 features.require("makeidx");
589 if (buffer().masterBuffer()->params().use_indices)
590 features.require("splitidx");
591 InsetCommand::validate(features);
595 string InsetPrintIndex::contextMenuName() const
597 return buffer().masterBuffer()->params().use_indices ?
598 "context-indexprint" : string();
602 bool InsetPrintIndex::hasSettings() const
604 return buffer().masterBuffer()->params().use_indices;
610 void parseItem(docstring & s, bool for_output)
612 // this does not yet check for escaped things
613 size_type loc = s.find(from_ascii("@"));
614 if (loc != string::npos) {
620 loc = s.find(from_ascii("|"));
621 if (loc != string::npos)
626 void extractSubentries(docstring const & entry, docstring & main,
627 docstring & sub1, docstring & sub2)
631 size_type const loc = entry.find(from_ascii(" ! "));
632 if (loc == string::npos)
635 main = trim(entry.substr(0, loc));
636 size_t const locend = loc + 3;
637 size_type const loc2 = entry.find(from_ascii(" ! "), locend);
638 if (loc2 == string::npos) {
639 sub1 = trim(entry.substr(locend));
641 sub1 = trim(entry.substr(locend, loc2 - locend));
642 sub2 = trim(entry.substr(loc2 + 3));
653 IndexEntry(docstring const & s, DocIterator const & d)
656 extractSubentries(s, main, sub, subsub);
657 parseItem(main, false);
658 parseItem(sub, false);
659 parseItem(subsub, false);
662 bool equal(IndexEntry const & rhs) const
664 return main == rhs.main && sub == rhs.sub && subsub == rhs.subsub;
667 bool same_sub(IndexEntry const & rhs) const
669 return main == rhs.main && sub == rhs.sub;
672 bool same_main(IndexEntry const & rhs) const
674 return main == rhs.main;
683 bool operator<(IndexEntry const & lhs, IndexEntry const & rhs)
685 int comp = compare_no_case(lhs.main, rhs.main);
687 comp = compare_no_case(lhs.sub, rhs.sub);
689 comp = compare_no_case(lhs.subsub, rhs.subsub);
696 docstring InsetPrintIndex::xhtml(XHTMLStream &, OutputParams const & op) const
698 BufferParams const & bp = buffer().masterBuffer()->params();
700 // we do not presently support multiple indices, so we refuse to print
701 // anything but the main index, so as not to generate multiple indices.
702 // NOTE Multiple index support would require some work. The reason
703 // is that the TOC does not know about multiple indices. Either it would
704 // need to be told about them (not a bad idea), or else the index entries
705 // would need to be collected differently, say, during validation.
706 if (bp.use_indices && getParam("type") != from_ascii("idx"))
709 shared_ptr<Toc const> toc = buffer().tocBackend().toc("index");
713 // Collect the index entries in a form we can use them.
714 Toc::const_iterator it = toc->begin();
715 Toc::const_iterator const en = toc->end();
716 vector<IndexEntry> entries;
717 for (; it != en; ++it)
719 entries.push_back(IndexEntry(it->str(), it->dit()));
722 // not very likely that all the index entries are in notes or
726 stable_sort(entries.begin(), entries.end());
728 Layout const & lay = bp.documentClass().htmlTOCLayout();
729 string const & tocclass = lay.defaultCSSClass();
730 string const tocattr = "class='index " + tocclass + "'";
732 // we'll use our own stream, because we are going to defer everything.
733 // that's how we deal with the fact that we're probably inside a standard
734 // paragraph, and we don't want to be.
735 odocstringstream ods;
738 xs << html::StartTag("div", tocattr);
739 xs << html::StartTag(lay.htmltag(), lay.htmlattr())
740 << translateIfPossible(from_ascii("Index"),
741 op.local_font->language()->lang())
742 << html::EndTag(lay.htmltag());
743 xs << html::StartTag("ul", "class='main'");
746 vector<IndexEntry>::const_iterator eit = entries.begin();
747 vector<IndexEntry>::const_iterator const een = entries.end();
748 // tracks whether we are already inside a main entry (1),
749 // a sub-entry (2), or a sub-sub-entry (3). see below for the
752 // the last one we saw
754 int entry_number = -1;
755 for (; eit != een; ++eit) {
756 Paragraph const & par = eit->dit.innerParagraph();
757 if (entry_number == -1 || !eit->equal(last)) {
758 if (entry_number != -1) {
759 // not the first time through the loop, so
760 // close last entry or entries, depending.
762 // close this sub-sub-entry
763 xs << html::EndTag("li") << html::CR();
764 // is this another sub-sub-entry within the same sub-entry?
765 if (!eit->same_sub(last)) {
767 xs << html::EndTag("ul") << html::CR();
771 // the point of the second test here is that we might get
772 // here two ways: (i) by falling through from above; (ii) because,
773 // though the sub-entry hasn't changed, the sub-sub-entry has,
774 // which means that it is the first sub-sub-entry within this
775 // sub-entry. In that case, we do not want to close anything.
776 if (level == 2 && !eit->same_sub(last)) {
778 xs << html::EndTag("li") << html::CR();
779 // is this another sub-entry with the same main entry?
780 if (!eit->same_main(last)) {
782 xs << html::EndTag("ul") << html::CR();
786 // again, we can get here two ways: from above, or because we have
787 // found the first sub-entry. in the latter case, we do not want to
789 if (level == 1 && !eit->same_main(last)) {
791 xs << html::EndTag("li") << html::CR();
795 // we'll be starting new entries
798 // We need to use our own stream, since we will have to
799 // modify what we get back.
800 odocstringstream ent;
801 XHTMLStream entstream(ent);
802 OutputParams ours = op;
804 par.simpleLyXHTMLOnePar(buffer(), entstream, ours, dummy);
806 // these will contain XHTML versions of the main entry, etc
807 // remember that everything will already have been escaped,
808 // so we'll need to use NextRaw() during output.
812 extractSubentries(ent.str(), main, sub, subsub);
813 parseItem(main, true);
814 parseItem(sub, true);
815 parseItem(subsub, true);
818 // another subsubentry
819 xs << html::StartTag("li", "class='subsubentry'")
820 << XHTMLStream::ESCAPE_NONE << subsub;
821 } else if (level == 2) {
822 // there are two ways we can be here:
823 // (i) we can actually be inside a sub-entry already and be about
824 // to output the first sub-sub-entry. in this case, our sub
825 // and the last sub will be the same.
826 // (ii) we can just have closed a sub-entry, possibly after also
827 // closing a list of sub-sub-entries. here our sub and the last
828 // sub are different.
829 // only in the latter case do we need to output the new sub-entry.
830 // note that in this case, too, though, the sub-entry might already
831 // have a sub-sub-entry.
832 if (eit->sub != last.sub)
833 xs << html::StartTag("li", "class='subentry'")
834 << XHTMLStream::ESCAPE_NONE << sub;
835 if (!subsub.empty()) {
836 // it's actually a subsubentry, so we need to start that list
838 << html::StartTag("ul", "class='subsubentry'")
839 << html::StartTag("li", "class='subsubentry'")
840 << XHTMLStream::ESCAPE_NONE << subsub;
844 // there are also two ways we can be here:
845 // (i) we can actually be inside an entry already and be about
846 // to output the first sub-entry. in this case, our main
847 // and the last main will be the same.
848 // (ii) we can just have closed an entry, possibly after also
849 // closing a list of sub-entries. here our main and the last
850 // main are different.
851 // only in the latter case do we need to output the new main entry.
852 // note that in this case, too, though, the main entry might already
853 // have a sub-entry, or even a sub-sub-entry.
854 if (eit->main != last.main)
855 xs << html::StartTag("li", "class='main'") << main;
857 // there's a sub-entry, too
859 << html::StartTag("ul", "class='subentry'")
860 << html::StartTag("li", "class='subentry'")
861 << XHTMLStream::ESCAPE_NONE << sub;
863 if (!subsub.empty()) {
864 // and a sub-sub-entry
866 << html::StartTag("ul", "class='subsubentry'")
867 << html::StartTag("li", "class='subsubentry'")
868 << XHTMLStream::ESCAPE_NONE << subsub;
874 // finally, then, we can output the index link itself
875 string const parattr = "href='#" + par.magicLabel() + "'";
876 xs << (entry_number == 0 ? ":" : ",");
877 xs << " " << html::StartTag("a", parattr)
878 << ++entry_number << html::EndTag("a");
881 // now we have to close all the open levels
883 xs << html::EndTag("li") << html::EndTag("ul") << html::CR();
886 xs << html::EndTag("div") << html::CR();