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_REQUIRED);
446 docstring InsetPrintIndex::screenLabel() const
448 bool const printall = suffixIs(getCmdName(), '*');
449 bool const multind = buffer().masterBuffer()->params().use_indices;
451 && getParam("type") == from_ascii("idx"))
452 || (getParam("type").empty() && !printall))
454 Buffer const & realbuffer = *buffer().masterBuffer();
455 IndicesList const & indiceslist = realbuffer.params().indiceslist();
456 Index const * index = indiceslist.findShortcut(getParam("type"));
457 if (!index && !printall)
458 return _("Unknown index type!");
459 docstring res = printall ? _("All indexes") : index->index();
461 res += " (" + _("non-active") + ")";
462 else if (contains(getCmdName(), "printsubindex"))
463 res += " (" + _("subindex") + ")";
468 bool InsetPrintIndex::isCompatibleCommand(string const & s)
470 return s == "printindex" || s == "printsubindex"
471 || s == "printindex*" || s == "printsubindex*";
475 void InsetPrintIndex::doDispatch(Cursor & cur, FuncRequest & cmd)
477 switch (cmd.action()) {
479 case LFUN_INSET_MODIFY: {
480 if (cmd.argument() == from_ascii("toggle-subindex")) {
481 string cmd = getCmdName();
482 if (contains(cmd, "printindex"))
483 cmd = subst(cmd, "printindex", "printsubindex");
485 cmd = subst(cmd, "printsubindex", "printindex");
489 } else if (cmd.argument() == from_ascii("check-printindex*")) {
490 string cmd = getCmdName();
491 if (suffixIs(cmd, '*'))
495 setParam("type", docstring());
499 InsetCommandParams p(INDEX_PRINT_CODE);
501 InsetCommand::string2params(to_utf8(cmd.argument()), p);
502 if (p.getCmdName().empty()) {
503 cur.noScreenUpdate();
512 InsetCommand::doDispatch(cur, cmd);
518 bool InsetPrintIndex::getStatus(Cursor & cur, FuncRequest const & cmd,
519 FuncStatus & status) const
521 switch (cmd.action()) {
523 case LFUN_INSET_MODIFY: {
524 if (cmd.argument() == from_ascii("toggle-subindex")) {
525 status.setEnabled(buffer().masterBuffer()->params().use_indices);
526 status.setOnOff(contains(getCmdName(), "printsubindex"));
528 } else if (cmd.argument() == from_ascii("check-printindex*")) {
529 status.setEnabled(buffer().masterBuffer()->params().use_indices);
530 status.setOnOff(suffixIs(getCmdName(), '*'));
532 } if (cmd.getArg(0) == "index_print"
533 && cmd.getArg(1) == "CommandInset") {
534 InsetCommandParams p(INDEX_PRINT_CODE);
535 InsetCommand::string2params(to_utf8(cmd.argument()), p);
536 if (suffixIs(p.getCmdName(), '*')) {
537 status.setEnabled(true);
538 status.setOnOff(false);
541 Buffer const & realbuffer = *buffer().masterBuffer();
542 IndicesList const & indiceslist =
543 realbuffer.params().indiceslist();
544 Index const * index = indiceslist.findShortcut(p["type"]);
545 status.setEnabled(index != 0);
546 status.setOnOff(p["type"] == getParam("type"));
549 return InsetCommand::getStatus(cur, cmd, status);
552 case LFUN_INSET_DIALOG_UPDATE: {
553 status.setEnabled(buffer().masterBuffer()->params().use_indices);
558 return InsetCommand::getStatus(cur, cmd, status);
563 void InsetPrintIndex::latex(otexstream & os, OutputParams const & runparams_in) const
565 if (!buffer().masterBuffer()->params().use_indices) {
566 if (getParam("type") == from_ascii("idx"))
567 os << "\\printindex" << termcmd;
570 OutputParams runparams = runparams_in;
571 os << getCommand(runparams);
575 void InsetPrintIndex::validate(LaTeXFeatures & features) const
577 features.require("makeidx");
578 if (buffer().masterBuffer()->params().use_indices)
579 features.require("splitidx");
583 string InsetPrintIndex::contextMenuName() const
585 return buffer().masterBuffer()->params().use_indices ?
586 "context-indexprint" : string();
590 bool InsetPrintIndex::hasSettings() const
592 return buffer().masterBuffer()->params().use_indices;
598 void parseItem(docstring & s, bool for_output)
600 // this does not yet check for escaped things
601 size_type loc = s.find(from_ascii("@"));
602 if (loc != string::npos) {
608 loc = s.find(from_ascii("|"));
609 if (loc != string::npos)
614 void extractSubentries(docstring const & entry, docstring & main,
615 docstring & sub1, docstring & sub2)
619 size_type const loc = entry.find(from_ascii(" ! "));
620 if (loc == string::npos)
623 main = trim(entry.substr(0, loc));
624 size_t const locend = loc + 3;
625 size_type const loc2 = entry.find(from_ascii(" ! "), locend);
626 if (loc2 == string::npos) {
627 sub1 = trim(entry.substr(locend));
629 sub1 = trim(entry.substr(locend, loc2 - locend));
630 sub2 = trim(entry.substr(loc2 + 3));
641 IndexEntry(docstring const & s, DocIterator const & d)
644 extractSubentries(s, main, sub, subsub);
645 parseItem(main, false);
646 parseItem(sub, false);
647 parseItem(subsub, false);
650 bool equal(IndexEntry const & rhs) const
652 return main == rhs.main && sub == rhs.sub && subsub == rhs.subsub;
655 bool same_sub(IndexEntry const & rhs) const
657 return main == rhs.main && sub == rhs.sub;
660 bool same_main(IndexEntry const & rhs) const
662 return main == rhs.main;
671 bool operator<(IndexEntry const & lhs, IndexEntry const & rhs)
673 int comp = compare_no_case(lhs.main, rhs.main);
675 comp = compare_no_case(lhs.sub, rhs.sub);
677 comp = compare_no_case(lhs.subsub, rhs.subsub);
684 docstring InsetPrintIndex::xhtml(XHTMLStream &, OutputParams const & op) const
686 BufferParams const & bp = buffer().masterBuffer()->params();
688 // we do not presently support multiple indices, so we refuse to print
689 // anything but the main index, so as not to generate multiple indices.
690 // NOTE Multiple index support would require some work. The reason
691 // is that the TOC does not know about multiple indices. Either it would
692 // need to be told about them (not a bad idea), or else the index entries
693 // would need to be collected differently, say, during validation.
694 if (bp.use_indices && getParam("type") != from_ascii("idx"))
697 shared_ptr<Toc const> toc = buffer().tocBackend().toc("index");
701 // Collect the index entries in a form we can use them.
702 Toc::const_iterator it = toc->begin();
703 Toc::const_iterator const en = toc->end();
704 vector<IndexEntry> entries;
705 for (; it != en; ++it)
707 entries.push_back(IndexEntry(it->str(), it->dit()));
710 // not very likely that all the index entries are in notes or
714 stable_sort(entries.begin(), entries.end());
716 Layout const & lay = bp.documentClass().htmlTOCLayout();
717 string const & tocclass = lay.defaultCSSClass();
718 string const tocattr = "class='index " + tocclass + "'";
720 // we'll use our own stream, because we are going to defer everything.
721 // that's how we deal with the fact that we're probably inside a standard
722 // paragraph, and we don't want to be.
723 odocstringstream ods;
726 xs << html::StartTag("div", tocattr);
727 xs << html::StartTag(lay.htmltag(), lay.htmlattr())
728 << translateIfPossible(from_ascii("Index"),
729 op.local_font->language()->lang())
730 << html::EndTag(lay.htmltag());
731 xs << html::StartTag("ul", "class='main'");
734 vector<IndexEntry>::const_iterator eit = entries.begin();
735 vector<IndexEntry>::const_iterator const een = entries.end();
736 // tracks whether we are already inside a main entry (1),
737 // a sub-entry (2), or a sub-sub-entry (3). see below for the
740 // the last one we saw
742 int entry_number = -1;
743 for (; eit != een; ++eit) {
744 Paragraph const & par = eit->dit.innerParagraph();
745 if (entry_number == -1 || !eit->equal(last)) {
746 if (entry_number != -1) {
747 // not the first time through the loop, so
748 // close last entry or entries, depending.
750 // close this sub-sub-entry
751 xs << html::EndTag("li") << html::CR();
752 // is this another sub-sub-entry within the same sub-entry?
753 if (!eit->same_sub(last)) {
755 xs << html::EndTag("ul") << html::CR();
759 // the point of the second test here is that we might get
760 // here two ways: (i) by falling through from above; (ii) because,
761 // though the sub-entry hasn't changed, the sub-sub-entry has,
762 // which means that it is the first sub-sub-entry within this
763 // sub-entry. In that case, we do not want to close anything.
764 if (level == 2 && !eit->same_sub(last)) {
766 xs << html::EndTag("li") << html::CR();
767 // is this another sub-entry with the same main entry?
768 if (!eit->same_main(last)) {
770 xs << html::EndTag("ul") << html::CR();
774 // again, we can get here two ways: from above, or because we have
775 // found the first sub-entry. in the latter case, we do not want to
777 if (level == 1 && !eit->same_main(last)) {
779 xs << html::EndTag("li") << html::CR();
783 // we'll be starting new entries
786 // We need to use our own stream, since we will have to
787 // modify what we get back.
788 odocstringstream ent;
789 XHTMLStream entstream(ent);
790 OutputParams ours = op;
792 par.simpleLyXHTMLOnePar(buffer(), entstream, ours, dummy);
794 // these will contain XHTML versions of the main entry, etc
795 // remember that everything will already have been escaped,
796 // so we'll need to use NextRaw() during output.
800 extractSubentries(ent.str(), main, sub, subsub);
801 parseItem(main, true);
802 parseItem(sub, true);
803 parseItem(subsub, true);
806 // another subsubentry
807 xs << html::StartTag("li", "class='subsubentry'")
808 << XHTMLStream::ESCAPE_NONE << subsub;
809 } else if (level == 2) {
810 // there are two ways we can be here:
811 // (i) we can actually be inside a sub-entry already and be about
812 // to output the first sub-sub-entry. in this case, our sub
813 // and the last sub will be the same.
814 // (ii) we can just have closed a sub-entry, possibly after also
815 // closing a list of sub-sub-entries. here our sub and the last
816 // sub are different.
817 // only in the latter case do we need to output the new sub-entry.
818 // note that in this case, too, though, the sub-entry might already
819 // have a sub-sub-entry.
820 if (eit->sub != last.sub)
821 xs << html::StartTag("li", "class='subentry'")
822 << XHTMLStream::ESCAPE_NONE << sub;
823 if (!subsub.empty()) {
824 // it's actually a subsubentry, so we need to start that list
826 << html::StartTag("ul", "class='subsubentry'")
827 << html::StartTag("li", "class='subsubentry'")
828 << XHTMLStream::ESCAPE_NONE << subsub;
832 // there are also two ways we can be here:
833 // (i) we can actually be inside an entry already and be about
834 // to output the first sub-entry. in this case, our main
835 // and the last main will be the same.
836 // (ii) we can just have closed an entry, possibly after also
837 // closing a list of sub-entries. here our main and the last
838 // main are different.
839 // only in the latter case do we need to output the new main entry.
840 // note that in this case, too, though, the main entry might already
841 // have a sub-entry, or even a sub-sub-entry.
842 if (eit->main != last.main)
843 xs << html::StartTag("li", "class='main'") << main;
845 // there's a sub-entry, too
847 << html::StartTag("ul", "class='subentry'")
848 << html::StartTag("li", "class='subentry'")
849 << XHTMLStream::ESCAPE_NONE << sub;
851 if (!subsub.empty()) {
852 // and a sub-sub-entry
854 << html::StartTag("ul", "class='subsubentry'")
855 << html::StartTag("li", "class='subsubentry'")
856 << XHTMLStream::ESCAPE_NONE << subsub;
862 // finally, then, we can output the index link itself
863 string const parattr = "href='#" + par.magicLabel() + "'";
864 xs << (entry_number == 0 ? ":" : ",");
865 xs << " " << html::StartTag("a", parattr)
866 << ++entry_number << html::EndTag("a");
869 // now we have to close all the open levels
871 xs << html::EndTag("li") << html::EndTag("ul") << html::CR();
874 xs << html::EndTag("div") << html::CR();