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