]> git.lyx.org Git - lyx.git/blob - src/insets/InsetIndex.cpp
Revert "Do not crash is release mode if we stumble across an unrealized font."
[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 "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 "texstream.h"
32 #include "TextClass.h"
33 #include "TocBackend.h"
34
35 #include "support/debug.h"
36 #include "support/docstream.h"
37 #include "support/gettext.h"
38 #include "support/lstrings.h"
39
40 #include "frontends/alert.h"
41
42 #include <algorithm>
43 #include <ostream>
44
45 using namespace std;
46 using namespace lyx::support;
47
48 namespace lyx {
49
50 /////////////////////////////////////////////////////////////////////
51 //
52 // InsetIndex
53 //
54 ///////////////////////////////////////////////////////////////////////
55
56
57 InsetIndex::InsetIndex(Buffer * buf, InsetIndexParams const & params)
58         : InsetCollapsable(buf), params_(params)
59 {}
60
61
62 void InsetIndex::latex(otexstream & os, OutputParams const & runparams_in) const
63 {
64         OutputParams runparams(runparams_in);
65         runparams.inIndexEntry = true;
66
67         if (buffer().masterBuffer()->params().use_indices && !params_.index.empty()
68             && params_.index != "idx") {
69                 os << "\\sindex[";
70                 os << escape(params_.index);
71                 os << "]{";
72         } else {
73                 os << "\\index";
74                 os << '{';
75         }
76
77         // get contents of InsetText as LaTeX and plaintext
78         odocstringstream ourlatex;
79         otexstream ots(ourlatex);
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,
352                                                   UpdateType utype) const
353 {
354         DocIterator pit = cpit;
355         pit.push_back(CursorSlice(const_cast<InsetIndex &>(*this)));
356         docstring str;
357         string type = "index";
358         if (buffer().masterBuffer()->params().use_indices)
359                 type += ":" + to_utf8(params_.index);
360         // this is unlikely to be terribly long
361         text().forOutliner(str, INT_MAX);
362         buffer().tocBackend().toc(type)->push_back(TocItem(pit, 0, str, output_active));
363         // Proceed with the rest of the inset.
364         InsetCollapsable::addToToc(cpit, output_active, utype);
365 }
366
367
368 void InsetIndex::validate(LaTeXFeatures & features) const
369 {
370         if (buffer().masterBuffer()->params().use_indices
371             && !params_.index.empty()
372             && params_.index != "idx")
373                 features.require("splitidx");
374         InsetCollapsable::validate(features);
375 }
376
377
378 string InsetIndex::contextMenuName() const
379 {
380         return "context-index";
381 }
382
383
384 bool InsetIndex::hasSettings() const
385 {
386         return buffer().masterBuffer()->params().use_indices;
387 }
388
389
390
391
392 /////////////////////////////////////////////////////////////////////
393 //
394 // InsetIndexParams
395 //
396 ///////////////////////////////////////////////////////////////////////
397
398
399 void InsetIndexParams::write(ostream & os) const
400 {
401         os << ' ';
402         if (!index.empty())
403                 os << to_utf8(index);
404         else
405                 os << "idx";
406         os << '\n';
407 }
408
409
410 void InsetIndexParams::read(Lexer & lex)
411 {
412         if (lex.eatLine())
413                 index = lex.getDocString();
414         else
415                 index = from_ascii("idx");
416 }
417
418
419 /////////////////////////////////////////////////////////////////////
420 //
421 // InsetPrintIndex
422 //
423 ///////////////////////////////////////////////////////////////////////
424
425 InsetPrintIndex::InsetPrintIndex(Buffer * buf, InsetCommandParams const & p)
426         : InsetCommand(buf, p)
427 {}
428
429
430 ParamInfo const & InsetPrintIndex::findInfo(string const & /* cmdName */)
431 {
432         static ParamInfo param_info_;
433         if (param_info_.empty()) {
434                 param_info_.add("type", ParamInfo::LATEX_OPTIONAL,
435                                 ParamInfo::HANDLING_ESCAPE);
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                 cur.recordUndo();
503                 setParams(p);
504                 break;
505         }
506
507         default:
508                 InsetCommand::doDispatch(cur, cmd);
509                 break;
510         }
511 }
512
513
514 bool InsetPrintIndex::getStatus(Cursor & cur, FuncRequest const & cmd,
515         FuncStatus & status) const
516 {
517         switch (cmd.action()) {
518
519         case LFUN_INSET_MODIFY: {
520                 if (cmd.argument() == from_ascii("toggle-subindex")) {
521                         status.setEnabled(buffer().masterBuffer()->params().use_indices);
522                         status.setOnOff(contains(getCmdName(), "printsubindex"));
523                         return true;
524                 } else if (cmd.argument() == from_ascii("check-printindex*")) {
525                         status.setEnabled(buffer().masterBuffer()->params().use_indices);
526                         status.setOnOff(suffixIs(getCmdName(), '*'));
527                         return true;
528                 } if (cmd.getArg(0) == "index_print"
529                     && cmd.getArg(1) == "CommandInset") {
530                         InsetCommandParams p(INDEX_PRINT_CODE);
531                         InsetCommand::string2params(to_utf8(cmd.argument()), p);
532                         if (suffixIs(p.getCmdName(), '*')) {
533                                 status.setEnabled(true);
534                                 status.setOnOff(false);
535                                 return true;
536                         }
537                         Buffer const & realbuffer = *buffer().masterBuffer();
538                         IndicesList const & indiceslist =
539                                 realbuffer.params().indiceslist();
540                         Index const * index = indiceslist.findShortcut(p["type"]);
541                         status.setEnabled(index != 0);
542                         status.setOnOff(p["type"] == getParam("type"));
543                         return true;
544                 } else
545                         return InsetCommand::getStatus(cur, cmd, status);
546         }
547         
548         case LFUN_INSET_DIALOG_UPDATE: {
549                 status.setEnabled(buffer().masterBuffer()->params().use_indices);
550                 return true;
551         }
552
553         default:
554                 return InsetCommand::getStatus(cur, cmd, status);
555         }
556 }
557
558
559 void InsetPrintIndex::latex(otexstream & os, OutputParams const & runparams_in) const
560 {
561         if (!buffer().masterBuffer()->params().use_indices) {
562                 if (getParam("type") == from_ascii("idx"))
563                         os << "\\printindex{}";
564                 return;
565         }
566         OutputParams runparams = runparams_in;
567         os << getCommand(runparams);
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 string InsetPrintIndex::contextMenuName() const
580 {
581         return buffer().masterBuffer()->params().use_indices ?
582                 "context-indexprint" : string();
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         int comp = compare_no_case(lhs.main, rhs.main);
670         if (comp == 0)
671                 comp = compare_no_case(lhs.sub, rhs.sub);
672         if (comp == 0)
673                 comp = compare_no_case(lhs.subsub, rhs.subsub);
674         return (comp < 0);
675 }
676
677 } // anon namespace
678
679
680 docstring InsetPrintIndex::xhtml(XHTMLStream &, OutputParams const & op) const
681 {
682         BufferParams const & bp = buffer().masterBuffer()->params();
683
684         // we do not presently support multiple indices, so we refuse to print
685         // anything but the main index, so as not to generate multiple indices.
686         // NOTE Multiple index support would require some work. The reason
687         // is that the TOC does not know about multiple indices. Either it would
688         // need to be told about them (not a bad idea), or else the index entries
689         // would need to be collected differently, say, during validation.
690         if (bp.use_indices && getParam("type") != from_ascii("idx"))
691                 return docstring();
692         
693         shared_ptr<Toc const> toc = buffer().tocBackend().toc("index");
694         if (toc->empty())
695                 return docstring();
696
697         // Collect the index entries in a form we can use them.
698         Toc::const_iterator it = toc->begin();
699         Toc::const_iterator const en = toc->end();
700         vector<IndexEntry> entries;
701         for (; it != en; ++it)
702                 if (it->isOutput())
703                         entries.push_back(IndexEntry(it->str(), it->dit()));
704
705         if (entries.empty())
706                 // not very likely that all the index entries are in notes or
707                 // whatever, but....
708                 return docstring();
709
710         stable_sort(entries.begin(), entries.end());
711
712         Layout const & lay = bp.documentClass().htmlTOCLayout();
713         string const & tocclass = lay.defaultCSSClass();
714         string const tocattr = "class='index " + tocclass + "'";
715
716         // we'll use our own stream, because we are going to defer everything.
717         // that's how we deal with the fact that we're probably inside a standard
718         // paragraph, and we don't want to be.
719         odocstringstream ods;
720         XHTMLStream xs(ods);
721
722         xs << html::StartTag("div", tocattr);
723         xs << html::StartTag(lay.htmltag(), lay.htmlattr()) 
724                  << translateIfPossible(from_ascii("Index"),
725                                   op.local_font->language()->lang())
726                  << html::EndTag(lay.htmltag());
727         xs << html::StartTag("ul", "class='main'");
728         Font const dummy;
729
730         vector<IndexEntry>::const_iterator eit = entries.begin();
731         vector<IndexEntry>::const_iterator const een = entries.end();
732         // tracks whether we are already inside a main entry (1),
733         // a sub-entry (2), or a sub-sub-entry (3). see below for the
734         // details.
735         int level = 1;
736         // the last one we saw
737         IndexEntry last;
738         int entry_number = -1;
739         for (; eit != een; ++eit) {
740                 Paragraph const & par = eit->dit.innerParagraph();
741                 if (entry_number == -1 || !eit->equal(last)) {
742                         if (entry_number != -1) {
743                                 // not the first time through the loop, so
744                                 // close last entry or entries, depending.
745                                 if (level == 3) {
746                                         // close this sub-sub-entry
747                                         xs << html::EndTag("li") << html::CR();
748                                         // is this another sub-sub-entry within the same sub-entry?
749                                         if (!eit->same_sub(last)) {
750                                                 // close this level
751                                                 xs << html::EndTag("ul") << html::CR();
752                                                 level = 2;
753                                         }
754                                 }
755                                 // the point of the second test here is that we might get
756                                 // here two ways: (i) by falling through from above; (ii) because,
757                                 // though the sub-entry hasn't changed, the sub-sub-entry has,
758                                 // which means that it is the first sub-sub-entry within this
759                                 // sub-entry. In that case, we do not want to close anything.
760                                 if (level == 2 && !eit->same_sub(last)) {
761                                         // close sub-entry 
762                                         xs << html::EndTag("li") << html::CR();
763                                         // is this another sub-entry with the same main entry?
764                                         if (!eit->same_main(last)) {
765                                                 // close this level
766                                                 xs << html::EndTag("ul") << html::CR();
767                                                 level = 1;
768                                         }
769                                 }
770                                 // again, we can get here two ways: from above, or because we have
771                                 // found the first sub-entry. in the latter case, we do not want to
772                                 // close the entry.
773                                 if (level == 1 && !eit->same_main(last)) {
774                                         // close entry
775                                         xs << html::EndTag("li") << html::CR();
776                                 }
777                         }
778
779                         // we'll be starting new entries
780                         entry_number = 0;
781
782                         // We need to use our own stream, since we will have to
783                         // modify what we get back.
784                         odocstringstream ent;
785                         XHTMLStream entstream(ent);
786                         OutputParams ours = op;
787                         ours.for_toc = true;
788                         par.simpleLyXHTMLOnePar(buffer(), entstream, ours, dummy);
789         
790                         // these will contain XHTML versions of the main entry, etc
791                         // remember that everything will already have been escaped,
792                         // so we'll need to use NextRaw() during output.
793                         docstring main;
794                         docstring sub;
795                         docstring subsub;
796                         extractSubentries(ent.str(), main, sub, subsub);
797                         parseItem(main, true);
798                         parseItem(sub, true);
799                         parseItem(subsub, true);
800         
801                         if (level == 3) {
802                                 // another subsubentry
803                                 xs << html::StartTag("li", "class='subsubentry'") 
804                                    << XHTMLStream::ESCAPE_NONE << subsub;
805                         } else if (level == 2) {
806                                 // there are two ways we can be here: 
807                                 // (i) we can actually be inside a sub-entry already and be about
808                                 //     to output the first sub-sub-entry. in this case, our sub
809                                 //     and the last sub will be the same.
810                                 // (ii) we can just have closed a sub-entry, possibly after also
811                                 //     closing a list of sub-sub-entries. here our sub and the last
812                                 //     sub are different.
813                                 // only in the latter case do we need to output the new sub-entry.
814                                 // note that in this case, too, though, the sub-entry might already
815                                 // have a sub-sub-entry.
816                                 if (eit->sub != last.sub)
817                                         xs << html::StartTag("li", "class='subentry'") 
818                                            << XHTMLStream::ESCAPE_NONE << sub;
819                                 if (!subsub.empty()) {
820                                         // it's actually a subsubentry, so we need to start that list
821                                         xs << html::CR()
822                                            << html::StartTag("ul", "class='subsubentry'") 
823                                            << html::StartTag("li", "class='subsubentry'") 
824                                            << XHTMLStream::ESCAPE_NONE << subsub;
825                                         level = 3;
826                                 } 
827                         } else {
828                                 // there are also two ways we can be here: 
829                                 // (i) we can actually be inside an entry already and be about
830                                 //     to output the first sub-entry. in this case, our main
831                                 //     and the last main will be the same.
832                                 // (ii) we can just have closed an entry, possibly after also
833                                 //     closing a list of sub-entries. here our main and the last
834                                 //     main are different.
835                                 // only in the latter case do we need to output the new main entry.
836                                 // note that in this case, too, though, the main entry might already
837                                 // have a sub-entry, or even a sub-sub-entry.
838                                 if (eit->main != last.main)
839                                         xs << html::StartTag("li", "class='main'") << main;
840                                 if (!sub.empty()) {
841                                         // there's a sub-entry, too
842                                         xs << html::CR()
843                                            << html::StartTag("ul", "class='subentry'") 
844                                            << html::StartTag("li", "class='subentry'") 
845                                            << XHTMLStream::ESCAPE_NONE << sub;
846                                         level = 2;
847                                         if (!subsub.empty()) {
848                                                 // and a sub-sub-entry
849                                                 xs << html::CR()
850                                                    << html::StartTag("ul", "class='subsubentry'") 
851                                                    << html::StartTag("li", "class='subsubentry'") 
852                                                    << XHTMLStream::ESCAPE_NONE << subsub;
853                                                 level = 3;
854                                         }
855                                 } 
856                         }
857                 }
858                 // finally, then, we can output the index link itself
859                 string const parattr = "href='#" + par.magicLabel() + "'";
860                 xs << (entry_number == 0 ? ":" : ",");
861                 xs << " " << html::StartTag("a", parattr)
862                    << ++entry_number << html::EndTag("a");
863                 last = *eit;
864         }
865         // now we have to close all the open levels
866         while (level > 0) {
867                 xs << html::EndTag("li") << html::EndTag("ul") << html::CR();
868                 --level;
869         }
870         xs << html::EndTag("div") << html::CR();
871         return ods.str();
872 }
873
874 } // namespace lyx