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 void InsetIndex::latex(otexstream & os, OutputParams const & runparams_in) const
62 OutputParams runparams(runparams_in);
63 runparams.inIndexEntry = true;
65 if (buffer().masterBuffer()->params().use_indices && !params_.index.empty()
66 && params_.index != "idx") {
75 // get contents of InsetText as LaTeX and plaintext
77 odocstringstream ourlatex;
78 otexstream ots(ourlatex, texrow);
79 InsetText::latex(ots, 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());
159 docstring const tpart = *it;
161 if (it2 < levels_plain.end())
164 // write the bit that followed "|"
172 int InsetIndex::docbook(odocstream & os, OutputParams const & runparams) const
174 os << "<indexterm><primary>";
175 int const i = InsetText::docbook(os, runparams);
176 os << "</primary></indexterm>";
181 docstring InsetIndex::xhtml(XHTMLStream & xs, OutputParams const &) const
183 // we just print an anchor, taking the paragraph ID from
184 // our own interior paragraph, which doesn't get printed
185 std::string const magic = paragraphs().front().magicLabel();
186 std::string const attr = "id='" + magic + "'";
187 xs << html::CompTag("a", attr);
192 bool InsetIndex::showInsetDialog(BufferView * bv) const
194 bv->showDialog("index", params2string(params_),
195 const_cast<InsetIndex *>(this));
200 void InsetIndex::doDispatch(Cursor & cur, FuncRequest & cmd)
202 switch (cmd.action()) {
204 case LFUN_INSET_MODIFY: {
205 if (cmd.getArg(0) == "changetype") {
206 cur.recordUndoInset(ATOMIC_UNDO, this);
207 params_.index = from_utf8(cmd.getArg(1));
210 InsetIndexParams params;
211 InsetIndex::string2params(to_utf8(cmd.argument()), params);
212 cur.recordUndoInset(ATOMIC_UNDO, this);
213 params_.index = params.index;
214 // what we really want here is a TOC update, but that means
215 // a full buffer update
216 cur.forceBufferUpdate();
220 case LFUN_INSET_DIALOG_UPDATE:
221 cur.bv().updateDialog("index", params2string(params_));
225 InsetCollapsable::doDispatch(cur, cmd);
231 bool InsetIndex::getStatus(Cursor & cur, FuncRequest const & cmd,
232 FuncStatus & flag) const
234 switch (cmd.action()) {
236 case LFUN_INSET_MODIFY:
237 if (cmd.getArg(0) == "changetype") {
238 docstring const newtype = from_utf8(cmd.getArg(1));
239 Buffer const & realbuffer = *buffer().masterBuffer();
240 IndicesList const & indiceslist = realbuffer.params().indiceslist();
241 Index const * index = indiceslist.findShortcut(newtype);
242 flag.setEnabled(index != 0);
244 from_utf8(cmd.getArg(1)) == params_.index);
247 flag.setEnabled(true);
250 case LFUN_INSET_DIALOG_UPDATE: {
251 Buffer const & realbuffer = *buffer().masterBuffer();
252 flag.setEnabled(realbuffer.params().use_indices);
257 return InsetCollapsable::getStatus(cur, cmd, flag);
262 ColorCode InsetIndex::labelColor() const
264 if (params_.index.empty() || params_.index == from_ascii("idx"))
265 return InsetCollapsable::labelColor();
267 ColorCode c = lcolor.getFromLyXName(to_utf8(params_.index));
269 c = InsetCollapsable::labelColor();
274 docstring InsetIndex::toolTip(BufferView const &, int, int) const
276 docstring tip = _("Index Entry");
277 if (buffer().params().use_indices && !params_.index.empty()) {
278 Buffer const & realbuffer = *buffer().masterBuffer();
279 IndicesList const & indiceslist = realbuffer.params().indiceslist();
281 Index const * index = indiceslist.findShortcut(params_.index);
283 tip += _("unknown type!");
285 tip += index->index();
289 return toolTipText(tip);
293 docstring const InsetIndex::buttonLabel(BufferView const & bv) const
295 InsetLayout const & il = getLayout();
296 docstring label = translateIfPossible(il.labelstring());
298 if (buffer().params().use_indices && !params_.index.empty()) {
299 Buffer const & realbuffer = *buffer().masterBuffer();
300 IndicesList const & indiceslist = realbuffer.params().indiceslist();
302 Index const * index = indiceslist.findShortcut(params_.index);
304 label += _("unknown type!");
306 label += index->index();
310 if (!il.contentaslabel() || geometry(bv) != ButtonOnly)
312 return getNewLabel(label);
316 void InsetIndex::write(ostream & os) const
318 os << to_utf8(layoutName());
320 InsetCollapsable::write(os);
324 void InsetIndex::read(Lexer & lex)
327 InsetCollapsable::read(lex);
331 string InsetIndex::params2string(InsetIndexParams const & params)
340 void InsetIndex::string2params(string const & in, InsetIndexParams & params)
342 params = InsetIndexParams();
346 istringstream data(in);
349 lex.setContext("InsetIndex::string2params");
355 void InsetIndex::addToToc(DocIterator const & cpit) const
357 DocIterator pit = cpit;
358 pit.push_back(CursorSlice(const_cast<InsetIndex &>(*this)));
360 text().forToc(str, TOC_ENTRY_LENGTH);
361 buffer().tocBackend().toc("index").push_back(TocItem(pit, 0, str));
362 // Proceed with the rest of the inset.
363 InsetCollapsable::addToToc(cpit);
367 void InsetIndex::validate(LaTeXFeatures & features) const
369 if (buffer().masterBuffer()->params().use_indices
370 && !params_.index.empty()
371 && params_.index != "idx")
372 features.require("splitidx");
373 InsetCollapsable::validate(features);
377 docstring InsetIndex::contextMenuName() const
379 return from_ascii("context-index");
383 bool InsetIndex::hasSettings() const
385 return buffer().masterBuffer()->params().use_indices;
391 /////////////////////////////////////////////////////////////////////
395 ///////////////////////////////////////////////////////////////////////
398 void InsetIndexParams::write(ostream & os) const
402 os << to_utf8(index);
409 void InsetIndexParams::read(Lexer & lex)
412 index = lex.getDocString();
414 index = from_ascii("idx");
418 /////////////////////////////////////////////////////////////////////
422 ///////////////////////////////////////////////////////////////////////
424 InsetPrintIndex::InsetPrintIndex(Buffer * buf, InsetCommandParams const & p)
425 : InsetCommand(buf, p)
429 ParamInfo const & InsetPrintIndex::findInfo(string const & /* cmdName */)
431 static ParamInfo param_info_;
432 if (param_info_.empty()) {
433 param_info_.add("type", ParamInfo::LATEX_OPTIONAL);
434 param_info_.add("name", ParamInfo::LATEX_REQUIRED);
440 docstring InsetPrintIndex::screenLabel() const
442 bool const printall = suffixIs(getCmdName(), '*');
443 bool const multind = buffer().masterBuffer()->params().use_indices;
445 && getParam("type") == from_ascii("idx"))
446 || (getParam("type").empty() && !printall))
448 Buffer const & realbuffer = *buffer().masterBuffer();
449 IndicesList const & indiceslist = realbuffer.params().indiceslist();
450 Index const * index = indiceslist.findShortcut(getParam("type"));
451 if (!index && !printall)
452 return _("Unknown index type!");
453 docstring res = printall ? _("All indexes") : index->index();
455 res += " (" + _("non-active") + ")";
456 else if (contains(getCmdName(), "printsubindex"))
457 res += " (" + _("subindex") + ")";
462 bool InsetPrintIndex::isCompatibleCommand(string const & s)
464 return s == "printindex" || s == "printsubindex"
465 || s == "printindex*" || s == "printsubindex*";
469 void InsetPrintIndex::doDispatch(Cursor & cur, FuncRequest & cmd)
471 switch (cmd.action()) {
473 case LFUN_INSET_MODIFY: {
474 if (cmd.argument() == from_ascii("toggle-subindex")) {
475 string cmd = getCmdName();
476 if (contains(cmd, "printindex"))
477 cmd = subst(cmd, "printindex", "printsubindex");
479 cmd = subst(cmd, "printsubindex", "printindex");
483 } else if (cmd.argument() == from_ascii("check-printindex*")) {
484 string cmd = getCmdName();
485 if (suffixIs(cmd, '*'))
489 setParam("type", docstring());
493 InsetCommandParams p(INDEX_PRINT_CODE);
495 InsetCommand::string2params(to_utf8(cmd.argument()), p);
496 if (p.getCmdName().empty()) {
497 cur.noScreenUpdate();
505 InsetCommand::doDispatch(cur, cmd);
511 bool InsetPrintIndex::getStatus(Cursor & cur, FuncRequest const & cmd,
512 FuncStatus & status) const
514 switch (cmd.action()) {
516 case LFUN_INSET_MODIFY: {
517 if (cmd.argument() == from_ascii("toggle-subindex")) {
518 status.setEnabled(buffer().masterBuffer()->params().use_indices);
519 status.setOnOff(contains(getCmdName(), "printsubindex"));
521 } else if (cmd.argument() == from_ascii("check-printindex*")) {
522 status.setEnabled(buffer().masterBuffer()->params().use_indices);
523 status.setOnOff(suffixIs(getCmdName(), '*'));
525 } if (cmd.getArg(0) == "index_print"
526 && cmd.getArg(1) == "CommandInset") {
527 InsetCommandParams p(INDEX_PRINT_CODE);
528 InsetCommand::string2params(to_utf8(cmd.argument()), p);
529 if (suffixIs(p.getCmdName(), '*')) {
530 status.setEnabled(true);
531 status.setOnOff(false);
534 Buffer const & realbuffer = *buffer().masterBuffer();
535 IndicesList const & indiceslist =
536 realbuffer.params().indiceslist();
537 Index const * index = indiceslist.findShortcut(p["type"]);
538 status.setEnabled(index != 0);
539 status.setOnOff(p["type"] == getParam("type"));
542 return InsetCommand::getStatus(cur, cmd, status);
545 case LFUN_INSET_DIALOG_UPDATE: {
546 status.setEnabled(buffer().masterBuffer()->params().use_indices);
551 return InsetCommand::getStatus(cur, cmd, status);
556 void InsetPrintIndex::latex(otexstream & os, OutputParams const & runparams_in) const
558 if (!buffer().masterBuffer()->params().use_indices) {
559 if (getParam("type") == from_ascii("idx"))
560 os << "\\printindex{}";
563 OutputParams runparams = runparams_in;
564 os << getCommand(runparams);
568 void InsetPrintIndex::validate(LaTeXFeatures & features) const
570 features.require("makeidx");
571 if (buffer().masterBuffer()->params().use_indices)
572 features.require("splitidx");
576 docstring InsetPrintIndex::contextMenuName() const
578 return buffer().masterBuffer()->params().use_indices ?
579 from_ascii("context-indexprint") : docstring();
583 bool InsetPrintIndex::hasSettings() const
585 return buffer().masterBuffer()->params().use_indices;
591 void parseItem(docstring & s, bool for_output)
593 // this does not yet check for escaped things
594 size_type loc = s.find(from_ascii("@"));
595 if (loc != string::npos) {
601 loc = s.find(from_ascii("|"));
602 if (loc != string::npos)
607 void extractSubentries(docstring const & entry, docstring & main,
608 docstring & sub1, docstring & sub2)
612 size_type const loc = entry.find(from_ascii(" ! "));
613 if (loc == string::npos)
616 main = trim(entry.substr(0, loc));
617 size_t const locend = loc + 3;
618 size_type const loc2 = entry.find(from_ascii(" ! "), locend);
619 if (loc2 == string::npos) {
620 sub1 = trim(entry.substr(locend));
622 sub1 = trim(entry.substr(locend, loc2 - locend));
623 sub2 = trim(entry.substr(loc2 + 3));
634 IndexEntry(docstring const & s, DocIterator const & d)
637 extractSubentries(s, main, sub, subsub);
638 parseItem(main, false);
639 parseItem(sub, false);
640 parseItem(subsub, false);
643 bool equal(IndexEntry const & rhs) const
645 return main == rhs.main && sub == rhs.sub && subsub == rhs.subsub;
648 bool same_sub(IndexEntry const & rhs) const
650 return main == rhs.main && sub == rhs.sub;
653 bool same_main(IndexEntry const & rhs) const
655 return main == rhs.main;
664 bool operator<(IndexEntry const & lhs, IndexEntry const & rhs)
666 return lhs.main < rhs.main
667 || (lhs.main == rhs.main && lhs.sub < rhs.sub)
668 || (lhs.main == rhs.main && lhs.sub == rhs.sub && lhs.subsub < rhs.subsub);
674 docstring InsetPrintIndex::xhtml(XHTMLStream &, OutputParams const & op) const
676 BufferParams const & bp = buffer().masterBuffer()->params();
678 // we do not presently support multiple indices, so we refuse to print
679 // anything but the main index, so as not to generate multiple indices.
680 // NOTE Multiple index support would require some work. The reason
681 // is that the TOC does not know about multiple indices. Either it would
682 // need to be told about them (not a bad idea), or else the index entries
683 // would need to be collected differently, say, during validation.
684 if (bp.use_indices && getParam("type") != from_ascii("idx"))
687 Toc const & toc = buffer().tocBackend().toc("index");
691 // Collection the index entries in a form we can use them.
692 Toc::const_iterator it = toc.begin();
693 Toc::const_iterator const en = toc.end();
694 vector<IndexEntry> entries;
695 for (; it != en; ++it)
696 entries.push_back(IndexEntry(it->str(), it->dit()));
697 stable_sort(entries.begin(), entries.end());
699 Layout const & lay = bp.documentClass().htmlTOCLayout();
700 string const & tocclass = lay.defaultCSSClass();
701 string const tocattr = "class='tochead " + tocclass + "'";
703 // we'll use our own stream, because we are going to defer everything.
704 // that's how we deal with the fact that we're probably inside a standard
705 // paragraph, and we don't want to be.
706 odocstringstream ods;
709 xs << html::StartTag("div", "class='index'");
710 xs << html::StartTag(lay.htmltag(), lay.htmlattr())
712 << html::EndTag(lay.htmltag());
713 xs << html::StartTag("ul", "class='main'");
716 vector<IndexEntry>::const_iterator eit = entries.begin();
717 vector<IndexEntry>::const_iterator const een = entries.end();
718 // tracks whether we are already inside a main entry (1),
719 // a sub-entry (2), or a sub-sub-entry (3). see below for the
722 // the last one we saw
724 int entry_number = -1;
725 for (; eit != een; ++eit) {
726 Paragraph const & par = eit->dit.innerParagraph();
727 if (entry_number == -1 || !eit->equal(last)) {
728 if (entry_number != -1) {
729 // not the first time through the loop, so
730 // close last entry or entries, depending.
732 // close this sub-sub-entry
733 xs << html::EndTag("li") << html::CR();
734 // is this another sub-sub-entry within the same sub-entry?
735 if (!eit->same_sub(last)) {
737 xs << html::EndTag("ul") << html::CR();
741 // the point of the second test here is that we might get
742 // here two ways: (i) by falling through from above; (ii) because,
743 // though the sub-entry hasn't changed, the sub-sub-entry has,
744 // which means that it is the first sub-sub-entry within this
745 // sub-entry. In that case, we do not want to close anything.
746 if (level == 2 && !eit->same_sub(last)) {
748 xs << html::EndTag("li") << html::CR();
749 // is this another sub-entry with the same main entry?
750 if (!eit->same_main(last)) {
752 xs << html::EndTag("ul") << html::CR();
756 // again, we can get here two ways: from above, or because we have
757 // found the first sub-entry. in the latter case, we do not want to
759 if (level == 1 && !eit->same_main(last)) {
761 xs << html::EndTag("li") << html::CR();
765 // we'll be starting new entries
768 // We need to use our own stream, since we will have to
769 // modify what we get back.
770 odocstringstream ent;
771 XHTMLStream entstream(ent);
772 OutputParams ours = op;
774 par.simpleLyXHTMLOnePar(buffer(), entstream, ours, dummy);
776 // these will contain XHTML versions of the main entry, etc
777 // remember that everything will already have been escaped,
778 // so we'll need to use NextRaw() during output.
782 extractSubentries(ent.str(), main, sub, subsub);
783 parseItem(main, true);
784 parseItem(sub, true);
785 parseItem(subsub, true);
788 // another subsubentry
789 xs << html::StartTag("li", "class='subsubentry'")
790 << XHTMLStream::ESCAPE_NONE << subsub;
791 } else if (level == 2) {
792 // there are two ways we can be here:
793 // (i) we can actually be inside a sub-entry already and be about
794 // to output the first sub-sub-entry. in this case, our sub
795 // and the last sub will be the same.
796 // (ii) we can just have closed a sub-entry, possibly after also
797 // closing a list of sub-sub-entries. here our sub and the last
798 // sub are different.
799 // only in the latter case do we need to output the new sub-entry.
800 // note that in this case, too, though, the sub-entry might already
801 // have a sub-sub-entry.
802 if (eit->sub != last.sub)
803 xs << html::StartTag("li", "class='subentry'")
804 << XHTMLStream::ESCAPE_NONE << sub;
805 if (!subsub.empty()) {
806 // it's actually a subsubentry, so we need to start that list
808 << html::StartTag("ul", "class='subsubentry'")
809 << html::StartTag("li", "class='subsubentry'")
810 << XHTMLStream::ESCAPE_NONE << subsub;
814 // there are also two ways we can be here:
815 // (i) we can actually be inside an entry already and be about
816 // to output the first sub-entry. in this case, our main
817 // and the last main will be the same.
818 // (ii) we can just have closed an entry, possibly after also
819 // closing a list of sub-entries. here our main and the last
820 // main are different.
821 // only in the latter case do we need to output the new main entry.
822 // note that in this case, too, though, the main entry might already
823 // have a sub-entry, or even a sub-sub-entry.
824 if (eit->main != last.main)
825 xs << html::StartTag("li", "class='main'") << main;
827 // there's a sub-entry, too
829 << html::StartTag("ul", "class='subentry'")
830 << html::StartTag("li", "class='subentry'")
831 << XHTMLStream::ESCAPE_NONE << sub;
833 if (!subsub.empty()) {
834 // and a sub-sub-entry
836 << html::StartTag("ul", "class='subsubentry'")
837 << html::StartTag("li", "class='subsubentry'")
838 << XHTMLStream::ESCAPE_NONE << subsub;
844 // finally, then, we can output the index link itself
845 string const parattr = "href='#" + par.magicLabel() + "'";
846 xs << (entry_number == 0 ? ":" : ",");
847 xs << " " << html::StartTag("a", parattr)
848 << ++entry_number << html::EndTag("a");
851 // now we have to close all the open levels
853 xs << html::EndTag("li") << html::EndTag("ul") << html::CR();
856 xs << html::EndTag("div") << html::CR();