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