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 "TextClass.h"
32 #include "TocBackend.h"
34 #include "support/debug.h"
35 #include "support/docstream.h"
36 #include "support/gettext.h"
37 #include "support/lstrings.h"
39 #include "frontends/alert.h"
45 using namespace lyx::support;
49 /////////////////////////////////////////////////////////////////////
53 ///////////////////////////////////////////////////////////////////////
56 InsetIndex::InsetIndex(Buffer * buf, InsetIndexParams const & params)
57 : InsetCollapsable(buf), params_(params)
61 void InsetIndex::latex(otexstream & os, OutputParams const & runparams_in) const
63 OutputParams runparams(runparams_in);
64 runparams.inIndexEntry = true;
66 if (buffer().masterBuffer()->params().use_indices && !params_.index.empty()
67 && params_.index != "idx") {
69 os << escape(params_.index);
76 // get contents of InsetText as LaTeX and plaintext
78 odocstringstream ourlatex;
79 otexstream ots(ourlatex, texrow);
80 InsetText::latex(ots, runparams);
81 odocstringstream ourplain;
82 InsetText::plaintext(ourplain, runparams);
83 docstring latexstr = ourlatex.str();
84 docstring plainstr = ourplain.str();
86 // this will get what follows | if anything does
89 // check for the | separator
90 // FIXME This would go wrong on an escaped "|", but
91 // how far do we want to go here?
92 size_t pos = latexstr.find(from_ascii("|"));
93 if (pos != docstring::npos) {
94 // put the bit after "|" into cmd...
95 cmd = latexstr.substr(pos + 1);
96 // ...and erase that stuff from latexstr
97 latexstr = latexstr.erase(pos);
98 // ...and similarly from plainstr
99 size_t ppos = plainstr.find(from_ascii("|"));
100 if (ppos < plainstr.size())
101 plainstr.erase(ppos);
103 LYXERR0("The `|' separator was not found in the plaintext version!");
106 // Separate the entires and subentries, i.e., split on "!"
107 // FIXME This would do the wrong thing with escaped ! characters
108 std::vector<docstring> const levels =
109 getVectorFromString(latexstr, from_ascii("!"), true);
110 std::vector<docstring> const levels_plain =
111 getVectorFromString(plainstr, from_ascii("!"), true);
113 vector<docstring>::const_iterator it = levels.begin();
114 vector<docstring>::const_iterator end = levels.end();
115 vector<docstring>::const_iterator it2 = levels_plain.begin();
117 for (; it != end; ++it) {
118 // write the separator except the first time
124 // correctly sort macros and formatted strings
125 // if we do find a command, prepend a plain text
126 // version of the content to get sorting right,
127 // e.g. \index{LyX@\LyX}, \index{text@\textbf{text}}
128 // Don't do that if the user entered '@' himself, though.
129 if (contains(*it, '\\') && !contains(*it, '@')) {
130 // Plaintext might return nothing (e.g. for ERTs)
131 docstring const spart =
132 (it2 < levels_plain.end() && !(*it2).empty())
134 // Now we need to validate that all characters in
135 // the sorting part are representable in the current
136 // encoding. If not try the LaTeX macro which might
137 // or might not be a good choice, and issue a warning.
138 pair<docstring, docstring> spart_latexed =
139 runparams.encoding->latexString(spart, runparams.dryrun);
140 if (!spart_latexed.second.empty())
141 LYXERR0("Uncodable character in index entry. Sorting might be wrong!");
142 if (spart != spart_latexed.first && !runparams.dryrun) {
143 // FIXME: warning should be passed to the error dialog
144 frontend::Alert::warning(_("Index sorting failed"),
145 bformat(_("LyX's automatic index sorting algorithm faced\n"
146 "problems with the entry '%1$s'.\n"
147 "Please specify the sorting of this entry manually, as\n"
148 "explained in the User Guide."), spart));
150 // remove remaining \'s for the sorting part
151 docstring const ppart =
152 subst(spart_latexed.first, from_ascii("\\"), docstring());
156 docstring const tpart = *it;
158 if (it2 < levels_plain.end())
161 // write the bit that followed "|"
169 int InsetIndex::docbook(odocstream & os, OutputParams const & runparams) const
171 os << "<indexterm><primary>";
172 int const i = InsetText::docbook(os, runparams);
173 os << "</primary></indexterm>";
178 docstring InsetIndex::xhtml(XHTMLStream & xs, OutputParams const &) const
180 // we just print an anchor, taking the paragraph ID from
181 // our own interior paragraph, which doesn't get printed
182 std::string const magic = paragraphs().front().magicLabel();
183 std::string const attr = "id='" + magic + "'";
184 xs << html::CompTag("a", attr);
189 bool InsetIndex::showInsetDialog(BufferView * bv) const
191 bv->showDialog("index", params2string(params_),
192 const_cast<InsetIndex *>(this));
197 void InsetIndex::doDispatch(Cursor & cur, FuncRequest & cmd)
199 switch (cmd.action()) {
201 case LFUN_INSET_MODIFY: {
202 if (cmd.getArg(0) == "changetype") {
203 cur.recordUndoInset(ATOMIC_UNDO, this);
204 params_.index = from_utf8(cmd.getArg(1));
207 InsetIndexParams params;
208 InsetIndex::string2params(to_utf8(cmd.argument()), params);
209 cur.recordUndoInset(ATOMIC_UNDO, this);
210 params_.index = params.index;
211 // what we really want here is a TOC update, but that means
212 // a full buffer update
213 cur.forceBufferUpdate();
217 case LFUN_INSET_DIALOG_UPDATE:
218 cur.bv().updateDialog("index", params2string(params_));
222 InsetCollapsable::doDispatch(cur, cmd);
228 bool InsetIndex::getStatus(Cursor & cur, FuncRequest const & cmd,
229 FuncStatus & flag) const
231 switch (cmd.action()) {
233 case LFUN_INSET_MODIFY:
234 if (cmd.getArg(0) == "changetype") {
235 docstring const newtype = from_utf8(cmd.getArg(1));
236 Buffer const & realbuffer = *buffer().masterBuffer();
237 IndicesList const & indiceslist = realbuffer.params().indiceslist();
238 Index const * index = indiceslist.findShortcut(newtype);
239 flag.setEnabled(index != 0);
241 from_utf8(cmd.getArg(1)) == params_.index);
244 return InsetCollapsable::getStatus(cur, cmd, flag);
246 case LFUN_INSET_DIALOG_UPDATE: {
247 Buffer const & realbuffer = *buffer().masterBuffer();
248 flag.setEnabled(realbuffer.params().use_indices);
253 return InsetCollapsable::getStatus(cur, cmd, flag);
258 ColorCode InsetIndex::labelColor() const
260 if (params_.index.empty() || params_.index == from_ascii("idx"))
261 return InsetCollapsable::labelColor();
263 ColorCode c = lcolor.getFromLyXName(to_utf8(params_.index));
265 c = InsetCollapsable::labelColor();
270 docstring InsetIndex::toolTip(BufferView const &, int, int) const
272 docstring tip = _("Index Entry");
273 if (buffer().params().use_indices && !params_.index.empty()) {
274 Buffer const & realbuffer = *buffer().masterBuffer();
275 IndicesList const & indiceslist = realbuffer.params().indiceslist();
277 Index const * index = indiceslist.findShortcut(params_.index);
279 tip += _("unknown type!");
281 tip += index->index();
285 return toolTipText(tip);
289 docstring const InsetIndex::buttonLabel(BufferView const & bv) const
291 InsetLayout const & il = getLayout();
292 docstring label = translateIfPossible(il.labelstring());
294 if (buffer().params().use_indices && !params_.index.empty()) {
295 Buffer const & realbuffer = *buffer().masterBuffer();
296 IndicesList const & indiceslist = realbuffer.params().indiceslist();
298 Index const * index = indiceslist.findShortcut(params_.index);
300 label += _("unknown type!");
302 label += index->index();
306 if (!il.contentaslabel() || geometry(bv) != ButtonOnly)
308 return getNewLabel(label);
312 void InsetIndex::write(ostream & os) const
314 os << to_utf8(layoutName());
316 InsetCollapsable::write(os);
320 void InsetIndex::read(Lexer & lex)
323 InsetCollapsable::read(lex);
327 string InsetIndex::params2string(InsetIndexParams const & params)
336 void InsetIndex::string2params(string const & in, InsetIndexParams & params)
338 params = InsetIndexParams();
342 istringstream data(in);
345 lex.setContext("InsetIndex::string2params");
351 void InsetIndex::addToToc(DocIterator const & cpit, bool output_active) const
353 DocIterator pit = cpit;
354 pit.push_back(CursorSlice(const_cast<InsetIndex &>(*this)));
356 text().forToc(str, 0);
357 buffer().tocBackend().toc("index").push_back(TocItem(pit, 0, str, output_active));
358 // Proceed with the rest of the inset.
359 InsetCollapsable::addToToc(cpit, output_active);
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");
369 InsetCollapsable::validate(features);
373 string InsetIndex::contextMenuName() const
375 return "context-index";
379 bool InsetIndex::hasSettings() const
381 return buffer().masterBuffer()->params().use_indices;
387 /////////////////////////////////////////////////////////////////////
391 ///////////////////////////////////////////////////////////////////////
394 void InsetIndexParams::write(ostream & os) const
398 os << to_utf8(index);
405 void InsetIndexParams::read(Lexer & lex)
408 index = lex.getDocString();
410 index = from_ascii("idx");
414 /////////////////////////////////////////////////////////////////////
418 ///////////////////////////////////////////////////////////////////////
420 InsetPrintIndex::InsetPrintIndex(Buffer * buf, InsetCommandParams const & p)
421 : InsetCommand(buf, p)
425 ParamInfo const & InsetPrintIndex::findInfo(string const & /* cmdName */)
427 static ParamInfo param_info_;
428 if (param_info_.empty()) {
429 param_info_.add("type", ParamInfo::LATEX_OPTIONAL,
430 ParamInfo::HANDLING_ESCAPE);
431 param_info_.add("name", ParamInfo::LATEX_REQUIRED);
437 docstring InsetPrintIndex::screenLabel() const
439 bool const printall = suffixIs(getCmdName(), '*');
440 bool const multind = buffer().masterBuffer()->params().use_indices;
442 && getParam("type") == from_ascii("idx"))
443 || (getParam("type").empty() && !printall))
445 Buffer const & realbuffer = *buffer().masterBuffer();
446 IndicesList const & indiceslist = realbuffer.params().indiceslist();
447 Index const * index = indiceslist.findShortcut(getParam("type"));
448 if (!index && !printall)
449 return _("Unknown index type!");
450 docstring res = printall ? _("All indexes") : index->index();
452 res += " (" + _("non-active") + ")";
453 else if (contains(getCmdName(), "printsubindex"))
454 res += " (" + _("subindex") + ")";
459 bool InsetPrintIndex::isCompatibleCommand(string const & s)
461 return s == "printindex" || s == "printsubindex"
462 || s == "printindex*" || s == "printsubindex*";
466 void InsetPrintIndex::doDispatch(Cursor & cur, FuncRequest & cmd)
468 switch (cmd.action()) {
470 case LFUN_INSET_MODIFY: {
471 if (cmd.argument() == from_ascii("toggle-subindex")) {
472 string cmd = getCmdName();
473 if (contains(cmd, "printindex"))
474 cmd = subst(cmd, "printindex", "printsubindex");
476 cmd = subst(cmd, "printsubindex", "printindex");
480 } else if (cmd.argument() == from_ascii("check-printindex*")) {
481 string cmd = getCmdName();
482 if (suffixIs(cmd, '*'))
486 setParam("type", docstring());
490 InsetCommandParams p(INDEX_PRINT_CODE);
492 InsetCommand::string2params(to_utf8(cmd.argument()), p);
493 if (p.getCmdName().empty()) {
494 cur.noScreenUpdate();
503 InsetCommand::doDispatch(cur, cmd);
509 bool InsetPrintIndex::getStatus(Cursor & cur, FuncRequest const & cmd,
510 FuncStatus & status) const
512 switch (cmd.action()) {
514 case LFUN_INSET_MODIFY: {
515 if (cmd.argument() == from_ascii("toggle-subindex")) {
516 status.setEnabled(buffer().masterBuffer()->params().use_indices);
517 status.setOnOff(contains(getCmdName(), "printsubindex"));
519 } else if (cmd.argument() == from_ascii("check-printindex*")) {
520 status.setEnabled(buffer().masterBuffer()->params().use_indices);
521 status.setOnOff(suffixIs(getCmdName(), '*'));
523 } if (cmd.getArg(0) == "index_print"
524 && cmd.getArg(1) == "CommandInset") {
525 InsetCommandParams p(INDEX_PRINT_CODE);
526 InsetCommand::string2params(to_utf8(cmd.argument()), p);
527 if (suffixIs(p.getCmdName(), '*')) {
528 status.setEnabled(true);
529 status.setOnOff(false);
532 Buffer const & realbuffer = *buffer().masterBuffer();
533 IndicesList const & indiceslist =
534 realbuffer.params().indiceslist();
535 Index const * index = indiceslist.findShortcut(p["type"]);
536 status.setEnabled(index != 0);
537 status.setOnOff(p["type"] == getParam("type"));
540 return InsetCommand::getStatus(cur, cmd, status);
543 case LFUN_INSET_DIALOG_UPDATE: {
544 status.setEnabled(buffer().masterBuffer()->params().use_indices);
549 return InsetCommand::getStatus(cur, cmd, status);
554 void InsetPrintIndex::latex(otexstream & os, OutputParams const & runparams_in) const
556 if (!buffer().masterBuffer()->params().use_indices) {
557 if (getParam("type") == from_ascii("idx"))
558 os << "\\printindex{}";
561 OutputParams runparams = runparams_in;
562 os << getCommand(runparams);
566 void InsetPrintIndex::validate(LaTeXFeatures & features) const
568 features.require("makeidx");
569 if (buffer().masterBuffer()->params().use_indices)
570 features.require("splitidx");
574 string InsetPrintIndex::contextMenuName() const
576 return buffer().masterBuffer()->params().use_indices ?
577 "context-indexprint" : string();
581 bool InsetPrintIndex::hasSettings() const
583 return buffer().masterBuffer()->params().use_indices;
589 void parseItem(docstring & s, bool for_output)
591 // this does not yet check for escaped things
592 size_type loc = s.find(from_ascii("@"));
593 if (loc != string::npos) {
599 loc = s.find(from_ascii("|"));
600 if (loc != string::npos)
605 void extractSubentries(docstring const & entry, docstring & main,
606 docstring & sub1, docstring & sub2)
610 size_type const loc = entry.find(from_ascii(" ! "));
611 if (loc == string::npos)
614 main = trim(entry.substr(0, loc));
615 size_t const locend = loc + 3;
616 size_type const loc2 = entry.find(from_ascii(" ! "), locend);
617 if (loc2 == string::npos) {
618 sub1 = trim(entry.substr(locend));
620 sub1 = trim(entry.substr(locend, loc2 - locend));
621 sub2 = trim(entry.substr(loc2 + 3));
632 IndexEntry(docstring const & s, DocIterator const & d)
635 extractSubentries(s, main, sub, subsub);
636 parseItem(main, false);
637 parseItem(sub, false);
638 parseItem(subsub, false);
641 bool equal(IndexEntry const & rhs) const
643 return main == rhs.main && sub == rhs.sub && subsub == rhs.subsub;
646 bool same_sub(IndexEntry const & rhs) const
648 return main == rhs.main && sub == rhs.sub;
651 bool same_main(IndexEntry const & rhs) const
653 return main == rhs.main;
662 bool operator<(IndexEntry const & lhs, IndexEntry const & rhs)
664 int comp = compare_no_case(lhs.main, rhs.main);
666 comp = compare_no_case(lhs.sub, rhs.sub);
668 comp = compare_no_case(lhs.subsub, rhs.subsub);
675 docstring InsetPrintIndex::xhtml(XHTMLStream &, OutputParams const & op) const
677 BufferParams const & bp = buffer().masterBuffer()->params();
679 // we do not presently support multiple indices, so we refuse to print
680 // anything but the main index, so as not to generate multiple indices.
681 // NOTE Multiple index support would require some work. The reason
682 // is that the TOC does not know about multiple indices. Either it would
683 // need to be told about them (not a bad idea), or else the index entries
684 // would need to be collected differently, say, during validation.
685 if (bp.use_indices && getParam("type") != from_ascii("idx"))
688 Toc const & toc = buffer().tocBackend().toc("index");
692 // Collection the index entries in a form we can use them.
693 Toc::const_iterator it = toc.begin();
694 Toc::const_iterator const en = toc.end();
695 vector<IndexEntry> entries;
696 for (; it != en; ++it)
697 entries.push_back(IndexEntry(it->str(), it->dit()));
698 stable_sort(entries.begin(), entries.end());
700 Layout const & lay = bp.documentClass().htmlTOCLayout();
701 string const & tocclass = lay.defaultCSSClass();
702 string const tocattr = "class='index " + tocclass + "'";
704 // we'll use our own stream, because we are going to defer everything.
705 // that's how we deal with the fact that we're probably inside a standard
706 // paragraph, and we don't want to be.
707 odocstringstream ods;
710 xs << html::StartTag("div", tocattr);
711 xs << html::StartTag(lay.htmltag(), lay.htmlattr())
712 << translateIfPossible(from_ascii("Index"),
713 op.local_font->language()->lang())
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") << html::CR();
736 // is this another sub-sub-entry within the same sub-entry?
737 if (!eit->same_sub(last)) {
739 xs << html::EndTag("ul") << html::CR();
743 // the point of the second test here is that we might get
744 // here two ways: (i) by falling through from above; (ii) because,
745 // though the sub-entry hasn't changed, the sub-sub-entry has,
746 // which means that it is the first sub-sub-entry within this
747 // sub-entry. In that case, we do not want to close anything.
748 if (level == 2 && !eit->same_sub(last)) {
750 xs << html::EndTag("li") << html::CR();
751 // is this another sub-entry with the same main entry?
752 if (!eit->same_main(last)) {
754 xs << html::EndTag("ul") << html::CR();
758 // again, we can get here two ways: from above, or because we have
759 // found the first sub-entry. in the latter case, we do not want to
761 if (level == 1 && !eit->same_main(last)) {
763 xs << html::EndTag("li") << html::CR();
767 // we'll be starting new entries
770 // We need to use our own stream, since we will have to
771 // modify what we get back.
772 odocstringstream ent;
773 XHTMLStream entstream(ent);
774 OutputParams ours = op;
776 par.simpleLyXHTMLOnePar(buffer(), entstream, ours, dummy);
778 // these will contain XHTML versions of the main entry, etc
779 // remember that everything will already have been escaped,
780 // so we'll need to use NextRaw() during output.
784 extractSubentries(ent.str(), main, sub, subsub);
785 parseItem(main, true);
786 parseItem(sub, true);
787 parseItem(subsub, true);
790 // another subsubentry
791 xs << html::StartTag("li", "class='subsubentry'")
792 << XHTMLStream::ESCAPE_NONE << subsub;
793 } else if (level == 2) {
794 // there are two ways we can be here:
795 // (i) we can actually be inside a sub-entry already and be about
796 // to output the first sub-sub-entry. in this case, our sub
797 // and the last sub will be the same.
798 // (ii) we can just have closed a sub-entry, possibly after also
799 // closing a list of sub-sub-entries. here our sub and the last
800 // sub are different.
801 // only in the latter case do we need to output the new sub-entry.
802 // note that in this case, too, though, the sub-entry might already
803 // have a sub-sub-entry.
804 if (eit->sub != last.sub)
805 xs << html::StartTag("li", "class='subentry'")
806 << XHTMLStream::ESCAPE_NONE << sub;
807 if (!subsub.empty()) {
808 // it's actually a subsubentry, so we need to start that list
810 << html::StartTag("ul", "class='subsubentry'")
811 << html::StartTag("li", "class='subsubentry'")
812 << XHTMLStream::ESCAPE_NONE << subsub;
816 // there are also two ways we can be here:
817 // (i) we can actually be inside an entry already and be about
818 // to output the first sub-entry. in this case, our main
819 // and the last main will be the same.
820 // (ii) we can just have closed an entry, possibly after also
821 // closing a list of sub-entries. here our main and the last
822 // main are different.
823 // only in the latter case do we need to output the new main entry.
824 // note that in this case, too, though, the main entry might already
825 // have a sub-entry, or even a sub-sub-entry.
826 if (eit->main != last.main)
827 xs << html::StartTag("li", "class='main'") << main;
829 // there's a sub-entry, too
831 << html::StartTag("ul", "class='subentry'")
832 << html::StartTag("li", "class='subentry'")
833 << XHTMLStream::ESCAPE_NONE << sub;
835 if (!subsub.empty()) {
836 // and a sub-sub-entry
838 << html::StartTag("ul", "class='subsubentry'")
839 << html::StartTag("li", "class='subsubentry'")
840 << XHTMLStream::ESCAPE_NONE << subsub;
846 // finally, then, we can output the index link itself
847 string const parattr = "href='#" + par.magicLabel() + "'";
848 xs << (entry_number == 0 ? ":" : ",");
849 xs << " " << html::StartTag("a", parattr)
850 << ++entry_number << html::EndTag("a");
853 // now we have to close all the open levels
855 xs << html::EndTag("li") << html::EndTag("ul") << html::CR();
858 xs << html::EndTag("div") << html::CR();