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"
25 #include "LaTeXFeatures.h"
27 #include "output_latex.h"
28 #include "output_xhtml.h"
30 #include "TextClass.h"
31 #include "TocBackend.h"
33 #include "support/debug.h"
34 #include "support/docstream.h"
35 #include "support/gettext.h"
36 #include "support/lstrings.h"
38 #include "frontends/alert.h"
44 using namespace lyx::support;
48 /////////////////////////////////////////////////////////////////////
52 ///////////////////////////////////////////////////////////////////////
55 InsetIndex::InsetIndex(Buffer * buf, InsetIndexParams const & params)
56 : InsetCollapsable(buf), params_(params)
60 int InsetIndex::latex(odocstream & os,
61 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") {
77 // get contents of InsetText as LaTeX and plaintext
78 odocstringstream ourlatex;
79 InsetText::latex(ourlatex, runparams);
80 odocstringstream ourplain;
81 InsetText::plaintext(ourplain, runparams);
82 docstring latexstr = ourlatex.str();
83 docstring plainstr = ourplain.str();
85 // this will get what follows | if anything does
88 // check for the | separator
89 // FIXME This would go wrong on an escaped "|", but
90 // how far do we want to go here?
91 size_t pos = latexstr.find(from_ascii("|"));
92 if (pos != docstring::npos) {
93 // put the bit after "|" into cmd...
94 cmd = latexstr.substr(pos + 1);
95 // ...and erase that stuff from latexstr
96 latexstr = latexstr.erase(pos);
97 // ...and similarly from plainstr
98 size_t ppos = plainstr.find(from_ascii("|"));
99 if (ppos < plainstr.size())
100 plainstr.erase(ppos);
102 LYXERR0("The `|' separator was not found in the plaintext version!");
105 // Separate the entires and subentries, i.e., split on "!"
106 // FIXME This would do the wrong thing with escaped ! characters
107 std::vector<docstring> const levels =
108 getVectorFromString(latexstr, from_ascii("!"), true);
109 std::vector<docstring> const levels_plain =
110 getVectorFromString(plainstr, from_ascii("!"), true);
112 vector<docstring>::const_iterator it = levels.begin();
113 vector<docstring>::const_iterator end = levels.end();
114 vector<docstring>::const_iterator it2 = levels_plain.begin();
116 for (; it != end; ++it) {
117 // write the separator except the first time
123 // correctly sort macros and formatted strings
124 // if we do find a command, prepend a plain text
125 // version of the content to get sorting right,
126 // e.g. \index{LyX@\LyX}, \index{text@\textbf{text}}
127 // Don't do that if the user entered '@' himself, though.
128 if (contains(*it, '\\') && !contains(*it, '@')) {
129 // Plaintext might return nothing (e.g. for ERTs)
130 docstring const spart =
131 (it2 < levels_plain.end() && !(*it2).empty())
133 // Now we need to validate that all characters in
134 // the sorting part are representable in the current
135 // encoding. If not try the LaTeX macro which might
136 // or might not be a good choice, and issue a warning.
138 for (size_t n = 0; n < spart.size(); ++n) {
140 spart2 += runparams.encoding->latexChar(spart[n]);
141 } catch (EncodingException & /* e */) {
142 LYXERR0("Uncodable character in index entry. Sorting might be wrong!");
145 if (spart != spart2 && !runparams.dryrun) {
146 // FIXME: warning should be passed to the error dialog
147 frontend::Alert::warning(_("Index sorting failed"),
148 bformat(_("LyX's automatic index sorting algorithm faced\n"
149 "problems with the entry '%1$s'.\n"
150 "Please specify the sorting of this entry manually, as\n"
151 "explained in the User Guide."), spart));
153 // remove remaining \'s for the sorting part
154 docstring const ppart =
155 subst(spart2, from_ascii("\\"), docstring());
158 i += count_char(ppart, '\n');
160 docstring const tpart = *it;
162 i += count_char(tpart, '\n');
163 if (it2 < levels_plain.end())
166 // write the bit that followed "|"
169 i += count_char(cmd, '\n');
176 int InsetIndex::docbook(odocstream & os, OutputParams const & runparams) const
178 os << "<indexterm><primary>";
179 int const i = InsetText::docbook(os, runparams);
180 os << "</primary></indexterm>";
185 docstring InsetIndex::xhtml(XHTMLStream & xs, OutputParams const &) const
187 // we just print an anchor, taking the paragraph ID from
188 // our own interior paragraph, which doesn't get printed
189 std::string const magic = paragraphs().front().magicLabel();
190 std::string const attr = "id='" + magic + "'";
191 xs << html::CompTag("a", attr);
196 bool InsetIndex::showInsetDialog(BufferView * bv) const
198 bv->showDialog("index", params2string(params_),
199 const_cast<InsetIndex *>(this));
204 void InsetIndex::doDispatch(Cursor & cur, FuncRequest & cmd)
206 switch (cmd.action()) {
208 case LFUN_INSET_MODIFY: {
209 if (cmd.getArg(0) == "changetype") {
210 params_.index = from_utf8(cmd.getArg(1));
213 InsetIndexParams params;
214 InsetIndex::string2params(to_utf8(cmd.argument()), params);
215 params_.index = params.index;
216 // what we really want here is a TOC update, but that means
217 // a full buffer update
218 cur.forceBufferUpdate();
222 case LFUN_INSET_DIALOG_UPDATE:
223 cur.bv().updateDialog("index", params2string(params_));
227 InsetCollapsable::doDispatch(cur, cmd);
233 bool InsetIndex::getStatus(Cursor & cur, FuncRequest const & cmd,
234 FuncStatus & flag) const
236 switch (cmd.action()) {
238 case LFUN_INSET_MODIFY:
239 if (cmd.getArg(0) == "changetype") {
240 docstring const newtype = from_utf8(cmd.getArg(1));
241 Buffer const & realbuffer = *buffer().masterBuffer();
242 IndicesList const & indiceslist = realbuffer.params().indiceslist();
243 Index const * index = indiceslist.findShortcut(newtype);
244 flag.setEnabled(index != 0);
246 from_utf8(cmd.getArg(1)) == params_.index);
249 flag.setEnabled(true);
252 case LFUN_INSET_DIALOG_UPDATE: {
253 Buffer const & realbuffer = *buffer().masterBuffer();
254 flag.setEnabled(realbuffer.params().use_indices);
259 return InsetCollapsable::getStatus(cur, cmd, flag);
264 ColorCode InsetIndex::labelColor() const
266 if (params_.index.empty() || params_.index == from_ascii("idx"))
267 return InsetCollapsable::labelColor();
269 ColorCode c = lcolor.getFromLyXName(to_utf8(params_.index));
271 c = InsetCollapsable::labelColor();
276 docstring InsetIndex::toolTip(BufferView const &, int, int) const
278 docstring tip = _("Index Entry");
279 if (buffer().params().use_indices && !params_.index.empty()) {
280 Buffer const & realbuffer = *buffer().masterBuffer();
281 IndicesList const & indiceslist = realbuffer.params().indiceslist();
283 Index const * index = indiceslist.findShortcut(params_.index);
285 tip += _("unknown type!");
287 tip += index->index();
291 OutputParams rp(&buffer().params().encoding());
292 odocstringstream ods;
293 InsetText::plaintext(ods, rp);
295 return wrapParas(tip);
299 docstring const InsetIndex::buttonLabel(BufferView const & bv) const
301 InsetLayout const & il = getLayout();
302 docstring label = translateIfPossible(il.labelstring());
304 if (buffer().params().use_indices && !params_.index.empty()) {
305 Buffer const & realbuffer = *buffer().masterBuffer();
306 IndicesList const & indiceslist = realbuffer.params().indiceslist();
308 Index const * index = indiceslist.findShortcut(params_.index);
310 label += _("unknown type!");
312 label += index->index();
316 if (!il.contentaslabel() || geometry(bv) != ButtonOnly)
318 return getNewLabel(label);
322 void InsetIndex::write(ostream & os) const
324 os << to_utf8(name());
326 InsetCollapsable::write(os);
330 void InsetIndex::read(Lexer & lex)
333 InsetCollapsable::read(lex);
337 string InsetIndex::params2string(InsetIndexParams const & params)
346 void InsetIndex::string2params(string const & in, InsetIndexParams & params)
348 params = InsetIndexParams();
352 istringstream data(in);
355 lex.setContext("InsetIndex::string2params");
361 void InsetIndex::addToToc(DocIterator const & cpit)
363 DocIterator pit = cpit;
364 pit.push_back(CursorSlice(*this));
365 docstring const item = text().asString(0, 1, AS_STR_LABEL | AS_STR_INSETS);
366 buffer().tocBackend().toc("index").push_back(TocItem(pit, 0, item));
367 // Proceed with the rest of the inset.
368 InsetCollapsable::addToToc(cpit);
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 docstring InsetIndex::contextMenu(BufferView const &, int, int) const
384 return from_ascii("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 param_info_.add("name", ParamInfo::LATEX_REQUIRED);
445 docstring InsetPrintIndex::screenLabel() const
447 bool const printall = suffixIs(getCmdName(), '*');
448 bool const multind = buffer().masterBuffer()->params().use_indices;
450 && getParam("type") == from_ascii("idx"))
451 || (getParam("type").empty() && !printall))
453 Buffer const & realbuffer = *buffer().masterBuffer();
454 IndicesList const & indiceslist = realbuffer.params().indiceslist();
455 Index const * index = indiceslist.findShortcut(getParam("type"));
456 if (!index && !printall)
457 return _("Unknown index type!");
458 docstring res = printall ? _("All indexes") : index->index();
460 res += " (" + _("non-active") + ")";
461 else if (contains(getCmdName(), "printsubindex"))
462 res += " (" + _("subindex") + ")";
467 bool InsetPrintIndex::isCompatibleCommand(string const & s)
469 return s == "printindex" || s == "printsubindex"
470 || s == "printindex*" || s == "printsubindex*";
474 void InsetPrintIndex::doDispatch(Cursor & cur, FuncRequest & cmd)
476 switch (cmd.action()) {
478 case LFUN_INSET_MODIFY: {
479 if (cmd.argument() == from_ascii("toggle-subindex")) {
480 string cmd = getCmdName();
481 if (contains(cmd, "printindex"))
482 cmd = subst(cmd, "printindex", "printsubindex");
484 cmd = subst(cmd, "printsubindex", "printindex");
487 } else if (cmd.argument() == from_ascii("check-printindex*")) {
488 string cmd = getCmdName();
489 if (suffixIs(cmd, '*'))
492 setParam("type", docstring());
496 InsetCommandParams p(INDEX_PRINT_CODE);
498 InsetCommand::string2params(to_utf8(cmd.argument()), p);
499 if (p.getCmdName().empty()) {
500 cur.noScreenUpdate();
508 InsetCommand::doDispatch(cur, cmd);
514 bool InsetPrintIndex::getStatus(Cursor & cur, FuncRequest const & cmd,
515 FuncStatus & status) const
517 switch (cmd.action()) {
519 case LFUN_INSET_MODIFY: {
520 if (cmd.argument() == from_ascii("toggle-subindex")) {
521 status.setEnabled(buffer().masterBuffer()->params().use_indices);
522 status.setOnOff(contains(getCmdName(), "printsubindex"));
524 } else if (cmd.argument() == from_ascii("check-printindex*")) {
525 status.setEnabled(buffer().masterBuffer()->params().use_indices);
526 status.setOnOff(suffixIs(getCmdName(), '*'));
528 } if (cmd.getArg(0) == "index_print"
529 && cmd.getArg(1) == "CommandInset") {
530 InsetCommandParams p(INDEX_PRINT_CODE);
531 InsetCommand::string2params(to_utf8(cmd.argument()), p);
532 if (suffixIs(p.getCmdName(), '*')) {
533 status.setEnabled(true);
534 status.setOnOff(false);
537 Buffer const & realbuffer = *buffer().masterBuffer();
538 IndicesList const & indiceslist =
539 realbuffer.params().indiceslist();
540 Index const * index = indiceslist.findShortcut(p["type"]);
541 status.setEnabled(index != 0);
542 status.setOnOff(p["type"] == getParam("type"));
545 return InsetCommand::getStatus(cur, cmd, status);
548 case LFUN_INSET_DIALOG_UPDATE: {
549 status.setEnabled(buffer().masterBuffer()->params().use_indices);
554 return InsetCommand::getStatus(cur, cmd, status);
559 int InsetPrintIndex::latex(odocstream & os, OutputParams const & runparams_in) const
561 if (!buffer().masterBuffer()->params().use_indices) {
562 if (getParam("type") == from_ascii("idx"))
563 os << "\\printindex{}";
566 OutputParams runparams = runparams_in;
567 os << getCommand(runparams);
572 void InsetPrintIndex::validate(LaTeXFeatures & features) const
574 features.require("makeidx");
575 if (buffer().masterBuffer()->params().use_indices)
576 features.require("splitidx");
580 docstring InsetPrintIndex::contextMenu(BufferView const &, int, int) const
582 return buffer().masterBuffer()->params().use_indices ?
583 from_ascii("context-indexprint") : docstring();
587 bool InsetPrintIndex::hasSettings() const
589 return buffer().masterBuffer()->params().use_indices;
595 void parseItem(docstring & s, bool for_output)
597 // this does not yet check for escaped things
598 size_type loc = s.find(from_ascii("@"));
599 if (loc != string::npos) {
605 loc = s.find(from_ascii("|"));
606 if (loc != string::npos)
611 void extractSubentries(docstring const & entry, docstring & main,
612 docstring & sub1, docstring & sub2)
616 size_type const loc = entry.find(from_ascii(" ! "));
617 if (loc == string::npos)
620 main = trim(entry.substr(0, loc));
621 size_t const locend = loc + 3;
622 size_type const loc2 = entry.find(from_ascii(" ! "), locend);
623 if (loc2 == string::npos) {
624 sub1 = trim(entry.substr(locend));
626 sub1 = trim(entry.substr(locend, loc2 - locend));
627 sub2 = trim(entry.substr(loc2 + 3));
638 IndexEntry(docstring const & s, DocIterator const & d)
641 extractSubentries(s, main, sub, subsub);
642 parseItem(main, false);
643 parseItem(sub, false);
644 parseItem(subsub, false);
647 bool equal(IndexEntry const & rhs) const
649 return main == rhs.main && sub == rhs.sub && subsub == rhs.subsub;
652 bool same_sub(IndexEntry const & rhs) const
654 return main == rhs.main && sub == rhs.sub;
657 bool same_main(IndexEntry const & rhs) const
659 return main == rhs.main;
668 bool operator<(IndexEntry const & lhs, IndexEntry const & rhs)
670 return lhs.main < rhs.main
671 || (lhs.main == rhs.main && lhs.sub < rhs.sub)
672 || (lhs.main == rhs.main && lhs.sub == rhs.sub && lhs.subsub < rhs.subsub);
678 docstring InsetPrintIndex::xhtml(XHTMLStream &, OutputParams const & op) const
680 BufferParams const & bp = buffer().masterBuffer()->params();
682 // we do not presently support multiple indices, so we refuse to print
683 // anything but the main index, so as not to generate multiple indices.
684 // NOTE Multiple index support would require some work. The reason
685 // is that the TOC does not know about multiple indices. Either it would
686 // need to be told about them (not a bad idea), or else the index entries
687 // would need to be collected differently, say, during validation.
688 if (bp.use_indices && getParam("type") != from_ascii("idx"))
691 Toc const & toc = buffer().tocBackend().toc("index");
695 // Collection the index entries in a form we can use them.
696 Toc::const_iterator it = toc.begin();
697 Toc::const_iterator const en = toc.end();
698 vector<IndexEntry> entries;
699 for (; it != en; ++it)
700 entries.push_back(IndexEntry(it->str(), it->dit()));
701 stable_sort(entries.begin(), entries.end());
703 Layout const & lay = bp.documentClass().htmlTOCLayout();
704 string const & tocclass = lay.defaultCSSClass();
705 string const tocattr = "class='tochead " + tocclass + "'";
707 // we'll use our own stream, because we are going to defer everything.
708 // that's how we deal with the fact that we're probably inside a standard
709 // paragraph, and we don't want to be.
710 odocstringstream ods;
713 xs << html::StartTag("div", "class='index'");
714 xs << html::StartTag(lay.htmltag(), lay.htmlattr())
716 << html::EndTag(lay.htmltag());
717 xs << html::StartTag("ul", "class='main'");
720 vector<IndexEntry>::const_iterator eit = entries.begin();
721 vector<IndexEntry>::const_iterator const een = entries.end();
722 // tracks whether we are already inside a main entry (1),
723 // a sub-entry (2), or a sub-sub-entry (3). see below for the
726 // the last one we saw
728 int entry_number = -1;
729 for (; eit != een; ++eit) {
730 Paragraph const & par = eit->dit.innerParagraph();
731 if (entry_number == -1 || !eit->equal(last)) {
732 if (entry_number != -1) {
733 // not the first time through the loop, so
734 // close last entry or entries, depending.
736 // close this sub-sub-entry
737 xs << html::EndTag("li");
739 // is this another sub-sub-entry within the same sub-entry?
740 if (!eit->same_sub(last)) {
742 xs << html::EndTag("ul");
747 // the point of the second test here is that we might get
748 // here two ways: (i) by falling through from above; (ii) because,
749 // though the sub-entry hasn't changed, the sub-sub-entry has,
750 // which means that it is the first sub-sub-entry within this
751 // sub-entry. In that case, we do not want to close anything.
752 if (level == 2 && !eit->same_sub(last)) {
754 xs << html::EndTag("li");
756 // is this another sub-entry with the same main entry?
757 if (!eit->same_main(last)) {
759 xs << html::EndTag("ul");
764 // again, we can get here two ways: from above, or because we have
765 // found the first sub-entry. in the latter case, we do not want to
767 if (level == 1 && !eit->same_main(last)) {
769 xs << html::EndTag("li");
774 // we'll be starting new entries
777 // We need to use our own stream, since we will have to
778 // modify what we get back.
779 odocstringstream ent;
780 XHTMLStream entstream(ent);
781 OutputParams ours = op;
783 par.simpleLyXHTMLOnePar(buffer(), entstream, ours, dummy);
785 // these will contain XHTML versions of the main entry, etc
786 // remember that everything will already have been escaped,
787 // so we'll need to use NextRaw() during output.
791 extractSubentries(ent.str(), main, sub, subsub);
792 parseItem(main, true);
793 parseItem(sub, true);
794 parseItem(subsub, true);
797 // another subsubentry
798 xs << html::StartTag("li", "class='subsubentry'")
799 << XHTMLStream::NextRaw() << subsub;
800 } else if (level == 2) {
801 // there are two ways we can be here:
802 // (i) we can actually be inside a sub-entry already and be about
803 // to output the first sub-sub-entry. in this case, our sub
804 // and the last sub will be the same.
805 // (ii) we can just have closed a sub-entry, possibly after also
806 // closing a list of sub-sub-entries. here our sub and the last
807 // sub are different.
808 // only in the latter case do we need to output the new sub-entry.
809 // note that in this case, too, though, the sub-entry might already
810 // have a sub-sub-entry.
811 if (eit->sub != last.sub)
812 xs << html::StartTag("li", "class='subentry'")
813 << XHTMLStream::NextRaw() << sub;
814 if (!subsub.empty()) {
815 // it's actually a subsubentry, so we need to start that list
817 xs << html::StartTag("ul", "class='subsubentry'")
818 << html::StartTag("li", "class='subsubentry'")
819 << XHTMLStream::NextRaw() << subsub;
823 // there are also two ways we can be here:
824 // (i) we can actually be inside an entry already and be about
825 // to output the first sub-entry. in this case, our main
826 // and the last main will be the same.
827 // (ii) we can just have closed an entry, possibly after also
828 // closing a list of sub-entries. here our main and the last
829 // main are different.
830 // only in the latter case do we need to output the new main entry.
831 // note that in this case, too, though, the main entry might already
832 // have a sub-entry, or even a sub-sub-entry.
833 if (eit->main != last.main)
834 xs << html::StartTag("li", "class='main'") << main;
836 // there's a sub-entry, too
838 xs << html::StartTag("ul", "class='subentry'")
839 << html::StartTag("li", "class='subentry'")
840 << XHTMLStream::NextRaw() << sub;
842 if (!subsub.empty()) {
843 // and a sub-sub-entry
845 xs << html::StartTag("ul", "class='subsubentry'")
846 << html::StartTag("li", "class='subsubentry'")
847 << XHTMLStream::NextRaw() << subsub;
853 // finally, then, we can output the index link itself
854 string const parattr = "href='#" + par.magicLabel() + "'";
855 xs << (entry_number == 0 ? ":" : ",");
856 xs << " " << html::StartTag("a", parattr)
857 << ++entry_number << html::EndTag("a");
860 // now we have to close all the open levels
862 xs << html::EndTag("li") << html::EndTag("ul");
866 xs << html::EndTag("div");