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