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