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