]> git.lyx.org Git - lyx.git/blob - src/insets/InsetIndex.cpp
Keep dialog connected to cross-ref inset after Apply.
[lyx.git] / src / insets / InsetIndex.cpp
1 /**
2  * \file InsetIndex.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author Jürgen Spitzmüller
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11 #include <config.h>
12
13 #include "InsetIndex.h"
14
15 #include "Buffer.h"
16 #include "BufferParams.h"
17 #include "BufferView.h"
18 #include "ColorSet.h"
19 #include "Cursor.h"
20 #include "DispatchResult.h"
21 #include "Encoding.h"
22 #include "FuncRequest.h"
23 #include "FuncStatus.h"
24 #include "IndicesList.h"
25 #include "Language.h"
26 #include "LaTeXFeatures.h"
27 #include "Lexer.h"
28 #include "output_latex.h"
29 #include "output_xhtml.h"
30 #include "xml.h"
31 #include "texstream.h"
32 #include "TextClass.h"
33 #include "TocBackend.h"
34
35 #include "support/debug.h"
36 #include "support/docstream.h"
37 #include "support/gettext.h"
38 #include "support/lstrings.h"
39
40 #include "frontends/alert.h"
41
42 #include <algorithm>
43 #include <set>
44 #include <ostream>
45
46 #include <QThreadStorage>
47
48 using namespace std;
49 using namespace lyx::support;
50
51 namespace lyx {
52
53 /////////////////////////////////////////////////////////////////////
54 //
55 // InsetIndex
56 //
57 ///////////////////////////////////////////////////////////////////////
58
59
60 InsetIndex::InsetIndex(Buffer * buf, InsetIndexParams const & params)
61         : InsetCollapsible(buf), params_(params)
62 {}
63
64
65 void InsetIndex::latex(otexstream & ios, OutputParams const & runparams_in) const
66 {
67         OutputParams runparams(runparams_in);
68         runparams.inIndexEntry = true;
69
70         otexstringstream os;
71
72         if (buffer().masterBuffer()->params().use_indices && !params_.index.empty()
73                 && params_.index != "idx") {
74                 os << "\\sindex[";
75                 os << escape(params_.index);
76                 os << "]{";
77         } else {
78                 os << "\\index";
79                 os << '{';
80         }
81
82         odocstringstream ourlatex;
83         otexstream ots(ourlatex);
84         InsetText::latex(ots, runparams);
85         if (runparams.for_search) {
86                 // No need for special handling, if we are only searching for some patterns
87                 os << ourlatex.str() << "}";
88                 return;
89         }
90         // get contents of InsetText as LaTeX and plaintext
91         odocstringstream ourplain;
92         InsetText::plaintext(ourplain, runparams);
93         // FIXME: do Tex/Row correspondence (I don't currently understand what is
94         // being generated from latexstr below)
95         docstring latexstr = ourlatex.str();
96         docstring plainstr = ourplain.str();
97
98         // this will get what follows | if anything does
99         docstring cmd;
100
101         // check for the | separator
102         // FIXME This would go wrong on an escaped "|", but
103         // how far do we want to go here?
104         size_t pos = latexstr.find(from_ascii("|"));
105         if (pos != docstring::npos) {
106                 // put the bit after "|" into cmd...
107                 cmd = latexstr.substr(pos + 1);
108                 // ...and erase that stuff from latexstr
109                 latexstr = latexstr.erase(pos);
110                 // ...and similarly from plainstr
111                 size_t ppos = plainstr.find(from_ascii("|"));
112                 if (ppos < plainstr.size())
113                         plainstr.erase(ppos);
114                 else
115                         LYXERR0("The `|' separator was not found in the plaintext version!");
116         }
117
118         // Separate the entries and subentries, i.e., split on "!"
119         // FIXME This would do the wrong thing with escaped ! characters
120         std::vector<docstring> const levels =
121                         getVectorFromString(latexstr, from_ascii("!"), true);
122         std::vector<docstring> const levels_plain =
123                         getVectorFromString(plainstr, from_ascii("!"), true);
124
125         vector<docstring>::const_iterator it = levels.begin();
126         vector<docstring>::const_iterator end = levels.end();
127         vector<docstring>::const_iterator it2 = levels_plain.begin();
128         bool first = true;
129         for (; it != end; ++it) {
130                 // write the separator except the first time
131                 if (!first)
132                         os << '!';
133                 else
134                         first = false;
135
136                 // correctly sort macros and formatted strings
137                 // if we do find a command, prepend a plain text
138                 // version of the content to get sorting right,
139                 // e.g. \index{LyX@\LyX}, \index{text@\textbf{text}}
140                 // Don't do that if the user entered '@' himself, though.
141                 if (contains(*it, '\\') && !contains(*it, '@')) {
142                         // Plaintext might return nothing (e.g. for ERTs)
143                         docstring const spart =
144                                         (it2 < levels_plain.end() && !(*it2).empty())
145                                         ? *it2 : *it;
146                         // Now we need to validate that all characters in
147                         // the sorting part are representable in the current
148                         // encoding. If not try the LaTeX macro which might
149                         // or might not be a good choice, and issue a warning.
150                         pair<docstring, docstring> spart_latexed =
151                                         runparams.encoding->latexString(spart, runparams.dryrun);
152                         if (!spart_latexed.second.empty())
153                                 LYXERR0("Uncodable character in index entry. Sorting might be wrong!");
154                         if (spart != spart_latexed.first && !runparams.dryrun) {
155                                 // FIXME: warning should be passed to the error dialog
156                                 frontend::Alert::warning(_("Index sorting failed"),
157                                                                                  bformat(_("LyX's automatic index sorting algorithm faced\n"
158                                                                                                                    "problems with the entry '%1$s'.\n"
159                                                                                                                    "Please specify the sorting of this entry manually, as\n"
160                                                                                                                    "explained in the User Guide."), spart));
161                         }
162                         // remove remaining \'s for the sorting part
163                         docstring const ppart =
164                                         subst(spart_latexed.first, from_ascii("\\"), docstring());
165                         os << ppart;
166                         os << '@';
167                 }
168                 docstring const tpart = *it;
169                 os << tpart;
170                 if (it2 < levels_plain.end())
171                         ++it2;
172         }
173         // write the bit that followed "|"
174         if (!cmd.empty()) {
175                 os << "|" << cmd;
176         }
177         os << '}';
178
179         // In macros with moving arguments, such as \section,
180         // we store the index and output it after the macro (#2154)
181         if (runparams_in.postpone_fragile_stuff)
182                 runparams_in.post_macro += os.str();
183         else
184                 ios << os.release();
185 }
186
187
188 void InsetIndex::docbook(XMLStream & xs, OutputParams const & runparams) const
189 {
190         // Get the content of the inset as LaTeX, as some things may be encoded as ERT (like {}).
191         odocstringstream odss;
192         otexstream ots(odss);
193         InsetText::latex(ots, runparams);
194         docstring latexString = trim(odss.str());
195
196         // Check whether there are unsupported things.
197         if (latexString.find(from_utf8("@")) != latexString.npos) {
198                 docstring error = from_utf8("Unsupported feature: an index entry contains an @. "
199                                                                         "Complete entry: \"") + latexString + from_utf8("\"");
200                 LYXERR0(error);
201                 xs << XMLStream::ESCAPE_NONE << (from_utf8("<!-- Output Error: ") + error + from_utf8(" -->\n"));
202                 // TODO: implement @ using the sortas attribute (on primary, secondary, tertiary).
203         }
204
205         // Handle several indices.
206         docstring indexType = from_utf8("");
207         if (buffer().masterBuffer()->params().use_indices) {
208                 indexType += " type=\"" + params_.index + "\"";
209         }
210
211         // Split the string into its main constituents: terms, and command (see, see also, range).
212         size_t positionVerticalBar = latexString.find(from_ascii("|")); // What comes before | is (sub)(sub)entries.
213         docstring indexTerms = latexString.substr(0, positionVerticalBar);
214         docstring command = latexString.substr(positionVerticalBar + 1);
215
216         // Handle primary, secondary, and tertiary terms (entries, subentries, and subsubentries, for LaTeX).
217         vector<docstring> terms = getVectorFromString(indexTerms, from_ascii("!"), false);
218
219         // Handle ranges. Happily, (| and |) can only be at the end of the string! However, | may be trapped by the
220         bool hasStartRange = latexString.find(from_ascii("|(")) != latexString.npos;
221         bool hasEndRange = latexString.find(from_ascii("|)")) != latexString.npos;
222         if (hasStartRange || hasEndRange) {
223                 // Remove the ranges from the command if they do not appear at the beginning.
224                 size_t index = 0;
225                 while ((index = command.find(from_utf8("|("), index)) != std::string::npos)
226                         command.erase(index, 1);
227                 index = 0;
228                 while ((index = command.find(from_utf8("|)"), index)) != std::string::npos)
229                         command.erase(index, 1);
230
231                 // Remove the ranges when they are the only vertical bar in the complete string.
232                 if (command[0] == '(' || command[0] == ')')
233                         command.erase(0, 1);
234         }
235
236         // Handle see and seealso. As "see" is a prefix of "seealso", the order of the comparisons is important.
237         // Both commands are mutually exclusive!
238         docstring see = from_utf8("");
239         vector<docstring> seeAlsoes;
240         if (command.substr(0, 3) == "see") {
241                 // Unescape brackets.
242                 size_t index = 0;
243                 while ((index = command.find(from_utf8("\\{"), index)) != std::string::npos)
244                         command.erase(index, 1);
245                 index = 0;
246                 while ((index = command.find(from_utf8("\\}"), index)) != std::string::npos)
247                         command.erase(index, 1);
248
249                 // Retrieve the part between brackets, and remove the complete seealso.
250                 size_t positionOpeningBracket = command.find(from_ascii("{"));
251                 size_t positionClosingBracket = command.find(from_ascii("}"));
252                 docstring list = command.substr(positionOpeningBracket + 1, positionClosingBracket - positionOpeningBracket - 1);
253
254                 // Parse the list of referenced entries (or a single one for see).
255                 if (command.substr(0, 7) == "seealso") {
256                         seeAlsoes = getVectorFromString(list, from_ascii(","), false);
257                 } else {
258                         see = list;
259
260                         if (see.find(from_ascii(",")) != see.npos) {
261                                 docstring error = from_utf8("Several index terms found as \"see\"! Only one is acceptable. "
262                                                                                         "Complete entry: \"") + latexString + from_utf8("\"");
263                                 LYXERR0(error);
264                                 xs << XMLStream::ESCAPE_NONE << (from_utf8("<!-- Output Error: ") + error + from_utf8(" -->\n"));
265                         }
266                 }
267
268                 // Remove the complete see/seealso from the commands, in case there is something else to parse.
269                 command = command.substr(positionClosingBracket + 1);
270         }
271
272         // Some parts of the strings are not parsed, as they do not have anything matching in DocBook: things like
273         // formatting the entry or the page number, other strings for sorting. https://wiki.lyx.org/Tips/Indexing
274         // If there are such things in the index entry, then this code may miserably fail. For example, for "Peter|(textbf",
275         // no range will be detected.
276         // TODO: Could handle formatting as significance="preferred"?
277
278     // Write all of this down.
279         if (terms.empty() && !hasEndRange) {
280                 docstring error = from_utf8("No index term found! Complete entry: \"") + latexString + from_utf8("\"");
281                 LYXERR0(error);
282                 xs << XMLStream::ESCAPE_NONE << (from_utf8("<!-- Output Error: ") + error + from_utf8(" -->\n"));
283         } else {
284                 // Generate the attributes for ranges. It is based on the terms that are indexed, but the ID must be unique
285                 // to this indexing area (xml::cleanID does not guarantee this: for each call with the same arguments,
286                 // the same legal ID is produced; here, as the input would be the same, the output must be, by design).
287                 // Hence the thread-local storage, as the numbers must strictly be unique, and thus cannot be shared across
288                 // a paragraph (making the solution used for HTML worthless). This solution is very similar to the one used in
289                 // xml::cleanID.
290                 // indexType can only be used for singular and startofrange types!
291                 docstring attrs;
292                 if (!hasStartRange && !hasEndRange) {
293                         attrs = indexType;
294                 } else {
295                         // Append an ID if uniqueness is not guaranteed across the document.
296                         static QThreadStorage<set<docstring>> tKnownTermLists;
297                         static QThreadStorage<int> tID;
298
299                         set<docstring> &knownTermLists = tKnownTermLists.localData();
300                         int &ID = tID.localData();
301
302                         if (!tID.hasLocalData()) {
303                                 tID.localData() = 0;
304                         }
305
306                         // Modify the index terms to add the unique ID if needed.
307                         docstring newIndexTerms = indexTerms;
308                         if (knownTermLists.find(indexTerms) != knownTermLists.end()) {
309                                 newIndexTerms += from_ascii(string("-") + to_string(ID));
310
311                                 // Only increment for the end of range, so that the same number is used for the start of range.
312                                 if (hasEndRange) {
313                                         ID++;
314                                 }
315                         }
316
317                         // Term list not yet known: add it to the set AFTER the end of range. After
318                         if (knownTermLists.find(indexTerms) == knownTermLists.end() && hasEndRange) {
319                                 knownTermLists.insert(indexTerms);
320                         }
321
322                         // Generate the attributes.
323                         docstring id = xml::cleanID(newIndexTerms);
324                         if (hasStartRange) {
325                                 attrs = indexType + " class=\"startofrange\" xml:id=\"" + id + "\"";
326                         } else {
327                                 attrs = " class=\"endofrange\" startref=\"" + id + "\"";
328                         }
329                 }
330
331                 // Handle the index terms (including the specific index for this entry).
332                 if (hasEndRange) {
333                         xs << xml::CompTag("indexterm", attrs);
334                 } else {
335                         xs << xml::StartTag("indexterm", attrs);
336                         if (!terms.empty()) { // hasEndRange has no content.
337                                 xs << xml::StartTag("primary");
338                                 xs << terms[0];
339                                 xs << xml::EndTag("primary");
340                         }
341                         if (terms.size() > 1) {
342                                 xs << xml::StartTag("secondary");
343                                 xs << terms[1];
344                                 xs << xml::EndTag("secondary");
345                         }
346                         if (terms.size() > 2) {
347                                 xs << xml::StartTag("tertiary");
348                                 xs << terms[2];
349                                 xs << xml::EndTag("tertiary");
350                         }
351
352                         // Handle see and see also.
353                         if (!see.empty()) {
354                                 xs << xml::StartTag("see");
355                                 xs << see;
356                                 xs << xml::EndTag("see");
357                         }
358
359                         if (!seeAlsoes.empty()) {
360                                 for (auto &entry : seeAlsoes) {
361                                         xs << xml::StartTag("seealso");
362                                         xs << entry;
363                                         xs << xml::EndTag("seealso");
364                                 }
365                         }
366
367                         // Close the entry.
368                         xs << xml::EndTag("indexterm");
369                 }
370         }
371 }
372
373
374 docstring InsetIndex::xhtml(XMLStream & xs, OutputParams const &) const
375 {
376         // we just print an anchor, taking the paragraph ID from
377         // our own interior paragraph, which doesn't get printed
378         std::string const magic = paragraphs().front().magicLabel();
379         std::string const attr = "id='" + magic + "'";
380         xs << xml::CompTag("a", attr);
381         return docstring();
382 }
383
384
385 bool InsetIndex::showInsetDialog(BufferView * bv) const
386 {
387         bv->showDialog("index", params2string(params_),
388                         const_cast<InsetIndex *>(this));
389         return true;
390 }
391
392
393 void InsetIndex::doDispatch(Cursor & cur, FuncRequest & cmd)
394 {
395         switch (cmd.action()) {
396
397         case LFUN_INSET_MODIFY: {
398                 if (cmd.getArg(0) == "changetype") {
399                         cur.recordUndoInset(this);
400                         params_.index = from_utf8(cmd.getArg(1));
401                         break;
402                 }
403                 InsetIndexParams params;
404                 InsetIndex::string2params(to_utf8(cmd.argument()), params);
405                 cur.recordUndoInset(this);
406                 params_.index = params.index;
407                 // what we really want here is a TOC update, but that means
408                 // a full buffer update
409                 cur.forceBufferUpdate();
410                 break;
411         }
412
413         case LFUN_INSET_DIALOG_UPDATE:
414                 cur.bv().updateDialog("index", params2string(params_));
415                 break;
416
417         default:
418                 InsetCollapsible::doDispatch(cur, cmd);
419                 break;
420         }
421 }
422
423
424 bool InsetIndex::getStatus(Cursor & cur, FuncRequest const & cmd,
425                 FuncStatus & flag) const
426 {
427         switch (cmd.action()) {
428
429         case LFUN_INSET_MODIFY:
430                 if (cmd.getArg(0) == "changetype") {
431                         docstring const newtype = from_utf8(cmd.getArg(1));
432                         Buffer const & realbuffer = *buffer().masterBuffer();
433                         IndicesList const & indiceslist = realbuffer.params().indiceslist();
434                         Index const * index = indiceslist.findShortcut(newtype);
435                         flag.setEnabled(index != 0);
436                         flag.setOnOff(
437                                 from_utf8(cmd.getArg(1)) == params_.index);
438                         return true;
439                 }
440                 return InsetCollapsible::getStatus(cur, cmd, flag);
441
442         case LFUN_INSET_DIALOG_UPDATE: {
443                 Buffer const & realbuffer = *buffer().masterBuffer();
444                 flag.setEnabled(realbuffer.params().use_indices);
445                 return true;
446         }
447
448         default:
449                 return InsetCollapsible::getStatus(cur, cmd, flag);
450         }
451 }
452
453
454 ColorCode InsetIndex::labelColor() const
455 {
456         if (params_.index.empty() || params_.index == from_ascii("idx"))
457                 return InsetCollapsible::labelColor();
458         // FIXME UNICODE
459         ColorCode c = lcolor.getFromLyXName(to_utf8(params_.index));
460         if (c == Color_none)
461                 c = InsetCollapsible::labelColor();
462         return c;
463 }
464
465
466 docstring InsetIndex::toolTip(BufferView const &, int, int) const
467 {
468         docstring tip = _("Index Entry");
469         if (buffer().params().use_indices && !params_.index.empty()) {
470                 Buffer const & realbuffer = *buffer().masterBuffer();
471                 IndicesList const & indiceslist = realbuffer.params().indiceslist();
472                 tip += " (";
473                 Index const * index = indiceslist.findShortcut(params_.index);
474                 if (!index)
475                         tip += _("unknown type!");
476                 else
477                         tip += index->index();
478                 tip += ")";
479         }
480         tip += ": ";
481         return toolTipText(tip);
482 }
483
484
485 docstring const InsetIndex::buttonLabel(BufferView const & bv) const
486 {
487         InsetLayout const & il = getLayout();
488         docstring label = translateIfPossible(il.labelstring());
489
490         if (buffer().params().use_indices && !params_.index.empty()) {
491                 Buffer const & realbuffer = *buffer().masterBuffer();
492                 IndicesList const & indiceslist = realbuffer.params().indiceslist();
493                 label += " (";
494                 Index const * index = indiceslist.findShortcut(params_.index);
495                 if (!index)
496                         label += _("unknown type!");
497                 else
498                         label += index->index();
499                 label += ")";
500         }
501
502         if (!il.contentaslabel() || geometry(bv) != ButtonOnly)
503                 return label;
504         return getNewLabel(label);
505 }
506
507
508 void InsetIndex::write(ostream & os) const
509 {
510         os << to_utf8(layoutName());
511         params_.write(os);
512         InsetCollapsible::write(os);
513 }
514
515
516 void InsetIndex::read(Lexer & lex)
517 {
518         params_.read(lex);
519         InsetCollapsible::read(lex);
520 }
521
522
523 string InsetIndex::params2string(InsetIndexParams const & params)
524 {
525         ostringstream data;
526         data << "index";
527         params.write(data);
528         return data.str();
529 }
530
531
532 void InsetIndex::string2params(string const & in, InsetIndexParams & params)
533 {
534         params = InsetIndexParams();
535         if (in.empty())
536                 return;
537
538         istringstream data(in);
539         Lexer lex;
540         lex.setStream(data);
541         lex.setContext("InsetIndex::string2params");
542         lex >> "index";
543         params.read(lex);
544 }
545
546
547 void InsetIndex::addToToc(DocIterator const & cpit, bool output_active,
548                                                   UpdateType utype, TocBackend & backend) const
549 {
550         DocIterator pit = cpit;
551         pit.push_back(CursorSlice(const_cast<InsetIndex &>(*this)));
552         docstring str;
553         string type = "index";
554         if (buffer().masterBuffer()->params().use_indices)
555                 type += ":" + to_utf8(params_.index);
556         // this is unlikely to be terribly long
557         text().forOutliner(str, INT_MAX);
558         TocBuilder & b = backend.builder(type);
559         b.pushItem(pit, str, output_active);
560         // Proceed with the rest of the inset.
561         InsetCollapsible::addToToc(cpit, output_active, utype, backend);
562         b.pop();
563 }
564
565
566 void InsetIndex::validate(LaTeXFeatures & features) const
567 {
568         if (buffer().masterBuffer()->params().use_indices
569             && !params_.index.empty()
570             && params_.index != "idx")
571                 features.require("splitidx");
572         InsetCollapsible::validate(features);
573 }
574
575
576 string InsetIndex::contextMenuName() const
577 {
578         return "context-index";
579 }
580
581
582 bool InsetIndex::hasSettings() const
583 {
584         return buffer().masterBuffer()->params().use_indices;
585 }
586
587
588
589
590 /////////////////////////////////////////////////////////////////////
591 //
592 // InsetIndexParams
593 //
594 ///////////////////////////////////////////////////////////////////////
595
596
597 void InsetIndexParams::write(ostream & os) const
598 {
599         os << ' ';
600         if (!index.empty())
601                 os << to_utf8(index);
602         else
603                 os << "idx";
604         os << '\n';
605 }
606
607
608 void InsetIndexParams::read(Lexer & lex)
609 {
610         if (lex.eatLine())
611                 index = lex.getDocString();
612         else
613                 index = from_ascii("idx");
614 }
615
616
617 /////////////////////////////////////////////////////////////////////
618 //
619 // InsetPrintIndex
620 //
621 ///////////////////////////////////////////////////////////////////////
622
623 InsetPrintIndex::InsetPrintIndex(Buffer * buf, InsetCommandParams const & p)
624         : InsetCommand(buf, p)
625 {}
626
627
628 ParamInfo const & InsetPrintIndex::findInfo(string const & /* cmdName */)
629 {
630         static ParamInfo param_info_;
631         if (param_info_.empty()) {
632                 param_info_.add("type", ParamInfo::LATEX_OPTIONAL,
633                                 ParamInfo::HANDLING_ESCAPE);
634                 param_info_.add("name", ParamInfo::LATEX_OPTIONAL,
635                                 ParamInfo::HANDLING_LATEXIFY);
636                 param_info_.add("literal", ParamInfo::LYX_INTERNAL);
637         }
638         return param_info_;
639 }
640
641
642 docstring InsetPrintIndex::screenLabel() const
643 {
644         bool const printall = suffixIs(getCmdName(), '*');
645         bool const multind = buffer().masterBuffer()->params().use_indices;
646         if ((!multind
647              && getParam("type") == from_ascii("idx"))
648             || (getParam("type").empty() && !printall))
649                 return _("Index");
650         Buffer const & realbuffer = *buffer().masterBuffer();
651         IndicesList const & indiceslist = realbuffer.params().indiceslist();
652         Index const * index = indiceslist.findShortcut(getParam("type"));
653         if (!index && !printall)
654                 return _("Unknown index type!");
655         docstring res = printall ? _("All indexes") : index->index();
656         if (!multind)
657                 res += " (" + _("non-active") + ")";
658         else if (contains(getCmdName(), "printsubindex"))
659                 res += " (" + _("subindex") + ")";
660         return res;
661 }
662
663
664 bool InsetPrintIndex::isCompatibleCommand(string const & s)
665 {
666         return s == "printindex" || s == "printsubindex"
667                 || s == "printindex*" || s == "printsubindex*";
668 }
669
670
671 void InsetPrintIndex::doDispatch(Cursor & cur, FuncRequest & cmd)
672 {
673         switch (cmd.action()) {
674
675         case LFUN_INSET_MODIFY: {
676                 if (cmd.argument() == from_ascii("toggle-subindex")) {
677                         string scmd = getCmdName();
678                         if (contains(scmd, "printindex"))
679                                 scmd = subst(scmd, "printindex", "printsubindex");
680                         else
681                                 scmd = subst(scmd, "printsubindex", "printindex");
682                         cur.recordUndo();
683                         setCmdName(scmd);
684                         break;
685                 } else if (cmd.argument() == from_ascii("check-printindex*")) {
686                         string scmd = getCmdName();
687                         if (suffixIs(scmd, '*'))
688                                 break;
689                         scmd += '*';
690                         cur.recordUndo();
691                         setParam("type", docstring());
692                         setCmdName(scmd);
693                         break;
694                 }
695                 InsetCommandParams p(INDEX_PRINT_CODE);
696                 // FIXME UNICODE
697                 InsetCommand::string2params(to_utf8(cmd.argument()), p);
698                 if (p.getCmdName().empty()) {
699                         cur.noScreenUpdate();
700                         break;
701                 }
702                 cur.recordUndo();
703                 setParams(p);
704                 break;
705         }
706
707         default:
708                 InsetCommand::doDispatch(cur, cmd);
709                 break;
710         }
711 }
712
713
714 bool InsetPrintIndex::getStatus(Cursor & cur, FuncRequest const & cmd,
715         FuncStatus & status) const
716 {
717         switch (cmd.action()) {
718
719         case LFUN_INSET_MODIFY: {
720                 if (cmd.argument() == from_ascii("toggle-subindex")) {
721                         status.setEnabled(buffer().masterBuffer()->params().use_indices);
722                         status.setOnOff(contains(getCmdName(), "printsubindex"));
723                         return true;
724                 } else if (cmd.argument() == from_ascii("check-printindex*")) {
725                         status.setEnabled(buffer().masterBuffer()->params().use_indices);
726                         status.setOnOff(suffixIs(getCmdName(), '*'));
727                         return true;
728                 } if (cmd.getArg(0) == "index_print"
729                     && cmd.getArg(1) == "CommandInset") {
730                         InsetCommandParams p(INDEX_PRINT_CODE);
731                         InsetCommand::string2params(to_utf8(cmd.argument()), p);
732                         if (suffixIs(p.getCmdName(), '*')) {
733                                 status.setEnabled(true);
734                                 status.setOnOff(false);
735                                 return true;
736                         }
737                         Buffer const & realbuffer = *buffer().masterBuffer();
738                         IndicesList const & indiceslist =
739                                 realbuffer.params().indiceslist();
740                         Index const * index = indiceslist.findShortcut(p["type"]);
741                         status.setEnabled(index != 0);
742                         status.setOnOff(p["type"] == getParam("type"));
743                         return true;
744                 } else
745                         return InsetCommand::getStatus(cur, cmd, status);
746         }
747
748         case LFUN_INSET_DIALOG_UPDATE: {
749                 status.setEnabled(buffer().masterBuffer()->params().use_indices);
750                 return true;
751         }
752
753         default:
754                 return InsetCommand::getStatus(cur, cmd, status);
755         }
756 }
757
758
759 void InsetPrintIndex::updateBuffer(ParIterator const &, UpdateType, bool const /*deleted*/)
760 {
761         Index const * index =
762                 buffer().masterParams().indiceslist().findShortcut(getParam("type"));
763         if (index)
764                 setParam("name", index->index());
765 }
766
767
768 void InsetPrintIndex::latex(otexstream & os, OutputParams const & runparams_in) const
769 {
770         if (!buffer().masterBuffer()->params().use_indices) {
771                 if (getParam("type") == from_ascii("idx"))
772                         os << "\\printindex" << termcmd;
773                 return;
774         }
775         OutputParams runparams = runparams_in;
776         os << getCommand(runparams);
777 }
778
779
780 void InsetPrintIndex::validate(LaTeXFeatures & features) const
781 {
782         features.require("makeidx");
783         if (buffer().masterBuffer()->params().use_indices)
784                 features.require("splitidx");
785         InsetCommand::validate(features);
786 }
787
788
789 string InsetPrintIndex::contextMenuName() const
790 {
791         return buffer().masterBuffer()->params().use_indices ?
792                 "context-indexprint" : string();
793 }
794
795
796 bool InsetPrintIndex::hasSettings() const
797 {
798         return buffer().masterBuffer()->params().use_indices;
799 }
800
801
802 namespace {
803
804 void parseItem(docstring & s, bool for_output)
805 {
806         // this does not yet check for escaped things
807         size_type loc = s.find(from_ascii("@"));
808         if (loc != string::npos) {
809                 if (for_output)
810                         s.erase(0, loc + 1);
811                 else
812                         s.erase(loc);
813         }
814         loc = s.find(from_ascii("|"));
815         if (loc != string::npos)
816                 s.erase(loc);
817 }
818
819
820 void extractSubentries(docstring const & entry, docstring & main,
821                 docstring & sub1, docstring & sub2)
822 {
823         if (entry.empty())
824                 return;
825         size_type const loc = entry.find(from_ascii(" ! "));
826         if (loc == string::npos)
827                 main = entry;
828         else {
829                 main = trim(entry.substr(0, loc));
830                 size_t const locend = loc + 3;
831                 size_type const loc2 = entry.find(from_ascii(" ! "), locend);
832                 if (loc2 == string::npos) {
833                         sub1 = trim(entry.substr(locend));
834                 } else {
835                         sub1 = trim(entry.substr(locend, loc2 - locend));
836                         sub2 = trim(entry.substr(loc2 + 3));
837                 }
838         }
839 }
840
841
842 struct IndexEntry
843 {
844         IndexEntry()
845         {}
846
847         IndexEntry(docstring const & s, DocIterator const & d)
848                         : dit(d)
849         {
850                 extractSubentries(s, main, sub, subsub);
851                 parseItem(main, false);
852                 parseItem(sub, false);
853                 parseItem(subsub, false);
854         }
855
856         bool equal(IndexEntry const & rhs) const
857         {
858                 return main == rhs.main && sub == rhs.sub && subsub == rhs.subsub;
859         }
860
861         bool same_sub(IndexEntry const & rhs) const
862         {
863                 return main == rhs.main && sub == rhs.sub;
864         }
865
866         bool same_main(IndexEntry const & rhs) const
867         {
868                 return main == rhs.main;
869         }
870
871         docstring main;
872         docstring sub;
873         docstring subsub;
874         DocIterator dit;
875 };
876
877 bool operator<(IndexEntry const & lhs, IndexEntry const & rhs)
878 {
879         int comp = compare_no_case(lhs.main, rhs.main);
880         if (comp == 0)
881                 comp = compare_no_case(lhs.sub, rhs.sub);
882         if (comp == 0)
883                 comp = compare_no_case(lhs.subsub, rhs.subsub);
884         return (comp < 0);
885 }
886
887 } // namespace
888
889
890 docstring InsetPrintIndex::xhtml(XMLStream &, OutputParams const & op) const
891 {
892         BufferParams const & bp = buffer().masterBuffer()->params();
893
894         // we do not presently support multiple indices, so we refuse to print
895         // anything but the main index, so as not to generate multiple indices.
896         // NOTE Multiple index support would require some work. The reason
897         // is that the TOC does not know about multiple indices. Either it would
898         // need to be told about them (not a bad idea), or else the index entries
899         // would need to be collected differently, say, during validation.
900         if (bp.use_indices && getParam("type") != from_ascii("idx"))
901                 return docstring();
902
903         shared_ptr<Toc const> toc = buffer().tocBackend().toc("index");
904         if (toc->empty())
905                 return docstring();
906
907         // Collect the index entries in a form we can use them.
908         Toc::const_iterator it = toc->begin();
909         Toc::const_iterator const en = toc->end();
910         vector<IndexEntry> entries;
911         for (; it != en; ++it)
912                 if (it->isOutput())
913                         entries.push_back(IndexEntry(it->str(), it->dit()));
914
915         if (entries.empty())
916                 // not very likely that all the index entries are in notes or
917                 // whatever, but....
918                 return docstring();
919
920         stable_sort(entries.begin(), entries.end());
921
922         Layout const & lay = bp.documentClass().htmlTOCLayout();
923         string const & tocclass = lay.defaultCSSClass();
924         string const tocattr = "class='index " + tocclass + "'";
925
926         // we'll use our own stream, because we are going to defer everything.
927         // that's how we deal with the fact that we're probably inside a standard
928         // paragraph, and we don't want to be.
929         odocstringstream ods;
930         XMLStream xs(ods);
931
932         xs << xml::StartTag("div", tocattr);
933         xs << xml::StartTag(lay.htmltag(), lay.htmlattr())
934                  << translateIfPossible(from_ascii("Index"),
935                                   op.local_font->language()->lang())
936                  << xml::EndTag(lay.htmltag());
937         xs << xml::StartTag("ul", "class='main'");
938         Font const dummy;
939
940         vector<IndexEntry>::const_iterator eit = entries.begin();
941         vector<IndexEntry>::const_iterator const een = entries.end();
942         // tracks whether we are already inside a main entry (1),
943         // a sub-entry (2), or a sub-sub-entry (3). see below for the
944         // details.
945         int level = 1;
946         // the last one we saw
947         IndexEntry last;
948         int entry_number = -1;
949         for (; eit != een; ++eit) {
950                 Paragraph const & par = eit->dit.innerParagraph();
951                 if (entry_number == -1 || !eit->equal(last)) {
952                         if (entry_number != -1) {
953                                 // not the first time through the loop, so
954                                 // close last entry or entries, depending.
955                                 if (level == 3) {
956                                         // close this sub-sub-entry
957                                         xs << xml::EndTag("li") << xml::CR();
958                                         // is this another sub-sub-entry within the same sub-entry?
959                                         if (!eit->same_sub(last)) {
960                                                 // close this level
961                                                 xs << xml::EndTag("ul") << xml::CR();
962                                                 level = 2;
963                                         }
964                                 }
965                                 // the point of the second test here is that we might get
966                                 // here two ways: (i) by falling through from above; (ii) because,
967                                 // though the sub-entry hasn't changed, the sub-sub-entry has,
968                                 // which means that it is the first sub-sub-entry within this
969                                 // sub-entry. In that case, we do not want to close anything.
970                                 if (level == 2 && !eit->same_sub(last)) {
971                                         // close sub-entry
972                                         xs << xml::EndTag("li") << xml::CR();
973                                         // is this another sub-entry with the same main entry?
974                                         if (!eit->same_main(last)) {
975                                                 // close this level
976                                                 xs << xml::EndTag("ul") << xml::CR();
977                                                 level = 1;
978                                         }
979                                 }
980                                 // again, we can get here two ways: from above, or because we have
981                                 // found the first sub-entry. in the latter case, we do not want to
982                                 // close the entry.
983                                 if (level == 1 && !eit->same_main(last)) {
984                                         // close entry
985                                         xs << xml::EndTag("li") << xml::CR();
986                                 }
987                         }
988
989                         // we'll be starting new entries
990                         entry_number = 0;
991
992                         // We need to use our own stream, since we will have to
993                         // modify what we get back.
994                         odocstringstream ent;
995                         XMLStream entstream(ent);
996                         OutputParams ours = op;
997                         ours.for_toc = true;
998                         par.simpleLyXHTMLOnePar(buffer(), entstream, ours, dummy);
999
1000                         // these will contain XHTML versions of the main entry, etc
1001                         // remember that everything will already have been escaped,
1002                         // so we'll need to use NextRaw() during output.
1003                         docstring main;
1004                         docstring sub;
1005                         docstring subsub;
1006                         extractSubentries(ent.str(), main, sub, subsub);
1007                         parseItem(main, true);
1008                         parseItem(sub, true);
1009                         parseItem(subsub, true);
1010
1011                         if (level == 3) {
1012                                 // another subsubentry
1013                                 xs << xml::StartTag("li", "class='subsubentry'")
1014                                    << XMLStream::ESCAPE_NONE << subsub;
1015                         } else if (level == 2) {
1016                                 // there are two ways we can be here:
1017                                 // (i) we can actually be inside a sub-entry already and be about
1018                                 //     to output the first sub-sub-entry. in this case, our sub
1019                                 //     and the last sub will be the same.
1020                                 // (ii) we can just have closed a sub-entry, possibly after also
1021                                 //     closing a list of sub-sub-entries. here our sub and the last
1022                                 //     sub are different.
1023                                 // only in the latter case do we need to output the new sub-entry.
1024                                 // note that in this case, too, though, the sub-entry might already
1025                                 // have a sub-sub-entry.
1026                                 if (eit->sub != last.sub)
1027                                         xs << xml::StartTag("li", "class='subentry'")
1028                                            << XMLStream::ESCAPE_NONE << sub;
1029                                 if (!subsub.empty()) {
1030                                         // it's actually a subsubentry, so we need to start that list
1031                                         xs << xml::CR()
1032                                            << xml::StartTag("ul", "class='subsubentry'")
1033                                            << xml::StartTag("li", "class='subsubentry'")
1034                                            << XMLStream::ESCAPE_NONE << subsub;
1035                                         level = 3;
1036                                 }
1037                         } else {
1038                                 // there are also two ways we can be here:
1039                                 // (i) we can actually be inside an entry already and be about
1040                                 //     to output the first sub-entry. in this case, our main
1041                                 //     and the last main will be the same.
1042                                 // (ii) we can just have closed an entry, possibly after also
1043                                 //     closing a list of sub-entries. here our main and the last
1044                                 //     main are different.
1045                                 // only in the latter case do we need to output the new main entry.
1046                                 // note that in this case, too, though, the main entry might already
1047                                 // have a sub-entry, or even a sub-sub-entry.
1048                                 if (eit->main != last.main)
1049                                         xs << xml::StartTag("li", "class='main'") << main;
1050                                 if (!sub.empty()) {
1051                                         // there's a sub-entry, too
1052                                         xs << xml::CR()
1053                                            << xml::StartTag("ul", "class='subentry'")
1054                                            << xml::StartTag("li", "class='subentry'")
1055                                            << XMLStream::ESCAPE_NONE << sub;
1056                                         level = 2;
1057                                         if (!subsub.empty()) {
1058                                                 // and a sub-sub-entry
1059                                                 xs << xml::CR()
1060                                                    << xml::StartTag("ul", "class='subsubentry'")
1061                                                    << xml::StartTag("li", "class='subsubentry'")
1062                                                    << XMLStream::ESCAPE_NONE << subsub;
1063                                                 level = 3;
1064                                         }
1065                                 }
1066                         }
1067                 }
1068                 // finally, then, we can output the index link itself
1069                 string const parattr = "href='#" + par.magicLabel() + "'";
1070                 xs << (entry_number == 0 ? ":" : ",");
1071                 xs << " " << xml::StartTag("a", parattr)
1072                    << ++entry_number << xml::EndTag("a");
1073                 last = *eit;
1074         }
1075         // now we have to close all the open levels
1076         while (level > 0) {
1077                 xs << xml::EndTag("li") << xml::EndTag("ul") << xml::CR();
1078                 --level;
1079         }
1080         xs << xml::EndTag("div") << xml::CR();
1081         return ods.str();
1082 }
1083
1084 } // namespace lyx