]> git.lyx.org Git - features.git/blob - src/insets/InsetIndex.cpp
Move the StartTag, EndTag, and CompTag classes into the html namespace.
[features.git] / src / insets / InsetIndex.cpp
1 /**
2  * \file InsetIndex.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author Jürgen Spitzmüller
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11 #include <config.h>
12
13 #include "InsetIndex.h"
14
15 #include "Buffer.h"
16 #include "BufferParams.h"
17 #include "BufferView.h"
18 #include "ColorSet.h"
19 #include "DispatchResult.h"
20 #include "Encoding.h"
21 #include "FuncRequest.h"
22 #include "FuncStatus.h"
23 #include "IndicesList.h"
24 #include "LaTeXFeatures.h"
25 #include "Lexer.h"
26 #include "MetricsInfo.h"
27 #include "output_latex.h"
28 #include "output_xhtml.h"
29 #include "sgml.h"
30 #include "TocBackend.h"
31
32 #include "support/debug.h"
33 #include "support/docstream.h"
34 #include "support/gettext.h"
35 #include "support/lstrings.h"
36
37 #include "frontends/alert.h"
38
39 #include <ostream>
40
41 using namespace std;
42 using namespace lyx::support;
43
44 namespace lyx {
45
46 /////////////////////////////////////////////////////////////////////
47 //
48 // InsetIndex
49 //
50 ///////////////////////////////////////////////////////////////////////
51
52
53 InsetIndex::InsetIndex(Buffer * buf, InsetIndexParams const & params)
54         : InsetCollapsable(buf), params_(params)
55 {}
56
57
58 int InsetIndex::latex(odocstream & os,
59                       OutputParams const & runparams_in) const
60 {
61         OutputParams runparams(runparams_in);
62         runparams.inIndexEntry = true;
63
64         if (buffer().masterBuffer()->params().use_indices && !params_.index.empty()
65             && params_.index != "idx") {
66                 os << "\\sindex[";
67                 os << params_.index;
68                 os << "]{";
69         } else {
70                 os << "\\index";
71                 os << '{';
72         }
73         int i = 0;
74
75         // get contents of InsetText as LaTeX and plaintext
76         odocstringstream ourlatex;
77         InsetText::latex(ourlatex, runparams);
78         odocstringstream ourplain;
79         InsetText::plaintext(ourplain, runparams);
80         docstring latexstr = ourlatex.str();
81         docstring plainstr = ourplain.str();
82
83         // this will get what follows | if anything does
84         docstring cmd;
85
86         // check for the | separator
87         // FIXME This would go wrong on an escaped "|", but
88         // how far do we want to go here?
89         size_t pos = latexstr.find(from_ascii("|"));
90         if (pos != docstring::npos) {
91                 // put the bit after "|" into cmd...
92                 cmd = latexstr.substr(pos + 1);
93                 // ...and erase that stuff from latexstr
94                 latexstr = latexstr.erase(pos);
95                 // ...and similarly from plainstr
96                 size_t ppos = plainstr.find(from_ascii("|"));
97                 if (ppos < plainstr.size())
98                         plainstr.erase(ppos);
99                 else
100                         LYXERR0("The `|' separator was not found in the plaintext version!");
101         }
102
103         // Separate the entires and subentries, i.e., split on "!"
104         // FIXME This would do the wrong thing with escaped ! characters
105         std::vector<docstring> const levels =
106                 getVectorFromString(latexstr, from_ascii("!"), true);
107         std::vector<docstring> const levels_plain =
108                 getVectorFromString(plainstr, from_ascii("!"), true);
109
110         vector<docstring>::const_iterator it = levels.begin();
111         vector<docstring>::const_iterator end = levels.end();
112         vector<docstring>::const_iterator it2 = levels_plain.begin();
113         bool first = true;
114         for (; it != end; ++it) {
115                 // write the separator except the first time
116                 if (!first)
117                         os << '!';
118                 else
119                         first = false;
120
121                 // correctly sort macros and formatted strings
122                 // if we do find a command, prepend a plain text
123                 // version of the content to get sorting right,
124                 // e.g. \index{LyX@\LyX}, \index{text@\textbf{text}}
125                 // Don't do that if the user entered '@' himself, though.
126                 if (contains(*it, '\\') && !contains(*it, '@')) {
127                         // Plaintext might return nothing (e.g. for ERTs)
128                         docstring const spart = 
129                                 (it2 < levels_plain.end() && !(*it2).empty())
130                                 ? *it2 : *it;
131                         // Now we need to validate that all characters in
132                         // the sorting part are representable in the current
133                         // encoding. If not try the LaTeX macro which might
134                         // or might not be a good choice, and issue a warning.
135                         docstring spart2;
136                         for (size_t n = 0; n < spart.size(); ++n) {
137                                 try {
138                                         spart2 += runparams.encoding->latexChar(spart[n]);
139                                 } catch (EncodingException & /* e */) {
140                                         LYXERR0("Uncodable character in index entry. Sorting might be wrong!");
141                                 }
142                         }
143                         if (spart != spart2 && !runparams.dryrun) {
144                                 // FIXME: warning should be passed to the error dialog
145                                 frontend::Alert::warning(_("Index sorting failed"),
146                                 bformat(_("LyX's automatic index sorting algorithm faced\n"
147                                   "problems with the entry '%1$s'.\n"
148                                   "Please specify the sorting of this entry manually, as\n"
149                                   "explained in the User Guide."), spart));
150                         }
151                         // remove remaining \'s for the sorting part
152                         docstring const ppart =
153                                 subst(spart2, from_ascii("\\"), docstring());
154                         os << ppart;
155                         os << '@';
156                 }
157                 docstring const tpart = *it;
158                 os << tpart;
159                 if (it2 < levels_plain.end())
160                         ++it2;
161         }
162         // write the bit that followed "|"
163         if (!cmd.empty())
164                 os << "|" << cmd;
165         os << '}';
166         return i;
167 }
168
169
170 int InsetIndex::docbook(odocstream & os, OutputParams const & runparams) const
171 {
172         os << "<indexterm><primary>";
173         int const i = InsetText::docbook(os, runparams);
174         os << "</primary></indexterm>";
175         return i;
176 }
177
178
179 docstring InsetIndex::xhtml(XHTMLStream & xs, OutputParams const &) const
180 {
181         // we just print an anchor, taking the paragraph ID from 
182         // our own interior paragraph, which doesn't get printed
183         std::string const magic = paragraphs().front().magicLabel();
184         std::string const attr = "id='" + magic + "'";
185         xs << html::CompTag("a", attr);
186         return docstring();
187 }
188
189
190 bool InsetIndex::showInsetDialog(BufferView * bv) const
191 {
192         bv->showDialog("index", params2string(params_),
193                         const_cast<InsetIndex *>(this));
194         return true;
195 }
196
197
198 void InsetIndex::doDispatch(Cursor & cur, FuncRequest & cmd)
199 {
200         switch (cmd.action) {
201
202         case LFUN_INSET_MODIFY: {
203                 if (cmd.getArg(0) == "changetype") {
204                         params_.index = from_utf8(cmd.getArg(1));
205                         break;
206                 }
207                 InsetIndexParams params;
208                 InsetIndex::string2params(to_utf8(cmd.argument()), params);
209                 params_.index = params.index;
210                 break;
211         }
212
213         case LFUN_INSET_DIALOG_UPDATE:
214                 cur.bv().updateDialog("index", params2string(params_));
215                 break;
216
217         default:
218                 InsetCollapsable::doDispatch(cur, cmd);
219                 break;
220         }
221 }
222
223
224 bool InsetIndex::getStatus(Cursor & cur, FuncRequest const & cmd,
225                 FuncStatus & flag) const
226 {
227         switch (cmd.action) {
228
229         case LFUN_INSET_MODIFY:
230                 if (cmd.getArg(0) == "changetype") {
231                         docstring const newtype = from_utf8(cmd.getArg(1));
232                         Buffer const & realbuffer = *buffer().masterBuffer();
233                         IndicesList const & indiceslist = realbuffer.params().indiceslist();
234                         Index const * index = indiceslist.findShortcut(newtype);
235                         flag.setEnabled(index != 0);
236                         flag.setOnOff(
237                                 from_utf8(cmd.getArg(1)) == params_.index);
238                         return true;
239                 }
240                 flag.setEnabled(true);
241                 return true;
242
243         case LFUN_INSET_DIALOG_UPDATE: {
244                 Buffer const & realbuffer = *buffer().masterBuffer();
245                 flag.setEnabled(realbuffer.params().use_indices);
246                 return true;
247         }
248
249         default:
250                 return InsetCollapsable::getStatus(cur, cmd, flag);
251         }
252 }
253
254
255 ColorCode InsetIndex::labelColor() const
256 {
257         if (params_.index.empty() || params_.index == from_ascii("idx"))
258                 return InsetCollapsable::labelColor();
259         // FIXME UNICODE
260         ColorCode c = lcolor.getFromLyXName(to_utf8(params_.index));
261         if (c == Color_none)
262                 c = InsetCollapsable::labelColor();
263         return c;
264 }
265
266
267 docstring InsetIndex::toolTip(BufferView const &, int, int) const
268 {
269         docstring tip = _("Index Entry");
270         if (buffer().params().use_indices && !params_.index.empty()) {
271                 Buffer const & realbuffer = *buffer().masterBuffer();
272                 IndicesList const & indiceslist = realbuffer.params().indiceslist();
273                 tip += " (";
274                 Index const * index = indiceslist.findShortcut(params_.index);
275                 if (!index)
276                         tip += _("unknown type!");
277                 else
278                         tip += index->index();
279                 tip += ")";
280         }
281         tip += ": ";
282         OutputParams rp(&buffer().params().encoding());
283         odocstringstream ods;
284         InsetText::plaintext(ods, rp);
285         tip += ods.str();
286         return wrapParas(tip);
287 }
288
289
290 docstring const InsetIndex::buttonLabel(BufferView const & bv) const
291 {
292         InsetLayout const & il = getLayout();
293         docstring label = translateIfPossible(il.labelstring());
294
295         if (buffer().params().use_indices && !params_.index.empty()) {
296                 Buffer const & realbuffer = *buffer().masterBuffer();
297                 IndicesList const & indiceslist = realbuffer.params().indiceslist();
298                 label += " (";
299                 Index const * index = indiceslist.findShortcut(params_.index);
300                 if (!index)
301                         label += _("unknown type!");
302                 else
303                         label += index->index();
304                 label += ")";
305         }
306
307         if (!il.contentaslabel() || geometry(bv) != ButtonOnly)
308                 return label;
309         return getNewLabel(label);
310 }
311
312
313 void InsetIndex::write(ostream & os) const
314 {
315         os << to_utf8(name());
316         params_.write(os);
317         InsetCollapsable::write(os);
318 }
319
320
321 void InsetIndex::read(Lexer & lex)
322 {
323         params_.read(lex);
324         InsetCollapsable::read(lex);
325 }
326
327
328 string InsetIndex::params2string(InsetIndexParams const & params)
329 {
330         ostringstream data;
331         data << "index";
332         params.write(data);
333         return data.str();
334 }
335
336
337 void InsetIndex::string2params(string const & in, InsetIndexParams & params)
338 {
339         params = InsetIndexParams();
340         if (in.empty())
341                 return;
342
343         istringstream data(in);
344         Lexer lex;
345         lex.setStream(data);
346         lex.setContext("InsetIndex::string2params");
347         lex >> "index";
348         params.read(lex);
349 }
350
351
352 void InsetIndex::addToToc(DocIterator const & cpit)
353 {
354         DocIterator pit = cpit;
355         pit.push_back(CursorSlice(*this));
356         docstring const item = text().asString(0, 1, AS_STR_LABEL | AS_STR_INSETS);
357         buffer().tocBackend().toc("index").push_back(TocItem(pit, 0, item));
358         // Proceed with the rest of the inset.
359         InsetCollapsable::addToToc(cpit);
360 }
361
362
363 void InsetIndex::validate(LaTeXFeatures & features) const
364 {
365         if (buffer().masterBuffer()->params().use_indices
366             && !params_.index.empty()
367             && params_.index != "idx")
368                 features.require("splitidx");
369 }
370
371
372 docstring InsetIndex::contextMenu(BufferView const &, int, int) const
373 {
374         return from_ascii("context-index");
375 }
376
377
378 bool InsetIndex::hasSettings() const
379 {
380         return buffer().masterBuffer()->params().use_indices;
381 }
382
383
384
385
386 /////////////////////////////////////////////////////////////////////
387 //
388 // InsetIndexParams
389 //
390 ///////////////////////////////////////////////////////////////////////
391
392
393 void InsetIndexParams::write(ostream & os) const
394 {
395         os << ' ';
396         if (!index.empty())
397                 os << to_utf8(index);
398         else
399                 os << "idx";
400         os << '\n';
401 }
402
403
404 void InsetIndexParams::read(Lexer & lex)
405 {
406         if (lex.eatLine())
407                 index = lex.getDocString();
408         else
409                 index = from_ascii("idx");
410 }
411
412
413 /////////////////////////////////////////////////////////////////////
414 //
415 // InsetPrintIndex
416 //
417 ///////////////////////////////////////////////////////////////////////
418
419 InsetPrintIndex::InsetPrintIndex(Buffer * buf, InsetCommandParams const & p)
420         : InsetCommand(buf, p, "index_print")
421 {}
422
423
424 ParamInfo const & InsetPrintIndex::findInfo(string const & /* cmdName */)
425 {
426         static ParamInfo param_info_;
427         if (param_info_.empty()) {
428                 param_info_.add("type", ParamInfo::LATEX_OPTIONAL);
429                 param_info_.add("name", ParamInfo::LATEX_REQUIRED);
430         }
431         return param_info_;
432 }
433
434
435 docstring InsetPrintIndex::screenLabel() const
436 {
437         bool const printall = suffixIs(getCmdName(), '*');
438         bool const multind = buffer().masterBuffer()->params().use_indices;
439         if ((!multind
440              && getParam("type") == from_ascii("idx"))
441             || (getParam("type").empty() && !printall))
442                 return _("Index");
443         Buffer const & realbuffer = *buffer().masterBuffer();
444         IndicesList const & indiceslist = realbuffer.params().indiceslist();
445         Index const * index = indiceslist.findShortcut(getParam("type"));
446         if (!index && !printall)
447                 return _("Unknown index type!");
448         docstring res = printall ? _("All indices") : index->index();
449         if (!multind)
450                 res += " (" + _("non-active") + ")";
451         else if (contains(getCmdName(), "printsubindex"))
452                 res += " (" + _("subindex") + ")";
453         return res;
454 }
455
456
457 bool InsetPrintIndex::isCompatibleCommand(string const & s)
458 {
459         return s == "printindex" || s == "printsubindex"
460                 || s == "printindex*" || s == "printsubindex*";
461 }
462
463
464 void InsetPrintIndex::doDispatch(Cursor & cur, FuncRequest & cmd)
465 {
466         switch (cmd.action) {
467
468         case LFUN_INSET_MODIFY: {
469                 if (cmd.argument() == from_ascii("toggle-subindex")) {
470                         string cmd = getCmdName();
471                         if (contains(cmd, "printindex"))
472                                 cmd = subst(cmd, "printindex", "printsubindex");
473                         else
474                                 cmd = subst(cmd, "printsubindex", "printindex");
475                         setCmdName(cmd);
476                         break;
477                 } else if (cmd.argument() == from_ascii("check-printindex*")) {
478                         string cmd = getCmdName();
479                         if (suffixIs(cmd, '*'))
480                                 break;
481                         cmd += '*';
482                         setParam("type", docstring());
483                         setCmdName(cmd);
484                         break;
485                 }
486                 InsetCommandParams p(INDEX_PRINT_CODE);
487                 // FIXME UNICODE
488                 InsetCommand::string2params("index_print",
489                         to_utf8(cmd.argument()), p);
490                 if (p.getCmdName().empty()) {
491                         cur.noUpdate();
492                         break;
493                 }
494                 setParams(p);
495                 break;
496         }
497
498         default:
499                 InsetCommand::doDispatch(cur, cmd);
500                 break;
501         }
502 }
503
504
505 bool InsetPrintIndex::getStatus(Cursor & cur, FuncRequest const & cmd,
506         FuncStatus & status) const
507 {
508         switch (cmd.action) {
509
510         case LFUN_INSET_MODIFY: {
511                 if (cmd.argument() == from_ascii("toggle-subindex")) {
512                         status.setEnabled(buffer().masterBuffer()->params().use_indices);
513                         status.setOnOff(contains(getCmdName(), "printsubindex"));
514                         return true;
515                 } else if (cmd.argument() == from_ascii("check-printindex*")) {
516                         status.setEnabled(buffer().masterBuffer()->params().use_indices);
517                         status.setOnOff(suffixIs(getCmdName(), '*'));
518                         return true;
519                 } if (cmd.getArg(0) == "index_print"
520                     && cmd.getArg(1) == "CommandInset") {
521                         InsetCommandParams p(INDEX_PRINT_CODE);
522                         InsetCommand::string2params("index_print",
523                                 to_utf8(cmd.argument()), p);
524                         if (suffixIs(p.getCmdName(), '*')) {
525                                 status.setEnabled(true);
526                                 status.setOnOff(false);
527                                 return true;
528                         }
529                         Buffer const & realbuffer = *buffer().masterBuffer();
530                         IndicesList const & indiceslist =
531                                 realbuffer.params().indiceslist();
532                         Index const * index = indiceslist.findShortcut(p["type"]);
533                         status.setEnabled(index != 0);
534                         status.setOnOff(p["type"] == getParam("type"));
535                         return true;
536                 } else
537                         return InsetCommand::getStatus(cur, cmd, status);
538         }
539         
540         case LFUN_INSET_DIALOG_UPDATE: {
541                 status.setEnabled(buffer().masterBuffer()->params().use_indices);
542                 return true;
543         }
544
545         default:
546                 return InsetCommand::getStatus(cur, cmd, status);
547         }
548 }
549
550
551 int InsetPrintIndex::latex(odocstream & os, OutputParams const &) const
552 {
553         if (!buffer().masterBuffer()->params().use_indices) {
554                 if (getParam("type") == from_ascii("idx"))
555                         os << "\\printindex{}";
556                 return 0;
557         }
558         os << getCommand();
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