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(otexstream & 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 otexstream ots(ourlatex);
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.
139 for (size_t n = 0; n < spart.size(); ++n) {
141 spart2 += runparams.encoding->latexChar(spart[n]);
142 } catch (EncodingException & /* e */) {
143 LYXERR0("Uncodable character in index entry. Sorting might be wrong!");
146 if (spart != spart2 && !runparams.dryrun) {
147 // FIXME: warning should be passed to the error dialog
148 frontend::Alert::warning(_("Index sorting failed"),
149 bformat(_("LyX's automatic index sorting algorithm faced\n"
150 "problems with the entry '%1$s'.\n"
151 "Please specify the sorting of this entry manually, as\n"
152 "explained in the User Guide."), spart));
154 // remove remaining \'s for the sorting part
155 docstring const ppart =
156 subst(spart2, from_ascii("\\"), docstring());
159 i += count_char(ppart, '\n');
161 docstring const tpart = *it;
163 i += count_char(tpart, '\n');
164 if (it2 < levels_plain.end())
167 // write the bit that followed "|"
170 i += count_char(cmd, '\n');
177 int InsetIndex::docbook(odocstream & os, OutputParams const & runparams) const
179 os << "<indexterm><primary>";
180 int const i = InsetText::docbook(os, runparams);
181 os << "</primary></indexterm>";
186 docstring InsetIndex::xhtml(XHTMLStream & xs, OutputParams const &) const
188 // we just print an anchor, taking the paragraph ID from
189 // our own interior paragraph, which doesn't get printed
190 std::string const magic = paragraphs().front().magicLabel();
191 std::string const attr = "id='" + magic + "'";
192 xs << html::CompTag("a", attr);
197 bool InsetIndex::showInsetDialog(BufferView * bv) const
199 bv->showDialog("index", params2string(params_),
200 const_cast<InsetIndex *>(this));
205 void InsetIndex::doDispatch(Cursor & cur, FuncRequest & cmd)
207 switch (cmd.action()) {
209 case LFUN_INSET_MODIFY: {
210 if (cmd.getArg(0) == "changetype") {
211 cur.recordUndoInset(ATOMIC_UNDO, this);
212 params_.index = from_utf8(cmd.getArg(1));
215 InsetIndexParams params;
216 InsetIndex::string2params(to_utf8(cmd.argument()), params);
217 cur.recordUndoInset(ATOMIC_UNDO, this);
218 params_.index = params.index;
219 // what we really want here is a TOC update, but that means
220 // a full buffer update
221 cur.forceBufferUpdate();
225 case LFUN_INSET_DIALOG_UPDATE:
226 cur.bv().updateDialog("index", params2string(params_));
230 InsetCollapsable::doDispatch(cur, cmd);
236 bool InsetIndex::getStatus(Cursor & cur, FuncRequest const & cmd,
237 FuncStatus & flag) const
239 switch (cmd.action()) {
241 case LFUN_INSET_MODIFY:
242 if (cmd.getArg(0) == "changetype") {
243 docstring const newtype = from_utf8(cmd.getArg(1));
244 Buffer const & realbuffer = *buffer().masterBuffer();
245 IndicesList const & indiceslist = realbuffer.params().indiceslist();
246 Index const * index = indiceslist.findShortcut(newtype);
247 flag.setEnabled(index != 0);
249 from_utf8(cmd.getArg(1)) == params_.index);
252 flag.setEnabled(true);
255 case LFUN_INSET_DIALOG_UPDATE: {
256 Buffer const & realbuffer = *buffer().masterBuffer();
257 flag.setEnabled(realbuffer.params().use_indices);
262 return InsetCollapsable::getStatus(cur, cmd, flag);
267 ColorCode InsetIndex::labelColor() const
269 if (params_.index.empty() || params_.index == from_ascii("idx"))
270 return InsetCollapsable::labelColor();
272 ColorCode c = lcolor.getFromLyXName(to_utf8(params_.index));
274 c = InsetCollapsable::labelColor();
279 docstring InsetIndex::toolTip(BufferView const &, int, int) const
281 docstring tip = _("Index Entry");
282 if (buffer().params().use_indices && !params_.index.empty()) {
283 Buffer const & realbuffer = *buffer().masterBuffer();
284 IndicesList const & indiceslist = realbuffer.params().indiceslist();
286 Index const * index = indiceslist.findShortcut(params_.index);
288 tip += _("unknown type!");
290 tip += index->index();
294 return toolTipText(tip);
298 docstring const InsetIndex::buttonLabel(BufferView const & bv) const
300 InsetLayout const & il = getLayout();
301 docstring label = translateIfPossible(il.labelstring());
303 if (buffer().params().use_indices && !params_.index.empty()) {
304 Buffer const & realbuffer = *buffer().masterBuffer();
305 IndicesList const & indiceslist = realbuffer.params().indiceslist();
307 Index const * index = indiceslist.findShortcut(params_.index);
309 label += _("unknown type!");
311 label += index->index();
315 if (!il.contentaslabel() || geometry(bv) != ButtonOnly)
317 return getNewLabel(label);
321 void InsetIndex::write(ostream & os) const
323 os << to_utf8(name());
325 InsetCollapsable::write(os);
329 void InsetIndex::read(Lexer & lex)
332 InsetCollapsable::read(lex);
336 string InsetIndex::params2string(InsetIndexParams const & params)
345 void InsetIndex::string2params(string const & in, InsetIndexParams & params)
347 params = InsetIndexParams();
351 istringstream data(in);
354 lex.setContext("InsetIndex::string2params");
360 void InsetIndex::addToToc(DocIterator const & cpit) const
362 DocIterator pit = cpit;
363 pit.push_back(CursorSlice(const_cast<InsetIndex &>(*this)));
365 text().forToc(str, TOC_ENTRY_LENGTH);
366 buffer().tocBackend().toc("index").push_back(TocItem(pit, 0, str));
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::contextMenuName() 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");
488 } else if (cmd.argument() == from_ascii("check-printindex*")) {
489 string cmd = getCmdName();
490 if (suffixIs(cmd, '*'))
494 setParam("type", docstring());
498 InsetCommandParams p(INDEX_PRINT_CODE);
500 InsetCommand::string2params(to_utf8(cmd.argument()), p);
501 if (p.getCmdName().empty()) {
502 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 int 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{}";
568 OutputParams runparams = runparams_in;
569 os << getCommand(runparams);
574 void InsetPrintIndex::validate(LaTeXFeatures & features) const
576 features.require("makeidx");
577 if (buffer().masterBuffer()->params().use_indices)
578 features.require("splitidx");
582 docstring InsetPrintIndex::contextMenuName() const
584 return buffer().masterBuffer()->params().use_indices ?
585 from_ascii("context-indexprint") : docstring();
589 bool InsetPrintIndex::hasSettings() const
591 return buffer().masterBuffer()->params().use_indices;
597 void parseItem(docstring & s, bool for_output)
599 // this does not yet check for escaped things
600 size_type loc = s.find(from_ascii("@"));
601 if (loc != string::npos) {
607 loc = s.find(from_ascii("|"));
608 if (loc != string::npos)
613 void extractSubentries(docstring const & entry, docstring & main,
614 docstring & sub1, docstring & sub2)
618 size_type const loc = entry.find(from_ascii(" ! "));
619 if (loc == string::npos)
622 main = trim(entry.substr(0, loc));
623 size_t const locend = loc + 3;
624 size_type const loc2 = entry.find(from_ascii(" ! "), locend);
625 if (loc2 == string::npos) {
626 sub1 = trim(entry.substr(locend));
628 sub1 = trim(entry.substr(locend, loc2 - locend));
629 sub2 = trim(entry.substr(loc2 + 3));
640 IndexEntry(docstring const & s, DocIterator const & d)
643 extractSubentries(s, main, sub, subsub);
644 parseItem(main, false);
645 parseItem(sub, false);
646 parseItem(subsub, false);
649 bool equal(IndexEntry const & rhs) const
651 return main == rhs.main && sub == rhs.sub && subsub == rhs.subsub;
654 bool same_sub(IndexEntry const & rhs) const
656 return main == rhs.main && sub == rhs.sub;
659 bool same_main(IndexEntry const & rhs) const
661 return main == rhs.main;
670 bool operator<(IndexEntry const & lhs, IndexEntry const & rhs)
672 return lhs.main < rhs.main
673 || (lhs.main == rhs.main && lhs.sub < rhs.sub)
674 || (lhs.main == rhs.main && lhs.sub == rhs.sub && lhs.subsub < rhs.subsub);
680 docstring InsetPrintIndex::xhtml(XHTMLStream &, OutputParams const & op) const
682 BufferParams const & bp = buffer().masterBuffer()->params();
684 // we do not presently support multiple indices, so we refuse to print
685 // anything but the main index, so as not to generate multiple indices.
686 // NOTE Multiple index support would require some work. The reason
687 // is that the TOC does not know about multiple indices. Either it would
688 // need to be told about them (not a bad idea), or else the index entries
689 // would need to be collected differently, say, during validation.
690 if (bp.use_indices && getParam("type") != from_ascii("idx"))
693 Toc const & toc = buffer().tocBackend().toc("index");
697 // Collection the index entries in a form we can use them.
698 Toc::const_iterator it = toc.begin();
699 Toc::const_iterator const en = toc.end();
700 vector<IndexEntry> entries;
701 for (; it != en; ++it)
702 entries.push_back(IndexEntry(it->str(), it->dit()));
703 stable_sort(entries.begin(), entries.end());
705 Layout const & lay = bp.documentClass().htmlTOCLayout();
706 string const & tocclass = lay.defaultCSSClass();
707 string const tocattr = "class='tochead " + tocclass + "'";
709 // we'll use our own stream, because we are going to defer everything.
710 // that's how we deal with the fact that we're probably inside a standard
711 // paragraph, and we don't want to be.
712 odocstringstream ods;
715 xs << html::StartTag("div", "class='index'");
716 xs << html::StartTag(lay.htmltag(), lay.htmlattr())
718 << html::EndTag(lay.htmltag());
719 xs << html::StartTag("ul", "class='main'");
722 vector<IndexEntry>::const_iterator eit = entries.begin();
723 vector<IndexEntry>::const_iterator const een = entries.end();
724 // tracks whether we are already inside a main entry (1),
725 // a sub-entry (2), or a sub-sub-entry (3). see below for the
728 // the last one we saw
730 int entry_number = -1;
731 for (; eit != een; ++eit) {
732 Paragraph const & par = eit->dit.innerParagraph();
733 if (entry_number == -1 || !eit->equal(last)) {
734 if (entry_number != -1) {
735 // not the first time through the loop, so
736 // close last entry or entries, depending.
738 // close this sub-sub-entry
739 xs << html::EndTag("li");
741 // is this another sub-sub-entry within the same sub-entry?
742 if (!eit->same_sub(last)) {
744 xs << html::EndTag("ul");
749 // the point of the second test here is that we might get
750 // here two ways: (i) by falling through from above; (ii) because,
751 // though the sub-entry hasn't changed, the sub-sub-entry has,
752 // which means that it is the first sub-sub-entry within this
753 // sub-entry. In that case, we do not want to close anything.
754 if (level == 2 && !eit->same_sub(last)) {
756 xs << html::EndTag("li");
758 // is this another sub-entry with the same main entry?
759 if (!eit->same_main(last)) {
761 xs << html::EndTag("ul");
766 // again, we can get here two ways: from above, or because we have
767 // found the first sub-entry. in the latter case, we do not want to
769 if (level == 1 && !eit->same_main(last)) {
771 xs << html::EndTag("li");
776 // we'll be starting new entries
779 // We need to use our own stream, since we will have to
780 // modify what we get back.
781 odocstringstream ent;
782 XHTMLStream entstream(ent);
783 OutputParams ours = op;
785 par.simpleLyXHTMLOnePar(buffer(), entstream, ours, dummy);
787 // these will contain XHTML versions of the main entry, etc
788 // remember that everything will already have been escaped,
789 // so we'll need to use NextRaw() during output.
793 extractSubentries(ent.str(), main, sub, subsub);
794 parseItem(main, true);
795 parseItem(sub, true);
796 parseItem(subsub, true);
799 // another subsubentry
800 xs << html::StartTag("li", "class='subsubentry'")
801 << XHTMLStream::ESCAPE_NONE << subsub;
802 } else if (level == 2) {
803 // there are two ways we can be here:
804 // (i) we can actually be inside a sub-entry already and be about
805 // to output the first sub-sub-entry. in this case, our sub
806 // and the last sub will be the same.
807 // (ii) we can just have closed a sub-entry, possibly after also
808 // closing a list of sub-sub-entries. here our sub and the last
809 // sub are different.
810 // only in the latter case do we need to output the new sub-entry.
811 // note that in this case, too, though, the sub-entry might already
812 // have a sub-sub-entry.
813 if (eit->sub != last.sub)
814 xs << html::StartTag("li", "class='subentry'")
815 << XHTMLStream::ESCAPE_NONE << sub;
816 if (!subsub.empty()) {
817 // it's actually a subsubentry, so we need to start that list
819 xs << html::StartTag("ul", "class='subsubentry'")
820 << html::StartTag("li", "class='subsubentry'")
821 << XHTMLStream::ESCAPE_NONE << subsub;
825 // there are also two ways we can be here:
826 // (i) we can actually be inside an entry already and be about
827 // to output the first sub-entry. in this case, our main
828 // and the last main will be the same.
829 // (ii) we can just have closed an entry, possibly after also
830 // closing a list of sub-entries. here our main and the last
831 // main are different.
832 // only in the latter case do we need to output the new main entry.
833 // note that in this case, too, though, the main entry might already
834 // have a sub-entry, or even a sub-sub-entry.
835 if (eit->main != last.main)
836 xs << html::StartTag("li", "class='main'") << main;
838 // there's a sub-entry, too
840 xs << html::StartTag("ul", "class='subentry'")
841 << html::StartTag("li", "class='subentry'")
842 << XHTMLStream::ESCAPE_NONE << sub;
844 if (!subsub.empty()) {
845 // and a sub-sub-entry
847 xs << html::StartTag("ul", "class='subsubentry'")
848 << html::StartTag("li", "class='subsubentry'")
849 << XHTMLStream::ESCAPE_NONE << subsub;
855 // finally, then, we can output the index link itself
856 string const parattr = "href='#" + par.magicLabel() + "'";
857 xs << (entry_number == 0 ? ":" : ",");
858 xs << " " << html::StartTag("a", parattr)
859 << ++entry_number << html::EndTag("a");
862 // now we have to close all the open levels
864 xs << html::EndTag("li") << html::EndTag("ul");
868 xs << html::EndTag("div");