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"
19 #include "DispatchResult.h"
21 #include "FuncRequest.h"
22 #include "FuncStatus.h"
23 #include "IndicesList.h"
24 #include "LaTeXFeatures.h"
26 #include "MetricsInfo.h"
27 #include "output_latex.h"
28 #include "output_xhtml.h"
30 #include "TocBackend.h"
32 #include "support/debug.h"
33 #include "support/docstream.h"
34 #include "support/gettext.h"
35 #include "support/lstrings.h"
37 #include "frontends/alert.h"
42 using namespace lyx::support;
46 /////////////////////////////////////////////////////////////////////
50 ///////////////////////////////////////////////////////////////////////
53 InsetIndex::InsetIndex(Buffer * buf, InsetIndexParams const & params)
54 : InsetCollapsable(buf), params_(params)
58 int InsetIndex::latex(odocstream & os,
59 OutputParams const & runparams_in) const
61 OutputParams runparams(runparams_in);
62 runparams.inIndexEntry = true;
64 if (buffer().masterBuffer()->params().use_indices && !params_.index.empty()
65 && params_.index != "idx") {
75 // get contents of InsetText as LaTeX and plaintext
76 odocstringstream ourlatex;
77 InsetText::latex(ourlatex, runparams);
78 odocstringstream ourplain;
79 InsetText::plaintext(ourplain, runparams);
80 docstring latexstr = ourlatex.str();
81 docstring plainstr = ourplain.str();
83 // this will get what follows | if anything does
86 // check for the | separator
87 // FIXME This would go wrong on an escaped "|", but
88 // how far do we want to go here?
89 size_t pos = latexstr.find(from_ascii("|"));
90 if (pos != docstring::npos) {
91 // put the bit after "|" into cmd...
92 cmd = latexstr.substr(pos + 1);
93 // ...and erase that stuff from latexstr
94 latexstr = latexstr.erase(pos);
95 // ...and similarly from plainstr
96 size_t ppos = plainstr.find(from_ascii("|"));
97 if (ppos < plainstr.size())
100 LYXERR0("The `|' separator was not found in the plaintext version!");
103 // Separate the entires and subentries, i.e., split on "!"
104 // FIXME This would do the wrong thing with escaped ! characters
105 std::vector<docstring> const levels =
106 getVectorFromString(latexstr, from_ascii("!"), true);
107 std::vector<docstring> const levels_plain =
108 getVectorFromString(plainstr, from_ascii("!"), true);
110 vector<docstring>::const_iterator it = levels.begin();
111 vector<docstring>::const_iterator end = levels.end();
112 vector<docstring>::const_iterator it2 = levels_plain.begin();
114 for (; it != end; ++it) {
115 // write the separator except the first time
121 // correctly sort macros and formatted strings
122 // if we do find a command, prepend a plain text
123 // version of the content to get sorting right,
124 // e.g. \index{LyX@\LyX}, \index{text@\textbf{text}}
125 // Don't do that if the user entered '@' himself, though.
126 if (contains(*it, '\\') && !contains(*it, '@')) {
127 // Plaintext might return nothing (e.g. for ERTs)
128 docstring const spart =
129 (it2 < levels_plain.end() && !(*it2).empty())
131 // Now we need to validate that all characters in
132 // the sorting part are representable in the current
133 // encoding. If not try the LaTeX macro which might
134 // or might not be a good choice, and issue a warning.
136 for (size_t n = 0; n < spart.size(); ++n) {
138 spart2 += runparams.encoding->latexChar(spart[n]);
139 } catch (EncodingException & /* e */) {
140 LYXERR0("Uncodable character in index entry. Sorting might be wrong!");
143 if (spart != spart2 && !runparams.dryrun) {
144 // FIXME: warning should be passed to the error dialog
145 frontend::Alert::warning(_("Index sorting failed"),
146 bformat(_("LyX's automatic index sorting algorithm faced\n"
147 "problems with the entry '%1$s'.\n"
148 "Please specify the sorting of this entry manually, as\n"
149 "explained in the User Guide."), spart));
151 // remove remaining \'s for the sorting part
152 docstring const ppart =
153 subst(spart2, from_ascii("\\"), docstring());
157 docstring const tpart = *it;
159 if (it2 < levels_plain.end())
162 // write the bit that followed "|"
170 int InsetIndex::docbook(odocstream & os, OutputParams const & runparams) const
172 os << "<indexterm><primary>";
173 int const i = InsetText::docbook(os, runparams);
174 os << "</primary></indexterm>";
179 docstring InsetIndex::xhtml(XHTMLStream & xs, OutputParams const &) const
181 // we just print an anchor, taking the paragraph ID from
182 // our own interior paragraph, which doesn't get printed
183 std::string const magic = paragraphs().front().magicLabel();
184 std::string const attr = "id='" + magic + "'";
185 xs << CompTag("a", attr);
190 bool InsetIndex::showInsetDialog(BufferView * bv) const
192 bv->showDialog("index", params2string(params_),
193 const_cast<InsetIndex *>(this));
198 void InsetIndex::doDispatch(Cursor & cur, FuncRequest & cmd)
200 switch (cmd.action) {
202 case LFUN_INSET_MODIFY: {
203 if (cmd.getArg(0) == "changetype") {
204 params_.index = from_utf8(cmd.getArg(1));
207 InsetIndexParams params;
208 InsetIndex::string2params(to_utf8(cmd.argument()), params);
209 params_.index = params.index;
213 case LFUN_INSET_DIALOG_UPDATE:
214 cur.bv().updateDialog("index", params2string(params_));
218 InsetCollapsable::doDispatch(cur, cmd);
224 bool InsetIndex::getStatus(Cursor & cur, FuncRequest const & cmd,
225 FuncStatus & flag) const
227 switch (cmd.action) {
229 case LFUN_INSET_MODIFY:
230 if (cmd.getArg(0) == "changetype") {
231 docstring const newtype = from_utf8(cmd.getArg(1));
232 Buffer const & realbuffer = *buffer().masterBuffer();
233 IndicesList const & indiceslist = realbuffer.params().indiceslist();
234 Index const * index = indiceslist.findShortcut(newtype);
235 flag.setEnabled(index != 0);
237 from_utf8(cmd.getArg(1)) == params_.index);
240 flag.setEnabled(true);
243 case LFUN_INSET_DIALOG_UPDATE: {
244 Buffer const & realbuffer = *buffer().masterBuffer();
245 flag.setEnabled(realbuffer.params().use_indices);
250 return InsetCollapsable::getStatus(cur, cmd, flag);
255 ColorCode InsetIndex::labelColor() const
257 if (params_.index.empty() || params_.index == from_ascii("idx"))
258 return InsetCollapsable::labelColor();
260 ColorCode c = lcolor.getFromLyXName(to_utf8(params_.index));
262 c = InsetCollapsable::labelColor();
267 docstring InsetIndex::toolTip(BufferView const &, int, int) const
269 docstring tip = _("Index Entry");
270 if (buffer().params().use_indices && !params_.index.empty()) {
271 Buffer const & realbuffer = *buffer().masterBuffer();
272 IndicesList const & indiceslist = realbuffer.params().indiceslist();
274 Index const * index = indiceslist.findShortcut(params_.index);
276 tip += _("unknown type!");
278 tip += index->index();
282 OutputParams rp(&buffer().params().encoding());
283 odocstringstream ods;
284 InsetText::plaintext(ods, rp);
286 return wrapParas(tip);
290 void InsetIndex::write(ostream & os) const
292 os << to_utf8(name());
294 InsetCollapsable::write(os);
298 void InsetIndex::read(Lexer & lex)
301 InsetCollapsable::read(lex);
305 string InsetIndex::params2string(InsetIndexParams const & params)
314 void InsetIndex::string2params(string const & in, InsetIndexParams & params)
316 params = InsetIndexParams();
320 istringstream data(in);
323 lex.setContext("InsetIndex::string2params");
329 void InsetIndex::addToToc(DocIterator const & cpit)
331 DocIterator pit = cpit;
332 pit.push_back(CursorSlice(*this));
333 docstring const item = text().asString(0, 1, AS_STR_LABEL | AS_STR_INSETS);
334 buffer().tocBackend().toc("index").push_back(TocItem(pit, 0, item));
335 // Proceed with the rest of the inset.
336 InsetCollapsable::addToToc(cpit);
340 void InsetIndex::validate(LaTeXFeatures & features) const
342 if (buffer().masterBuffer()->params().use_indices
343 && !params_.index.empty()
344 && params_.index != "idx")
345 features.require("splitidx");
349 docstring InsetIndex::contextMenu(BufferView const &, int, int) const
351 return from_ascii("context-index");
355 bool InsetIndex::hasSettings() const
357 return buffer().masterBuffer()->params().use_indices;
363 /////////////////////////////////////////////////////////////////////
367 ///////////////////////////////////////////////////////////////////////
370 void InsetIndexParams::write(ostream & os) const
374 os << to_utf8(index);
381 void InsetIndexParams::read(Lexer & lex)
384 index = lex.getDocString();
386 index = from_ascii("idx");
390 /////////////////////////////////////////////////////////////////////
394 ///////////////////////////////////////////////////////////////////////
396 InsetPrintIndex::InsetPrintIndex(Buffer * buf, InsetCommandParams const & p)
397 : InsetCommand(buf, p, "index_print")
401 ParamInfo const & InsetPrintIndex::findInfo(string const & /* cmdName */)
403 static ParamInfo param_info_;
404 if (param_info_.empty()) {
405 param_info_.add("type", ParamInfo::LATEX_OPTIONAL);
406 param_info_.add("name", ParamInfo::LATEX_REQUIRED);
412 docstring InsetPrintIndex::screenLabel() const
414 bool const printall = suffixIs(getCmdName(), '*');
415 bool const multind = buffer().masterBuffer()->params().use_indices;
417 && getParam("type") == from_ascii("idx"))
418 || (getParam("type").empty() && !printall))
420 Buffer const & realbuffer = *buffer().masterBuffer();
421 IndicesList const & indiceslist = realbuffer.params().indiceslist();
422 Index const * index = indiceslist.findShortcut(getParam("type"));
423 if (!index && !printall)
424 return _("Unknown index type!");
425 docstring res = printall ? _("All indices") : index->index();
427 res += " (" + _("non-active") + ")";
428 else if (contains(getCmdName(), "printsubindex"))
429 res += " (" + _("subindex") + ")";
434 bool InsetPrintIndex::isCompatibleCommand(string const & s)
436 return s == "printindex" || s == "printsubindex"
437 || s == "printindex*" || s == "printsubindex*";
441 void InsetPrintIndex::doDispatch(Cursor & cur, FuncRequest & cmd)
443 switch (cmd.action) {
445 case LFUN_INSET_MODIFY: {
446 if (cmd.argument() == from_ascii("toggle-subindex")) {
447 string cmd = getCmdName();
448 if (contains(cmd, "printindex"))
449 cmd = subst(cmd, "printindex", "printsubindex");
451 cmd = subst(cmd, "printsubindex", "printindex");
454 } else if (cmd.argument() == from_ascii("check-printindex*")) {
455 string cmd = getCmdName();
456 if (suffixIs(cmd, '*'))
459 setParam("type", docstring());
463 InsetCommandParams p(INDEX_PRINT_CODE);
465 InsetCommand::string2params("index_print",
466 to_utf8(cmd.argument()), p);
467 if (p.getCmdName().empty()) {
476 InsetCommand::doDispatch(cur, cmd);
482 bool InsetPrintIndex::getStatus(Cursor & cur, FuncRequest const & cmd,
483 FuncStatus & status) const
485 switch (cmd.action) {
487 case LFUN_INSET_MODIFY: {
488 if (cmd.argument() == from_ascii("toggle-subindex")) {
489 status.setEnabled(buffer().masterBuffer()->params().use_indices);
490 status.setOnOff(contains(getCmdName(), "printsubindex"));
492 } else if (cmd.argument() == from_ascii("check-printindex*")) {
493 status.setEnabled(buffer().masterBuffer()->params().use_indices);
494 status.setOnOff(suffixIs(getCmdName(), '*'));
496 } if (cmd.getArg(0) == "index_print"
497 && cmd.getArg(1) == "CommandInset") {
498 InsetCommandParams p(INDEX_PRINT_CODE);
499 InsetCommand::string2params("index_print",
500 to_utf8(cmd.argument()), p);
501 if (suffixIs(p.getCmdName(), '*')) {
502 status.setEnabled(true);
503 status.setOnOff(false);
506 Buffer const & realbuffer = *buffer().masterBuffer();
507 IndicesList const & indiceslist =
508 realbuffer.params().indiceslist();
509 Index const * index = indiceslist.findShortcut(p["type"]);
510 status.setEnabled(index != 0);
511 status.setOnOff(p["type"] == getParam("type"));
514 return InsetCommand::getStatus(cur, cmd, status);
517 case LFUN_INSET_DIALOG_UPDATE: {
518 status.setEnabled(buffer().masterBuffer()->params().use_indices);
523 return InsetCommand::getStatus(cur, cmd, status);
528 int InsetPrintIndex::latex(odocstream & os, OutputParams const &) const
530 if (!buffer().masterBuffer()->params().use_indices) {
531 if (getParam("type") == from_ascii("idx"))
532 os << "\\printindex{}";
540 void InsetPrintIndex::validate(LaTeXFeatures & features) const
542 features.require("makeidx");
543 if (buffer().masterBuffer()->params().use_indices)
544 features.require("splitidx");
548 docstring InsetPrintIndex::contextMenu(BufferView const &, int, int) const
550 return buffer().masterBuffer()->params().use_indices ?
551 from_ascii("context-indexprint") : docstring();
555 bool InsetPrintIndex::hasSettings() const
557 return buffer().masterBuffer()->params().use_indices;
565 IndexEntry(docstring const & s, DocIterator const & d)
573 bool operator<(IndexEntry const & lhs, IndexEntry const & rhs)
575 return lhs.idx < rhs.idx;
581 docstring InsetPrintIndex::xhtml(XHTMLStream &, OutputParams const & op) const
583 Layout const & lay = buffer().params().documentClass().htmlTOCLayout();
584 string const & tocclass = lay.defaultCSSClass();
585 string const tocattr = "class='tochead " + tocclass + "'";
587 // we'll use our own stream, because we are going to defer everything.
588 // that's how we deal with the fact that we're probably inside a standard
589 // paragraph, and we don't want to be.
590 odocstringstream ods;
593 Toc const & toc = buffer().tocBackend().toc("index");
597 xs << StartTag("div", "class='index'");
598 xs << StartTag("div", tocattr)
601 Toc::const_iterator it = toc.begin();
602 Toc::const_iterator const en = toc.end();
604 vector<IndexEntry> entries;
605 for (; it != en; ++it)
606 entries.push_back(IndexEntry(it->str(), it->dit()));
607 stable_sort(entries.begin(), entries.end());
609 vector<IndexEntry>::const_iterator eit = entries.begin();
610 vector<IndexEntry>::const_iterator const een = entries.end();
611 vector<IndexEntry>::const_iterator last = een;
612 int entry_number = 0;
613 for (; eit != een; ++eit) {
614 Paragraph const & par = eit->dit.innerParagraph();
616 // first time through the loop
617 xs << StartTag("div", "class='index_entry'");
618 par.simpleLyXHTMLOnePar(buffer(), xs, op, dummy, true);
620 else if (last->idx != eit->idx) {
621 // this is a new entry
624 xs << StartTag("div", "class='index_entry'");
625 par.simpleLyXHTMLOnePar(buffer(), xs, op, dummy, true);
630 string const parattr = "href='#" + par.magicLabel() + "'";
631 xs << " " << StartTag("a", parattr);
632 xs << ++entry_number;
636 xs << EndTag("div"); // last entry