]> git.lyx.org Git - lyx.git/blob - src/insets/InsetIndex.cpp
#5502 add binding for full screen toggle on mac
[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 "sgml.h"
31 #include "TextClass.h"
32 #include "TocBackend.h"
33
34 #include "support/debug.h"
35 #include "support/docstream.h"
36 #include "support/gettext.h"
37 #include "support/lstrings.h"
38
39 #include "frontends/alert.h"
40
41 #include <algorithm>
42 #include <ostream>
43
44 using namespace std;
45 using namespace lyx::support;
46
47 namespace lyx {
48
49 /////////////////////////////////////////////////////////////////////
50 //
51 // InsetIndex
52 //
53 ///////////////////////////////////////////////////////////////////////
54
55
56 InsetIndex::InsetIndex(Buffer * buf, InsetIndexParams const & params)
57         : InsetCollapsable(buf), params_(params)
58 {}
59
60
61 void InsetIndex::latex(otexstream & os, OutputParams const & runparams_in) const
62 {
63         OutputParams runparams(runparams_in);
64         runparams.inIndexEntry = true;
65
66         if (buffer().masterBuffer()->params().use_indices && !params_.index.empty()
67             && params_.index != "idx") {
68                 os << "\\sindex[";
69                 os << escape(params_.index);
70                 os << "]{";
71         } else {
72                 os << "\\index";
73                 os << '{';
74         }
75
76         // get contents of InsetText as LaTeX and plaintext
77         TexRow texrow;
78         odocstringstream ourlatex;
79         otexstream ots(ourlatex, texrow);
80         InsetText::latex(ots, runparams);
81         odocstringstream ourplain;
82         InsetText::plaintext(ourplain, runparams);
83         docstring latexstr = ourlatex.str();
84         docstring plainstr = ourplain.str();
85
86         // this will get what follows | if anything does
87         docstring cmd;
88
89         // check for the | separator
90         // FIXME This would go wrong on an escaped "|", but
91         // how far do we want to go here?
92         size_t pos = latexstr.find(from_ascii("|"));
93         if (pos != docstring::npos) {
94                 // put the bit after "|" into cmd...
95                 cmd = latexstr.substr(pos + 1);
96                 // ...and erase that stuff from latexstr
97                 latexstr = latexstr.erase(pos);
98                 // ...and similarly from plainstr
99                 size_t ppos = plainstr.find(from_ascii("|"));
100                 if (ppos < plainstr.size())
101                         plainstr.erase(ppos);
102                 else
103                         LYXERR0("The `|' separator was not found in the plaintext version!");
104         }
105
106         // Separate the entires and subentries, i.e., split on "!"
107         // FIXME This would do the wrong thing with escaped ! characters
108         std::vector<docstring> const levels =
109                 getVectorFromString(latexstr, from_ascii("!"), true);
110         std::vector<docstring> const levels_plain =
111                 getVectorFromString(plainstr, from_ascii("!"), true);
112
113         vector<docstring>::const_iterator it = levels.begin();
114         vector<docstring>::const_iterator end = levels.end();
115         vector<docstring>::const_iterator it2 = levels_plain.begin();
116         bool first = true;
117         for (; it != end; ++it) {
118                 // write the separator except the first time
119                 if (!first)
120                         os << '!';
121                 else
122                         first = false;
123
124                 // correctly sort macros and formatted strings
125                 // if we do find a command, prepend a plain text
126                 // version of the content to get sorting right,
127                 // e.g. \index{LyX@\LyX}, \index{text@\textbf{text}}
128                 // Don't do that if the user entered '@' himself, though.
129                 if (contains(*it, '\\') && !contains(*it, '@')) {
130                         // Plaintext might return nothing (e.g. for ERTs)
131                         docstring const spart = 
132                                 (it2 < levels_plain.end() && !(*it2).empty())
133                                 ? *it2 : *it;
134                         // Now we need to validate that all characters in
135                         // the sorting part are representable in the current
136                         // encoding. If not try the LaTeX macro which might
137                         // or might not be a good choice, and issue a warning.
138                         pair<docstring, docstring> spart_latexed =
139                                 runparams.encoding->latexString(spart, runparams.dryrun);
140                         if (!spart_latexed.second.empty())
141                                         LYXERR0("Uncodable character in index entry. Sorting might be wrong!");
142                         if (spart != spart_latexed.first && !runparams.dryrun) {
143                                 // FIXME: warning should be passed to the error dialog
144                                 frontend::Alert::warning(_("Index sorting failed"),
145                                 bformat(_("LyX's automatic index sorting algorithm faced\n"
146                                   "problems with the entry '%1$s'.\n"
147                                   "Please specify the sorting of this entry manually, as\n"
148                                   "explained in the User Guide."), spart));
149                         }
150                         // remove remaining \'s for the sorting part
151                         docstring const ppart =
152                                 subst(spart_latexed.first, from_ascii("\\"), docstring());
153                         os << ppart;
154                         os << '@';
155                 }
156                 docstring const tpart = *it;
157                 os << tpart;
158                 if (it2 < levels_plain.end())
159                         ++it2;
160         }
161         // write the bit that followed "|"
162         if (!cmd.empty()) {
163                 os << "|" << cmd;
164         }
165         os << '}';
166 }
167
168
169 int InsetIndex::docbook(odocstream & os, OutputParams const & runparams) const
170 {
171         os << "<indexterm><primary>";
172         int const i = InsetText::docbook(os, runparams);
173         os << "</primary></indexterm>";
174         return i;
175 }
176
177
178 docstring InsetIndex::xhtml(XHTMLStream & xs, OutputParams const &) const
179 {
180         // we just print an anchor, taking the paragraph ID from 
181         // our own interior paragraph, which doesn't get printed
182         std::string const magic = paragraphs().front().magicLabel();
183         std::string const attr = "id='" + magic + "'";
184         xs << html::CompTag("a", attr);
185         return docstring();
186 }
187
188
189 bool InsetIndex::showInsetDialog(BufferView * bv) const
190 {
191         bv->showDialog("index", params2string(params_),
192                         const_cast<InsetIndex *>(this));
193         return true;
194 }
195
196
197 void InsetIndex::doDispatch(Cursor & cur, FuncRequest & cmd)
198 {
199         switch (cmd.action()) {
200
201         case LFUN_INSET_MODIFY: {
202                 if (cmd.getArg(0) == "changetype") {
203                         cur.recordUndoInset(this);
204                         params_.index = from_utf8(cmd.getArg(1));
205                         break;
206                 }
207                 InsetIndexParams params;
208                 InsetIndex::string2params(to_utf8(cmd.argument()), params);
209                 cur.recordUndoInset(this);
210                 params_.index = params.index;
211                 // what we really want here is a TOC update, but that means
212                 // a full buffer update
213                 cur.forceBufferUpdate();
214                 break;
215         }
216
217         case LFUN_INSET_DIALOG_UPDATE:
218                 cur.bv().updateDialog("index", params2string(params_));
219                 break;
220
221         default:
222                 InsetCollapsable::doDispatch(cur, cmd);
223                 break;
224         }
225 }
226
227
228 bool InsetIndex::getStatus(Cursor & cur, FuncRequest const & cmd,
229                 FuncStatus & flag) const
230 {
231         switch (cmd.action()) {
232
233         case LFUN_INSET_MODIFY:
234                 if (cmd.getArg(0) == "changetype") {
235                         docstring const newtype = from_utf8(cmd.getArg(1));
236                         Buffer const & realbuffer = *buffer().masterBuffer();
237                         IndicesList const & indiceslist = realbuffer.params().indiceslist();
238                         Index const * index = indiceslist.findShortcut(newtype);
239                         flag.setEnabled(index != 0);
240                         flag.setOnOff(
241                                 from_utf8(cmd.getArg(1)) == params_.index);
242                         return true;
243                 }
244                 return InsetCollapsable::getStatus(cur, cmd, flag);
245
246         case LFUN_INSET_DIALOG_UPDATE: {
247                 Buffer const & realbuffer = *buffer().masterBuffer();
248                 flag.setEnabled(realbuffer.params().use_indices);
249                 return true;
250         }
251
252         default:
253                 return InsetCollapsable::getStatus(cur, cmd, flag);
254         }
255 }
256
257
258 ColorCode InsetIndex::labelColor() const
259 {
260         if (params_.index.empty() || params_.index == from_ascii("idx"))
261                 return InsetCollapsable::labelColor();
262         // FIXME UNICODE
263         ColorCode c = lcolor.getFromLyXName(to_utf8(params_.index));
264         if (c == Color_none)
265                 c = InsetCollapsable::labelColor();
266         return c;
267 }
268
269
270 docstring InsetIndex::toolTip(BufferView const &, int, int) const
271 {
272         docstring tip = _("Index Entry");
273         if (buffer().params().use_indices && !params_.index.empty()) {
274                 Buffer const & realbuffer = *buffer().masterBuffer();
275                 IndicesList const & indiceslist = realbuffer.params().indiceslist();
276                 tip += " (";
277                 Index const * index = indiceslist.findShortcut(params_.index);
278                 if (!index)
279                         tip += _("unknown type!");
280                 else
281                         tip += index->index();
282                 tip += ")";
283         }
284         tip += ": ";
285         return toolTipText(tip);
286 }
287
288
289 docstring const InsetIndex::buttonLabel(BufferView const & bv) const
290 {
291         InsetLayout const & il = getLayout();
292         docstring label = translateIfPossible(il.labelstring());
293
294         if (buffer().params().use_indices && !params_.index.empty()) {
295                 Buffer const & realbuffer = *buffer().masterBuffer();
296                 IndicesList const & indiceslist = realbuffer.params().indiceslist();
297                 label += " (";
298                 Index const * index = indiceslist.findShortcut(params_.index);
299                 if (!index)
300                         label += _("unknown type!");
301                 else
302                         label += index->index();
303                 label += ")";
304         }
305
306         if (!il.contentaslabel() || geometry(bv) != ButtonOnly)
307                 return label;
308         return getNewLabel(label);
309 }
310
311
312 void InsetIndex::write(ostream & os) const
313 {
314         os << to_utf8(layoutName());
315         params_.write(os);
316         InsetCollapsable::write(os);
317 }
318
319
320 void InsetIndex::read(Lexer & lex)
321 {
322         params_.read(lex);
323         InsetCollapsable::read(lex);
324 }
325
326
327 string InsetIndex::params2string(InsetIndexParams const & params)
328 {
329         ostringstream data;
330         data << "index";
331         params.write(data);
332         return data.str();
333 }
334
335
336 void InsetIndex::string2params(string const & in, InsetIndexParams & params)
337 {
338         params = InsetIndexParams();
339         if (in.empty())
340                 return;
341
342         istringstream data(in);
343         Lexer lex;
344         lex.setStream(data);
345         lex.setContext("InsetIndex::string2params");
346         lex >> "index";
347         params.read(lex);
348 }
349
350
351 void InsetIndex::addToToc(DocIterator const & cpit, bool output_active) const
352 {
353         DocIterator pit = cpit;
354         pit.push_back(CursorSlice(const_cast<InsetIndex &>(*this)));
355         docstring str;
356         text().forOutliner(str, 0);
357         buffer().tocBackend().toc("index").push_back(TocItem(pit, 0, str, output_active));
358         // Proceed with the rest of the inset.
359         InsetCollapsable::addToToc(cpit, output_active);
360 }
361
362
363 void InsetIndex::validate(LaTeXFeatures & features) const
364 {
365         if (buffer().masterBuffer()->params().use_indices
366             && !params_.index.empty()
367             && params_.index != "idx")
368                 features.require("splitidx");
369         InsetCollapsable::validate(features);
370 }
371
372
373 string InsetIndex::contextMenuName() const
374 {
375         return "context-index";
376 }
377
378
379 bool InsetIndex::hasSettings() const
380 {
381         return buffer().masterBuffer()->params().use_indices;
382 }
383
384
385
386
387 /////////////////////////////////////////////////////////////////////
388 //
389 // InsetIndexParams
390 //
391 ///////////////////////////////////////////////////////////////////////
392
393
394 void InsetIndexParams::write(ostream & os) const
395 {
396         os << ' ';
397         if (!index.empty())
398                 os << to_utf8(index);
399         else
400                 os << "idx";
401         os << '\n';
402 }
403
404
405 void InsetIndexParams::read(Lexer & lex)
406 {
407         if (lex.eatLine())
408                 index = lex.getDocString();
409         else
410                 index = from_ascii("idx");
411 }
412
413
414 /////////////////////////////////////////////////////////////////////
415 //
416 // InsetPrintIndex
417 //
418 ///////////////////////////////////////////////////////////////////////
419
420 InsetPrintIndex::InsetPrintIndex(Buffer * buf, InsetCommandParams const & p)
421         : InsetCommand(buf, p)
422 {}
423
424
425 ParamInfo const & InsetPrintIndex::findInfo(string const & /* cmdName */)
426 {
427         static ParamInfo param_info_;
428         if (param_info_.empty()) {
429                 param_info_.add("type", ParamInfo::LATEX_OPTIONAL,
430                         ParamInfo::HANDLING_ESCAPE);
431                 param_info_.add("name", ParamInfo::LATEX_REQUIRED);
432         }
433         return param_info_;
434 }
435
436
437 docstring InsetPrintIndex::screenLabel() const
438 {
439         bool const printall = suffixIs(getCmdName(), '*');
440         bool const multind = buffer().masterBuffer()->params().use_indices;
441         if ((!multind
442              && getParam("type") == from_ascii("idx"))
443             || (getParam("type").empty() && !printall))
444                 return _("Index");
445         Buffer const & realbuffer = *buffer().masterBuffer();
446         IndicesList const & indiceslist = realbuffer.params().indiceslist();
447         Index const * index = indiceslist.findShortcut(getParam("type"));
448         if (!index && !printall)
449                 return _("Unknown index type!");
450         docstring res = printall ? _("All indexes") : index->index();
451         if (!multind)
452                 res += " (" + _("non-active") + ")";
453         else if (contains(getCmdName(), "printsubindex"))
454                 res += " (" + _("subindex") + ")";
455         return res;
456 }
457
458
459 bool InsetPrintIndex::isCompatibleCommand(string const & s)
460 {
461         return s == "printindex" || s == "printsubindex"
462                 || s == "printindex*" || s == "printsubindex*";
463 }
464
465
466 void InsetPrintIndex::doDispatch(Cursor & cur, FuncRequest & cmd)
467 {
468         switch (cmd.action()) {
469
470         case LFUN_INSET_MODIFY: {
471                 if (cmd.argument() == from_ascii("toggle-subindex")) {
472                         string cmd = getCmdName();
473                         if (contains(cmd, "printindex"))
474                                 cmd = subst(cmd, "printindex", "printsubindex");
475                         else
476                                 cmd = subst(cmd, "printsubindex", "printindex");
477                         cur.recordUndo();
478                         setCmdName(cmd);
479                         break;
480                 } else if (cmd.argument() == from_ascii("check-printindex*")) {
481                         string cmd = getCmdName();
482                         if (suffixIs(cmd, '*'))
483                                 break;
484                         cmd += '*';
485                         cur.recordUndo();
486                         setParam("type", docstring());
487                         setCmdName(cmd);
488                         break;
489                 }
490                 InsetCommandParams p(INDEX_PRINT_CODE);
491                 // FIXME UNICODE
492                 InsetCommand::string2params(to_utf8(cmd.argument()), p);
493                 if (p.getCmdName().empty()) {
494                         cur.noScreenUpdate();
495                         break;
496                 }
497                 cur.recordUndo();
498                 setParams(p);
499                 break;
500         }
501
502         default:
503                 InsetCommand::doDispatch(cur, cmd);
504                 break;
505         }
506 }
507
508
509 bool InsetPrintIndex::getStatus(Cursor & cur, FuncRequest const & cmd,
510         FuncStatus & status) const
511 {
512         switch (cmd.action()) {
513
514         case LFUN_INSET_MODIFY: {
515                 if (cmd.argument() == from_ascii("toggle-subindex")) {
516                         status.setEnabled(buffer().masterBuffer()->params().use_indices);
517                         status.setOnOff(contains(getCmdName(), "printsubindex"));
518                         return true;
519                 } else if (cmd.argument() == from_ascii("check-printindex*")) {
520                         status.setEnabled(buffer().masterBuffer()->params().use_indices);
521                         status.setOnOff(suffixIs(getCmdName(), '*'));
522                         return true;
523                 } if (cmd.getArg(0) == "index_print"
524                     && cmd.getArg(1) == "CommandInset") {
525                         InsetCommandParams p(INDEX_PRINT_CODE);
526                         InsetCommand::string2params(to_utf8(cmd.argument()), p);
527                         if (suffixIs(p.getCmdName(), '*')) {
528                                 status.setEnabled(true);
529                                 status.setOnOff(false);
530                                 return true;
531                         }
532                         Buffer const & realbuffer = *buffer().masterBuffer();
533                         IndicesList const & indiceslist =
534                                 realbuffer.params().indiceslist();
535                         Index const * index = indiceslist.findShortcut(p["type"]);
536                         status.setEnabled(index != 0);
537                         status.setOnOff(p["type"] == getParam("type"));
538                         return true;
539                 } else
540                         return InsetCommand::getStatus(cur, cmd, status);
541         }
542         
543         case LFUN_INSET_DIALOG_UPDATE: {
544                 status.setEnabled(buffer().masterBuffer()->params().use_indices);
545                 return true;
546         }
547
548         default:
549                 return InsetCommand::getStatus(cur, cmd, status);
550         }
551 }
552
553
554 void InsetPrintIndex::latex(otexstream & os, OutputParams const & runparams_in) const
555 {
556         if (!buffer().masterBuffer()->params().use_indices) {
557                 if (getParam("type") == from_ascii("idx"))
558                         os << "\\printindex{}";
559                 return;
560         }
561         OutputParams runparams = runparams_in;
562         os << getCommand(runparams);
563 }
564
565
566 void InsetPrintIndex::validate(LaTeXFeatures & features) const
567 {
568         features.require("makeidx");
569         if (buffer().masterBuffer()->params().use_indices)
570                 features.require("splitidx");
571 }
572
573
574 string InsetPrintIndex::contextMenuName() const
575 {
576         return buffer().masterBuffer()->params().use_indices ?
577                 "context-indexprint" : string();
578 }
579
580
581 bool InsetPrintIndex::hasSettings() const
582 {
583         return buffer().masterBuffer()->params().use_indices;
584 }
585
586
587 namespace {
588
589 void parseItem(docstring & s, bool for_output)
590 {
591         // this does not yet check for escaped things
592         size_type loc = s.find(from_ascii("@"));
593         if (loc != string::npos) {
594                 if (for_output)
595                         s.erase(0, loc + 1);
596                 else
597                         s.erase(loc);
598         }
599         loc = s.find(from_ascii("|"));
600         if (loc != string::npos)
601                 s.erase(loc);
602 }
603
604         
605 void extractSubentries(docstring const & entry, docstring & main,
606                 docstring & sub1, docstring & sub2)
607 {
608         if (entry.empty())
609                 return;
610         size_type const loc = entry.find(from_ascii(" ! "));
611         if (loc == string::npos)
612                 main = entry;
613         else {
614                 main = trim(entry.substr(0, loc));
615                 size_t const locend = loc + 3;
616                 size_type const loc2 = entry.find(from_ascii(" ! "), locend);
617                 if (loc2 == string::npos) {
618                         sub1 = trim(entry.substr(locend));
619                 } else {
620                         sub1 = trim(entry.substr(locend, loc2 - locend));
621                         sub2 = trim(entry.substr(loc2 + 3));
622                 }
623         }
624 }
625
626
627 struct IndexEntry
628 {
629         IndexEntry() 
630         {}
631         
632         IndexEntry(docstring const & s, DocIterator const & d) 
633                         : dit(d)
634         {
635                 extractSubentries(s, main, sub, subsub);
636                 parseItem(main, false);
637                 parseItem(sub, false);
638                 parseItem(subsub, false);
639         }
640         
641         bool equal(IndexEntry const & rhs) const
642         {
643                 return main == rhs.main && sub == rhs.sub && subsub == rhs.subsub;
644         }
645         
646         bool same_sub(IndexEntry const & rhs) const
647         {
648                 return main == rhs.main && sub == rhs.sub;
649         }
650         
651         bool same_main(IndexEntry const & rhs) const
652         {
653                 return main == rhs.main;
654         }
655         
656         docstring main;
657         docstring sub;
658         docstring subsub;
659         DocIterator dit;
660 };
661
662 bool operator<(IndexEntry const & lhs, IndexEntry const & rhs)
663 {
664         int comp = compare_no_case(lhs.main, rhs.main);
665         if (comp == 0)
666                 comp = compare_no_case(lhs.sub, rhs.sub);
667         if (comp == 0)
668                 comp = compare_no_case(lhs.subsub, rhs.subsub);
669         return (comp < 0);
670 }
671
672 } // anon namespace
673
674
675 docstring InsetPrintIndex::xhtml(XHTMLStream &, OutputParams const & op) const
676 {
677         BufferParams const & bp = buffer().masterBuffer()->params();
678
679         // we do not presently support multiple indices, so we refuse to print
680         // anything but the main index, so as not to generate multiple indices.
681         // NOTE Multiple index support would require some work. The reason
682         // is that the TOC does not know about multiple indices. Either it would
683         // need to be told about them (not a bad idea), or else the index entries
684         // would need to be collected differently, say, during validation.
685         if (bp.use_indices && getParam("type") != from_ascii("idx"))
686                 return docstring();
687         
688         Toc const & toc = buffer().tocBackend().toc("index");
689         if (toc.empty())
690                 return docstring();
691
692         // Collect the index entries in a form we can use them.
693         Toc::const_iterator it = toc.begin();
694         Toc::const_iterator const en = toc.end();
695         vector<IndexEntry> entries;
696         for (; it != en; ++it)
697                 if (it->isOutput())
698                         entries.push_back(IndexEntry(it->str(), it->dit()));
699
700         if (entries.empty())
701                 // not very likely that all the index entries are in notes or
702                 // whatever, but....
703                 return docstring();
704
705         stable_sort(entries.begin(), entries.end());
706
707         Layout const & lay = bp.documentClass().htmlTOCLayout();
708         string const & tocclass = lay.defaultCSSClass();
709         string const tocattr = "class='index " + tocclass + "'";
710
711         // we'll use our own stream, because we are going to defer everything.
712         // that's how we deal with the fact that we're probably inside a standard
713         // paragraph, and we don't want to be.
714         odocstringstream ods;
715         XHTMLStream xs(ods);
716
717         xs << html::StartTag("div", tocattr);
718         xs << html::StartTag(lay.htmltag(), lay.htmlattr()) 
719                  << translateIfPossible(from_ascii("Index"),
720                                   op.local_font->language()->lang())
721                  << html::EndTag(lay.htmltag());
722         xs << html::StartTag("ul", "class='main'");
723         Font const dummy;
724
725         vector<IndexEntry>::const_iterator eit = entries.begin();
726         vector<IndexEntry>::const_iterator const een = entries.end();
727         // tracks whether we are already inside a main entry (1),
728         // a sub-entry (2), or a sub-sub-entry (3). see below for the
729         // details.
730         int level = 1;
731         // the last one we saw
732         IndexEntry last;
733         int entry_number = -1;
734         for (; eit != een; ++eit) {
735                 Paragraph const & par = eit->dit.innerParagraph();
736                 if (entry_number == -1 || !eit->equal(last)) {
737                         if (entry_number != -1) {
738                                 // not the first time through the loop, so
739                                 // close last entry or entries, depending.
740                                 if (level == 3) {
741                                         // close this sub-sub-entry
742                                         xs << html::EndTag("li") << html::CR();
743                                         // is this another sub-sub-entry within the same sub-entry?
744                                         if (!eit->same_sub(last)) {
745                                                 // close this level
746                                                 xs << html::EndTag("ul") << html::CR();
747                                                 level = 2;
748                                         }
749                                 }
750                                 // the point of the second test here is that we might get
751                                 // here two ways: (i) by falling through from above; (ii) because,
752                                 // though the sub-entry hasn't changed, the sub-sub-entry has,
753                                 // which means that it is the first sub-sub-entry within this
754                                 // sub-entry. In that case, we do not want to close anything.
755                                 if (level == 2 && !eit->same_sub(last)) {
756                                         // close sub-entry 
757                                         xs << html::EndTag("li") << html::CR();
758                                         // is this another sub-entry with the same main entry?
759                                         if (!eit->same_main(last)) {
760                                                 // close this level
761                                                 xs << html::EndTag("ul") << html::CR();
762                                                 level = 1;
763                                         }
764                                 }
765                                 // again, we can get here two ways: from above, or because we have
766                                 // found the first sub-entry. in the latter case, we do not want to
767                                 // close the entry.
768                                 if (level == 1 && !eit->same_main(last)) {
769                                         // close entry
770                                         xs << html::EndTag("li") << html::CR();
771                                 }
772                         }
773
774                         // we'll be starting new entries
775                         entry_number = 0;
776
777                         // We need to use our own stream, since we will have to
778                         // modify what we get back.
779                         odocstringstream ent;
780                         XHTMLStream entstream(ent);
781                         OutputParams ours = op;
782                         ours.for_toc = true;
783                         par.simpleLyXHTMLOnePar(buffer(), entstream, ours, dummy);
784         
785                         // these will contain XHTML versions of the main entry, etc
786                         // remember that everything will already have been escaped,
787                         // so we'll need to use NextRaw() during output.
788                         docstring main;
789                         docstring sub;
790                         docstring subsub;
791                         extractSubentries(ent.str(), main, sub, subsub);
792                         parseItem(main, true);
793                         parseItem(sub, true);
794                         parseItem(subsub, true);
795         
796                         if (level == 3) {
797                                 // another subsubentry
798                                 xs << html::StartTag("li", "class='subsubentry'") 
799                                    << XHTMLStream::ESCAPE_NONE << subsub;
800                         } else if (level == 2) {
801                                 // there are two ways we can be here: 
802                                 // (i) we can actually be inside a sub-entry already and be about
803                                 //     to output the first sub-sub-entry. in this case, our sub
804                                 //     and the last sub will be the same.
805                                 // (ii) we can just have closed a sub-entry, possibly after also
806                                 //     closing a list of sub-sub-entries. here our sub and the last
807                                 //     sub are different.
808                                 // only in the latter case do we need to output the new sub-entry.
809                                 // note that in this case, too, though, the sub-entry might already
810                                 // have a sub-sub-entry.
811                                 if (eit->sub != last.sub)
812                                         xs << html::StartTag("li", "class='subentry'") 
813                                            << XHTMLStream::ESCAPE_NONE << sub;
814                                 if (!subsub.empty()) {
815                                         // it's actually a subsubentry, so we need to start that list
816                                         xs << html::CR()
817                                            << html::StartTag("ul", "class='subsubentry'") 
818                                            << html::StartTag("li", "class='subsubentry'") 
819                                            << XHTMLStream::ESCAPE_NONE << subsub;
820                                         level = 3;
821                                 } 
822                         } else {
823                                 // there are also two ways we can be here: 
824                                 // (i) we can actually be inside an entry already and be about
825                                 //     to output the first sub-entry. in this case, our main
826                                 //     and the last main will be the same.
827                                 // (ii) we can just have closed an entry, possibly after also
828                                 //     closing a list of sub-entries. here our main and the last
829                                 //     main are different.
830                                 // only in the latter case do we need to output the new main entry.
831                                 // note that in this case, too, though, the main entry might already
832                                 // have a sub-entry, or even a sub-sub-entry.
833                                 if (eit->main != last.main)
834                                         xs << html::StartTag("li", "class='main'") << main;
835                                 if (!sub.empty()) {
836                                         // there's a sub-entry, too
837                                         xs << html::CR()
838                                            << html::StartTag("ul", "class='subentry'") 
839                                            << html::StartTag("li", "class='subentry'") 
840                                            << XHTMLStream::ESCAPE_NONE << sub;
841                                         level = 2;
842                                         if (!subsub.empty()) {
843                                                 // and a sub-sub-entry
844                                                 xs << html::CR()
845                                                    << html::StartTag("ul", "class='subsubentry'") 
846                                                    << html::StartTag("li", "class='subsubentry'") 
847                                                    << XHTMLStream::ESCAPE_NONE << subsub;
848                                                 level = 3;
849                                         }
850                                 } 
851                         }
852                 }
853                 // finally, then, we can output the index link itself
854                 string const parattr = "href='#" + par.magicLabel() + "'";
855                 xs << (entry_number == 0 ? ":" : ",");
856                 xs << " " << html::StartTag("a", parattr)
857                    << ++entry_number << html::EndTag("a");
858                 last = *eit;
859         }
860         // now we have to close all the open levels
861         while (level > 0) {
862                 xs << html::EndTag("li") << html::EndTag("ul") << html::CR();
863                 --level;
864         }
865         xs << html::EndTag("div") << html::CR();
866         return ods.str();
867 }
868
869 } // namespace lyx