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