]> git.lyx.org Git - features.git/blob - src/insets/InsetIndex.cpp
Finish the output of the index for XHTML.
[features.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 "MetricsInfo.h"
27 #include "output_latex.h"
28 #include "output_xhtml.h"
29 #include "sgml.h"
30 #include "TocBackend.h"
31
32 #include "support/debug.h"
33 #include "support/docstream.h"
34 #include "support/gettext.h"
35 #include "support/lstrings.h"
36
37 #include "frontends/alert.h"
38
39 #include <ostream>
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                 }
157                 docstring const tpart = *it;
158                 os << tpart;
159                 if (it2 < levels_plain.end())
160                         ++it2;
161         }
162         // write the bit that followed "|"
163         if (!cmd.empty())
164                 os << "|" << cmd;
165         os << '}';
166         return i;
167 }
168
169
170 int InsetIndex::docbook(odocstream & os, OutputParams const & runparams) const
171 {
172         os << "<indexterm><primary>";
173         int const i = InsetText::docbook(os, runparams);
174         os << "</primary></indexterm>";
175         return i;
176 }
177
178
179 docstring InsetIndex::xhtml(XHTMLStream & xs, OutputParams const &) const
180 {
181         // we just print an anchor, taking the paragraph ID from 
182         // our own interior paragraph, which doesn't get printed
183         std::string const magic = paragraphs().front().magicLabel();
184         std::string const attr = "id='" + magic + "'";
185         xs << CompTag("a", attr);
186         return docstring();
187 }
188
189
190 bool InsetIndex::showInsetDialog(BufferView * bv) const
191 {
192         bv->showDialog("index", params2string(params_),
193                         const_cast<InsetIndex *>(this));
194         return true;
195 }
196
197
198 void InsetIndex::doDispatch(Cursor & cur, FuncRequest & cmd)
199 {
200         switch (cmd.action) {
201
202         case LFUN_INSET_MODIFY: {
203                 if (cmd.getArg(0) == "changetype") {
204                         params_.index = from_utf8(cmd.getArg(1));
205                         break;
206                 }
207                 InsetIndexParams params;
208                 InsetIndex::string2params(to_utf8(cmd.argument()), params);
209                 params_.index = params.index;
210                 break;
211         }
212
213         case LFUN_INSET_DIALOG_UPDATE:
214                 cur.bv().updateDialog("index", params2string(params_));
215                 break;
216
217         default:
218                 InsetCollapsable::doDispatch(cur, cmd);
219                 break;
220         }
221 }
222
223
224 bool InsetIndex::getStatus(Cursor & cur, FuncRequest const & cmd,
225                 FuncStatus & flag) const
226 {
227         switch (cmd.action) {
228
229         case LFUN_INSET_MODIFY:
230                 if (cmd.getArg(0) == "changetype") {
231                         docstring const newtype = from_utf8(cmd.getArg(1));
232                         Buffer const & realbuffer = *buffer().masterBuffer();
233                         IndicesList const & indiceslist = realbuffer.params().indiceslist();
234                         Index const * index = indiceslist.findShortcut(newtype);
235                         flag.setEnabled(index != 0);
236                         flag.setOnOff(
237                                 from_utf8(cmd.getArg(1)) == params_.index);
238                         return true;
239                 }
240                 flag.setEnabled(true);
241                 return true;
242
243         case LFUN_INSET_DIALOG_UPDATE: {
244                 Buffer const & realbuffer = *buffer().masterBuffer();
245                 flag.setEnabled(realbuffer.params().use_indices);
246                 return true;
247         }
248
249         default:
250                 return InsetCollapsable::getStatus(cur, cmd, flag);
251         }
252 }
253
254
255 ColorCode InsetIndex::labelColor() const
256 {
257         if (params_.index.empty() || params_.index == from_ascii("idx"))
258                 return InsetCollapsable::labelColor();
259         // FIXME UNICODE
260         ColorCode c = lcolor.getFromLyXName(to_utf8(params_.index));
261         if (c == Color_none)
262                 c = InsetCollapsable::labelColor();
263         return c;
264 }
265
266
267 docstring InsetIndex::toolTip(BufferView const &, int, int) const
268 {
269         docstring tip = _("Index Entry");
270         if (buffer().params().use_indices && !params_.index.empty()) {
271                 Buffer const & realbuffer = *buffer().masterBuffer();
272                 IndicesList const & indiceslist = realbuffer.params().indiceslist();
273                 tip += " (";
274                 Index const * index = indiceslist.findShortcut(params_.index);
275                 if (!index)
276                         tip += _("unknown type!");
277                 else
278                         tip += index->index();
279                 tip += ")";
280         }
281         tip += ": ";
282         OutputParams rp(&buffer().params().encoding());
283         odocstringstream ods;
284         InsetText::plaintext(ods, rp);
285         tip += ods.str();
286         return wrapParas(tip);
287 }
288
289
290 void InsetIndex::write(ostream & os) const
291 {
292         os << to_utf8(name());
293         params_.write(os);
294         InsetCollapsable::write(os);
295 }
296
297
298 void InsetIndex::read(Lexer & lex)
299 {
300         params_.read(lex);
301         InsetCollapsable::read(lex);
302 }
303
304
305 string InsetIndex::params2string(InsetIndexParams const & params)
306 {
307         ostringstream data;
308         data << "index";
309         params.write(data);
310         return data.str();
311 }
312
313
314 void InsetIndex::string2params(string const & in, InsetIndexParams & params)
315 {
316         params = InsetIndexParams();
317         if (in.empty())
318                 return;
319
320         istringstream data(in);
321         Lexer lex;
322         lex.setStream(data);
323         lex.setContext("InsetIndex::string2params");
324         lex >> "index";
325         params.read(lex);
326 }
327
328
329 void InsetIndex::addToToc(DocIterator const & cpit)
330 {
331         DocIterator pit = cpit;
332         pit.push_back(CursorSlice(*this));
333         docstring const item = text().asString(0, 1, AS_STR_LABEL | AS_STR_INSETS);
334         buffer().tocBackend().toc("index").push_back(TocItem(pit, 0, item));
335         // Proceed with the rest of the inset.
336         InsetCollapsable::addToToc(cpit);
337 }
338
339
340 void InsetIndex::validate(LaTeXFeatures & features) const
341 {
342         if (buffer().masterBuffer()->params().use_indices
343             && !params_.index.empty()
344             && params_.index != "idx")
345                 features.require("splitidx");
346 }
347
348
349 docstring InsetIndex::contextMenu(BufferView const &, int, int) const
350 {
351         return from_ascii("context-index");
352 }
353
354
355 bool InsetIndex::hasSettings() const
356 {
357         return buffer().masterBuffer()->params().use_indices;
358 }
359
360
361
362
363 /////////////////////////////////////////////////////////////////////
364 //
365 // InsetIndexParams
366 //
367 ///////////////////////////////////////////////////////////////////////
368
369
370 void InsetIndexParams::write(ostream & os) const
371 {
372         os << ' ';
373         if (!index.empty())
374                 os << to_utf8(index);
375         else
376                 os << "idx";
377         os << '\n';
378 }
379
380
381 void InsetIndexParams::read(Lexer & lex)
382 {
383         if (lex.eatLine())
384                 index = lex.getDocString();
385         else
386                 index = from_ascii("idx");
387 }
388
389
390 /////////////////////////////////////////////////////////////////////
391 //
392 // InsetPrintIndex
393 //
394 ///////////////////////////////////////////////////////////////////////
395
396 InsetPrintIndex::InsetPrintIndex(Buffer * buf, InsetCommandParams const & p)
397         : InsetCommand(buf, p, "index_print")
398 {}
399
400
401 ParamInfo const & InsetPrintIndex::findInfo(string const & /* cmdName */)
402 {
403         static ParamInfo param_info_;
404         if (param_info_.empty()) {
405                 param_info_.add("type", ParamInfo::LATEX_OPTIONAL);
406                 param_info_.add("name", ParamInfo::LATEX_REQUIRED);
407         }
408         return param_info_;
409 }
410
411
412 docstring InsetPrintIndex::screenLabel() const
413 {
414         bool const printall = suffixIs(getCmdName(), '*');
415         bool const multind = buffer().masterBuffer()->params().use_indices;
416         if ((!multind
417              && getParam("type") == from_ascii("idx"))
418             || (getParam("type").empty() && !printall))
419                 return _("Index");
420         Buffer const & realbuffer = *buffer().masterBuffer();
421         IndicesList const & indiceslist = realbuffer.params().indiceslist();
422         Index const * index = indiceslist.findShortcut(getParam("type"));
423         if (!index && !printall)
424                 return _("Unknown index type!");
425         docstring res = printall ? _("All indices") : index->index();
426         if (!multind)
427                 res += " (" + _("non-active") + ")";
428         else if (contains(getCmdName(), "printsubindex"))
429                 res += " (" + _("subindex") + ")";
430         return res;
431 }
432
433
434 bool InsetPrintIndex::isCompatibleCommand(string const & s)
435 {
436         return s == "printindex" || s == "printsubindex"
437                 || s == "printindex*" || s == "printsubindex*";
438 }
439
440
441 void InsetPrintIndex::doDispatch(Cursor & cur, FuncRequest & cmd)
442 {
443         switch (cmd.action) {
444
445         case LFUN_INSET_MODIFY: {
446                 if (cmd.argument() == from_ascii("toggle-subindex")) {
447                         string cmd = getCmdName();
448                         if (contains(cmd, "printindex"))
449                                 cmd = subst(cmd, "printindex", "printsubindex");
450                         else
451                                 cmd = subst(cmd, "printsubindex", "printindex");
452                         setCmdName(cmd);
453                         break;
454                 } else if (cmd.argument() == from_ascii("check-printindex*")) {
455                         string cmd = getCmdName();
456                         if (suffixIs(cmd, '*'))
457                                 break;
458                         cmd += '*';
459                         setParam("type", docstring());
460                         setCmdName(cmd);
461                         break;
462                 }
463                 InsetCommandParams p(INDEX_PRINT_CODE);
464                 // FIXME UNICODE
465                 InsetCommand::string2params("index_print",
466                         to_utf8(cmd.argument()), p);
467                 if (p.getCmdName().empty()) {
468                         cur.noUpdate();
469                         break;
470                 }
471                 setParams(p);
472                 break;
473         }
474
475         default:
476                 InsetCommand::doDispatch(cur, cmd);
477                 break;
478         }
479 }
480
481
482 bool InsetPrintIndex::getStatus(Cursor & cur, FuncRequest const & cmd,
483         FuncStatus & status) const
484 {
485         switch (cmd.action) {
486
487         case LFUN_INSET_MODIFY: {
488                 if (cmd.argument() == from_ascii("toggle-subindex")) {
489                         status.setEnabled(buffer().masterBuffer()->params().use_indices);
490                         status.setOnOff(contains(getCmdName(), "printsubindex"));
491                         return true;
492                 } else if (cmd.argument() == from_ascii("check-printindex*")) {
493                         status.setEnabled(buffer().masterBuffer()->params().use_indices);
494                         status.setOnOff(suffixIs(getCmdName(), '*'));
495                         return true;
496                 } if (cmd.getArg(0) == "index_print"
497                     && cmd.getArg(1) == "CommandInset") {
498                         InsetCommandParams p(INDEX_PRINT_CODE);
499                         InsetCommand::string2params("index_print",
500                                 to_utf8(cmd.argument()), p);
501                         if (suffixIs(p.getCmdName(), '*')) {
502                                 status.setEnabled(true);
503                                 status.setOnOff(false);
504                                 return true;
505                         }
506                         Buffer const & realbuffer = *buffer().masterBuffer();
507                         IndicesList const & indiceslist =
508                                 realbuffer.params().indiceslist();
509                         Index const * index = indiceslist.findShortcut(p["type"]);
510                         status.setEnabled(index != 0);
511                         status.setOnOff(p["type"] == getParam("type"));
512                         return true;
513                 } else
514                         return InsetCommand::getStatus(cur, cmd, status);
515         }
516         
517         case LFUN_INSET_DIALOG_UPDATE: {
518                 status.setEnabled(buffer().masterBuffer()->params().use_indices);
519                 return true;
520         }
521
522         default:
523                 return InsetCommand::getStatus(cur, cmd, status);
524         }
525 }
526
527
528 int InsetPrintIndex::latex(odocstream & os, OutputParams const &) const
529 {
530         if (!buffer().masterBuffer()->params().use_indices) {
531                 if (getParam("type") == from_ascii("idx"))
532                         os << "\\printindex{}";
533                 return 0;
534         }
535         os << getCommand();
536         return 0;
537 }
538
539
540 void InsetPrintIndex::validate(LaTeXFeatures & features) const
541 {
542         features.require("makeidx");
543         if (buffer().masterBuffer()->params().use_indices)
544                 features.require("splitidx");
545 }
546
547
548 docstring InsetPrintIndex::contextMenu(BufferView const &, int, int) const
549 {
550         return buffer().masterBuffer()->params().use_indices ?
551                 from_ascii("context-indexprint") : docstring();
552 }
553
554
555 bool InsetPrintIndex::hasSettings() const
556 {
557         return buffer().masterBuffer()->params().use_indices;
558 }
559
560
561 namespace {
562
563 void parseItem(docstring & s, bool for_output)
564 {
565         // this does not yet check for escaped things
566         size_type loc = s.find(from_ascii("@"));
567         if (loc != string::npos) {
568                 if (for_output)
569                         s.erase(0, loc + 1);
570                 else
571                         s.erase(loc);
572         }
573         loc = s.find(from_ascii("|"));
574         if (loc != string::npos)
575                 s.erase(loc);
576 }
577
578         
579 void extractSubentries(docstring const & entry, docstring & main,
580                 docstring & sub1, docstring & sub2)
581 {
582         if (entry.empty())
583                 return;
584         size_type const loc = entry.find(from_ascii(" ! "));
585         if (loc == string::npos)
586                 main = entry;
587         else {
588                 main = trim(entry.substr(0, loc));
589                 size_t const locend = loc + 3;
590                 size_type const loc2 = entry.find(from_ascii(" ! "), locend);
591                 if (loc2 == string::npos) {
592                         sub1 = trim(entry.substr(locend));
593                 } else {
594                         sub1 = trim(entry.substr(locend, loc2 - locend));
595                         sub2 = trim(entry.substr(loc2 + 3));
596                 }
597         }
598 }
599
600
601 struct IndexEntry
602 {
603         IndexEntry() 
604         {}
605         
606         IndexEntry(docstring const & s, DocIterator const & d) 
607                         : dit(d)
608         {
609                 extractSubentries(s, main, sub, subsub);
610                 parseItem(main, false);
611                 parseItem(sub, false);
612                 parseItem(subsub, false);
613         }
614         
615         bool equal(IndexEntry const & rhs) const
616         {
617                 return main == rhs.main && sub == rhs.sub && subsub == rhs.subsub;
618         }
619         
620         bool same_sub(IndexEntry const & rhs) const
621         {
622                 return main == rhs.main && sub == rhs.sub;
623         }
624         
625         bool same_main(IndexEntry const & rhs) const
626         {
627                 return main == rhs.main;
628         }
629         
630         docstring main;
631         docstring sub;
632         docstring subsub;
633         DocIterator dit;
634 };
635
636 bool operator<(IndexEntry const & lhs, IndexEntry const & rhs)
637 {
638         return lhs.main < rhs.main
639                         || (lhs.main == rhs.main && lhs.sub < rhs.sub)
640                         || (lhs.main == rhs.main && lhs.sub == rhs.sub && lhs.subsub < rhs.subsub);
641 }
642
643 } // anon namespace
644
645
646 docstring InsetPrintIndex::xhtml(XHTMLStream &, OutputParams const & op) const
647 {
648         BufferParams const & bp = buffer().masterBuffer()->params();
649
650         // we do not presently support multiple indices, so we refuse to print
651         // anything but the main index, so as not to generate multiple indices.
652         // NOTE Multiple index support would require some work. The reason
653         // is that the TOC does not know about multiple indices. Either it would
654         // need to be told about them (not a bad idea), or else the index entries
655         // would need to be collected differently, say, during validation.
656         if (bp.use_indices && getParam("type") != from_ascii("idx"))
657                 return docstring();
658         
659         Toc const & toc = buffer().tocBackend().toc("index");
660         if (toc.empty())
661                 return docstring();
662
663         // Collection the index entries in a form we can use them.
664         Toc::const_iterator it = toc.begin();
665         Toc::const_iterator const en = toc.end();
666         vector<IndexEntry> entries;
667         for (; it != en; ++it)
668                 entries.push_back(IndexEntry(it->str(), it->dit()));
669         stable_sort(entries.begin(), entries.end());
670
671         Layout const & lay = bp.documentClass().htmlTOCLayout();
672         string const & tocclass = lay.defaultCSSClass();
673         string const tocattr = "class='tochead " + tocclass + "'";
674
675         // we'll use our own stream, because we are going to defer everything.
676         // that's how we deal with the fact that we're probably inside a standard
677         // paragraph, and we don't want to be.
678         odocstringstream ods;
679         XHTMLStream xs(ods);
680
681         xs << StartTag("div", "class='index'");
682         xs << StartTag(lay.htmltag(), lay.htmlattr()) 
683                  << _("Index") 
684                  << EndTag(lay.htmltag());
685         xs << StartTag("ul", "class='main'");
686         Font const dummy;
687
688         vector<IndexEntry>::const_iterator eit = entries.begin();
689         vector<IndexEntry>::const_iterator const een = entries.end();
690         // tracks whether we are already inside a main entry (1),
691         // a sub-entry (2), or a sub-sub-entry (3). see below for the
692         // details.
693         int level = 1;
694         // the last one we saw
695         IndexEntry last;
696         int entry_number = -1;
697         for (; eit != een; ++eit) {
698                 Paragraph const & par = eit->dit.innerParagraph();
699                 if (entry_number == -1 || !eit->equal(last)) {
700                         if (entry_number != -1) {
701                                 // not the first time through the loop, so
702                                 // close last entry or entries, depending.
703                                 if (level == 3) {
704                                         // close this sub-sub-entry
705                                         xs << EndTag("li");
706                                         xs.cr();
707                                         // is this another sub-sub-entry within the same sub-entry?
708                                         if (!eit->same_sub(last)) {
709                                                 // close this level
710                                                 xs << EndTag("ul");
711                                                 xs.cr();
712                                                 level = 2;
713                                         }
714                                 }
715                                 // the point of the second test here is that we might get
716                                 // here two ways: (i) by falling through from above; (ii) because,
717                                 // though the sub-entry hasn't changed, the sub-sub-entry has,
718                                 // which means that it is the first sub-sub-entry within this
719                                 // sub-entry. In that case, we do not want to close anything.
720                                 if (level == 2 && !eit->same_sub(last)) {
721                                         // close sub-entry 
722                                         xs << EndTag("li");
723                                         xs.cr();
724                                         // is this another sub-entry with the same main entry?
725                                         if (!eit->same_main(last)) {
726                                                 // close this level
727                                                 xs << EndTag("ul");
728                                                 xs.cr();
729                                                 level = 1;
730                                         }
731                                 }
732                                 // again, we can get here two ways: from above, or because we have
733                                 // found the first sub-entry. in the latter case, we do not want to
734                                 // close the entry.
735                                 if (level == 1 && !eit->same_main(last)) {
736                                         // close entry
737                                         xs << EndTag("li");
738                                         xs.cr();
739                                 }
740                         }
741
742                         // we'll be starting new entries
743                         entry_number = 0;
744
745                         // We need to use our own stream, since we will have to
746                         // modify what we get back.
747                         odocstringstream ent;
748                         XHTMLStream entstream(ent);
749                         par.simpleLyXHTMLOnePar(buffer(), entstream, op, dummy, true);
750         
751                         // these will contain XHTML versions of the main entry, etc
752                         // remember that everything will already have been escaped,
753                         // so we'll need to use NextRaw() during output.
754                         docstring main;
755                         docstring sub;
756                         docstring subsub;
757                         extractSubentries(ent.str(), main, sub, subsub);
758                         parseItem(main, true);
759                         parseItem(sub, true);
760                         parseItem(subsub, true);
761         
762                         if (level == 3) {
763                                 // another subsubentry
764                                 xs << StartTag("li", "class='subsubentry'") 
765                                    << XHTMLStream::NextRaw() << subsub;
766                         } else if (level == 2) {
767                                 // there are two ways we can be here: 
768                                 // (i) we can actually be inside a sub-entry already and be about
769                                 //     to output the first sub-sub-entry. in this case, our sub
770                                 //     and the last sub will be the same.
771                                 // (ii) we can just have closed a sub-entry, possibly after also
772                                 //     closing a list of sub-sub-entries. here our sub and the last
773                                 //     sub are different.
774                                 // only in the latter case do we need to output the new sub-entry.
775                                 // note that in this case, too, though, the sub-entry might already
776                                 // have a sub-sub-entry.
777                                 if (eit->sub != last.sub)
778                                         xs << StartTag("li", "class='subentry'") 
779                                            << XHTMLStream::NextRaw() << sub;
780                                 if (!subsub.empty()) {
781                                         // it's actually a subsubentry, so we need to start that list
782                                         xs.cr();
783                                         xs << StartTag("ul", "class='subsubentry'") 
784                                            << StartTag("li", "class='subsubentry'") 
785                                            << XHTMLStream::NextRaw() << subsub;
786                                         level = 3;
787                                 } 
788                         } else {
789                                 // there are also two ways we can be here: 
790                                 // (i) we can actually be inside an entry already and be about
791                                 //     to output the first sub-entry. in this case, our main
792                                 //     and the last main will be the same.
793                                 // (ii) we can just have closed an entry, possibly after also
794                                 //     closing a list of sub-entries. here our main and the last
795                                 //     main are different.
796                                 // only in the latter case do we need to output the new main entry.
797                                 // note that in this case, too, though, the main entry might already
798                                 // have a sub-entry, or even a sub-sub-entry.
799                                 if (eit->main != last.main)
800                                         xs << StartTag("li", "class='main'") << main;
801                                 if (!sub.empty()) {
802                                         // there's a sub-entry, too
803                                         xs.cr();
804                                         xs << StartTag("ul", "class='subentry'") 
805                                            << StartTag("li", "class='subentry'") 
806                                            << XHTMLStream::NextRaw() << sub;
807                                         level = 2;
808                                         if (!subsub.empty()) {
809                                                 // and a sub-sub-entry
810                                                 xs.cr();
811                                                 xs << StartTag("ul", "class='subsubentry'") 
812                                                    << StartTag("li", "class='subsubentry'") 
813                                                    << XHTMLStream::NextRaw() << subsub;
814                                                 level = 3;
815                                         }
816                                 } 
817                         }
818                 }
819                 // finally, then, we can output the index link itself
820                 string const parattr = "href='#" + par.magicLabel() + "'";
821                 xs << (entry_number == 0 ? ":" : ",");
822                 xs << " " << StartTag("a", parattr)
823                    << ++entry_number << EndTag("a");
824                 last = *eit;
825         }
826         // now we have to close all the open levels
827         while (level > 0) {
828                 xs << EndTag("li") << EndTag("ul");
829                 xs.cr();
830                 --level;
831         }
832         xs << EndTag("div");
833         xs.cr();
834         return ods.str();
835 }
836
837 } // namespace lyx