]> git.lyx.org Git - lyx.git/blob - src/insets/InsetIndex.cpp
72f18feef802cf1b208c9364a6ca85bac507ea49
[lyx.git] / src / insets / InsetIndex.cpp
1 /**
2  * \file InsetIndex.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author Jürgen Spitzmüller
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11 #include <config.h>
12
13 #include "InsetIndex.h"
14
15 #include "Buffer.h"
16 #include "BufferParams.h"
17 #include "BufferView.h"
18 #include "ColorSet.h"
19 #include "Cursor.h"
20 #include "DispatchResult.h"
21 #include "Encoding.h"
22 #include "FuncRequest.h"
23 #include "FuncStatus.h"
24 #include "IndicesList.h"
25 #include "LaTeXFeatures.h"
26 #include "Lexer.h"
27 #include "output_latex.h"
28 #include "output_xhtml.h"
29 #include "sgml.h"
30 #include "TextClass.h"
31 #include "TocBackend.h"
32
33 #include "support/debug.h"
34 #include "support/docstream.h"
35 #include "support/gettext.h"
36 #include "support/lstrings.h"
37
38 #include "frontends/alert.h"
39
40 #include <ostream>
41 #include <algorithm>
42
43 using namespace std;
44 using namespace lyx::support;
45
46 namespace lyx {
47
48 /////////////////////////////////////////////////////////////////////
49 //
50 // InsetIndex
51 //
52 ///////////////////////////////////////////////////////////////////////
53
54
55 InsetIndex::InsetIndex(Buffer * buf, InsetIndexParams const & params)
56         : InsetCollapsable(buf), params_(params)
57 {}
58
59
60 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 << escape(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                         pair<docstring, docstring> spart_latexed =
138                                 runparams.encoding->latexString(spart, runparams.dryrun);
139                         if (!spart_latexed.second.empty())
140                                         LYXERR0("Uncodable character in index entry. Sorting might be wrong!");
141                         if (spart != spart_latexed.first && !runparams.dryrun) {
142                                 // FIXME: warning should be passed to the error dialog
143                                 frontend::Alert::warning(_("Index sorting failed"),
144                                 bformat(_("LyX's automatic index sorting algorithm faced\n"
145                                   "problems with the entry '%1$s'.\n"
146                                   "Please specify the sorting of this entry manually, as\n"
147                                   "explained in the User Guide."), spart));
148                         }
149                         // remove remaining \'s for the sorting part
150                         docstring const ppart =
151                                 subst(spart_latexed.first, from_ascii("\\"), docstring());
152                         os << ppart;
153                         os << '@';
154                 }
155                 docstring const tpart = *it;
156                 os << tpart;
157                 if (it2 < levels_plain.end())
158                         ++it2;
159         }
160         // write the bit that followed "|"
161         if (!cmd.empty()) {
162                 os << "|" << cmd;
163         }
164         os << '}';
165 }
166
167
168 int InsetIndex::docbook(odocstream & os, OutputParams const & runparams) const
169 {
170         os << "<indexterm><primary>";
171         int const i = InsetText::docbook(os, runparams);
172         os << "</primary></indexterm>";
173         return i;
174 }
175
176
177 docstring InsetIndex::xhtml(XHTMLStream & xs, OutputParams const &) const
178 {
179         // we just print an anchor, taking the paragraph ID from 
180         // our own interior paragraph, which doesn't get printed
181         std::string const magic = paragraphs().front().magicLabel();
182         std::string const attr = "id='" + magic + "'";
183         xs << html::CompTag("a", attr);
184         return docstring();
185 }
186
187
188 bool InsetIndex::showInsetDialog(BufferView * bv) const
189 {
190         bv->showDialog("index", params2string(params_),
191                         const_cast<InsetIndex *>(this));
192         return true;
193 }
194
195
196 void InsetIndex::doDispatch(Cursor & cur, FuncRequest & cmd)
197 {
198         switch (cmd.action()) {
199
200         case LFUN_INSET_MODIFY: {
201                 if (cmd.getArg(0) == "changetype") {
202                         cur.recordUndoInset(ATOMIC_UNDO, this);
203                         params_.index = from_utf8(cmd.getArg(1));
204                         break;
205                 }
206                 InsetIndexParams params;
207                 InsetIndex::string2params(to_utf8(cmd.argument()), params);
208                 cur.recordUndoInset(ATOMIC_UNDO, this);
209                 params_.index = params.index;
210                 // what we really want here is a TOC update, but that means
211                 // a full buffer update
212                 cur.forceBufferUpdate();
213                 break;
214         }
215
216         case LFUN_INSET_DIALOG_UPDATE:
217                 cur.bv().updateDialog("index", params2string(params_));
218                 break;
219
220         default:
221                 InsetCollapsable::doDispatch(cur, cmd);
222                 break;
223         }
224 }
225
226
227 bool InsetIndex::getStatus(Cursor & cur, FuncRequest const & cmd,
228                 FuncStatus & flag) const
229 {
230         switch (cmd.action()) {
231
232         case LFUN_INSET_MODIFY:
233                 if (cmd.getArg(0) == "changetype") {
234                         docstring const newtype = from_utf8(cmd.getArg(1));
235                         Buffer const & realbuffer = *buffer().masterBuffer();
236                         IndicesList const & indiceslist = realbuffer.params().indiceslist();
237                         Index const * index = indiceslist.findShortcut(newtype);
238                         flag.setEnabled(index != 0);
239                         flag.setOnOff(
240                                 from_utf8(cmd.getArg(1)) == params_.index);
241                         return true;
242                 }
243                 return InsetCollapsable::getStatus(cur, cmd, flag);
244
245         case LFUN_INSET_DIALOG_UPDATE: {
246                 Buffer const & realbuffer = *buffer().masterBuffer();
247                 flag.setEnabled(realbuffer.params().use_indices);
248                 return true;
249         }
250
251         default:
252                 return InsetCollapsable::getStatus(cur, cmd, flag);
253         }
254 }
255
256
257 ColorCode InsetIndex::labelColor() const
258 {
259         if (params_.index.empty() || params_.index == from_ascii("idx"))
260                 return InsetCollapsable::labelColor();
261         // FIXME UNICODE
262         ColorCode c = lcolor.getFromLyXName(to_utf8(params_.index));
263         if (c == Color_none)
264                 c = InsetCollapsable::labelColor();
265         return c;
266 }
267
268
269 docstring InsetIndex::toolTip(BufferView const &, int, int) const
270 {
271         docstring tip = _("Index Entry");
272         if (buffer().params().use_indices && !params_.index.empty()) {
273                 Buffer const & realbuffer = *buffer().masterBuffer();
274                 IndicesList const & indiceslist = realbuffer.params().indiceslist();
275                 tip += " (";
276                 Index const * index = indiceslist.findShortcut(params_.index);
277                 if (!index)
278                         tip += _("unknown type!");
279                 else
280                         tip += index->index();
281                 tip += ")";
282         }
283         tip += ": ";
284         return toolTipText(tip);
285 }
286
287
288 docstring const InsetIndex::buttonLabel(BufferView const & bv) const
289 {
290         InsetLayout const & il = getLayout();
291         docstring label = translateIfPossible(il.labelstring());
292
293         if (buffer().params().use_indices && !params_.index.empty()) {
294                 Buffer const & realbuffer = *buffer().masterBuffer();
295                 IndicesList const & indiceslist = realbuffer.params().indiceslist();
296                 label += " (";
297                 Index const * index = indiceslist.findShortcut(params_.index);
298                 if (!index)
299                         label += _("unknown type!");
300                 else
301                         label += index->index();
302                 label += ")";
303         }
304
305         if (!il.contentaslabel() || geometry(bv) != ButtonOnly)
306                 return label;
307         return getNewLabel(label);
308 }
309
310
311 void InsetIndex::write(ostream & os) const
312 {
313         os << to_utf8(layoutName());
314         params_.write(os);
315         InsetCollapsable::write(os);
316 }
317
318
319 void InsetIndex::read(Lexer & lex)
320 {
321         params_.read(lex);
322         InsetCollapsable::read(lex);
323 }
324
325
326 string InsetIndex::params2string(InsetIndexParams const & params)
327 {
328         ostringstream data;
329         data << "index";
330         params.write(data);
331         return data.str();
332 }
333
334
335 void InsetIndex::string2params(string const & in, InsetIndexParams & params)
336 {
337         params = InsetIndexParams();
338         if (in.empty())
339                 return;
340
341         istringstream data(in);
342         Lexer lex;
343         lex.setStream(data);
344         lex.setContext("InsetIndex::string2params");
345         lex >> "index";
346         params.read(lex);
347 }
348
349
350 void InsetIndex::addToToc(DocIterator const & cpit) const
351 {
352         DocIterator pit = cpit;
353         pit.push_back(CursorSlice(const_cast<InsetIndex &>(*this)));
354         docstring str;
355         text().forToc(str, 0);
356         buffer().tocBackend().toc("index").push_back(TocItem(pit, 0, str));
357         // Proceed with the rest of the inset.
358         InsetCollapsable::addToToc(cpit);
359 }
360
361
362 void InsetIndex::validate(LaTeXFeatures & features) const
363 {
364         if (buffer().masterBuffer()->params().use_indices
365             && !params_.index.empty()
366             && params_.index != "idx")
367                 features.require("splitidx");
368         InsetCollapsable::validate(features);
369 }
370
371
372 string InsetIndex::contextMenuName() const
373 {
374         return "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)
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                         ParamInfo::HANDLING_ESCAPE);
430                 param_info_.add("name", ParamInfo::LATEX_REQUIRED);
431         }
432         return param_info_;
433 }
434
435
436 docstring InsetPrintIndex::screenLabel() const
437 {
438         bool const printall = suffixIs(getCmdName(), '*');
439         bool const multind = buffer().masterBuffer()->params().use_indices;
440         if ((!multind
441              && getParam("type") == from_ascii("idx"))
442             || (getParam("type").empty() && !printall))
443                 return _("Index");
444         Buffer const & realbuffer = *buffer().masterBuffer();
445         IndicesList const & indiceslist = realbuffer.params().indiceslist();
446         Index const * index = indiceslist.findShortcut(getParam("type"));
447         if (!index && !printall)
448                 return _("Unknown index type!");
449         docstring res = printall ? _("All indexes") : index->index();
450         if (!multind)
451                 res += " (" + _("non-active") + ")";
452         else if (contains(getCmdName(), "printsubindex"))
453                 res += " (" + _("subindex") + ")";
454         return res;
455 }
456
457
458 bool InsetPrintIndex::isCompatibleCommand(string const & s)
459 {
460         return s == "printindex" || s == "printsubindex"
461                 || s == "printindex*" || s == "printsubindex*";
462 }
463
464
465 void InsetPrintIndex::doDispatch(Cursor & cur, FuncRequest & cmd)
466 {
467         switch (cmd.action()) {
468
469         case LFUN_INSET_MODIFY: {
470                 if (cmd.argument() == from_ascii("toggle-subindex")) {
471                         string cmd = getCmdName();
472                         if (contains(cmd, "printindex"))
473                                 cmd = subst(cmd, "printindex", "printsubindex");
474                         else
475                                 cmd = subst(cmd, "printsubindex", "printindex");
476                         cur.recordUndo();
477                         setCmdName(cmd);
478                         break;
479                 } else if (cmd.argument() == from_ascii("check-printindex*")) {
480                         string cmd = getCmdName();
481                         if (suffixIs(cmd, '*'))
482                                 break;
483                         cmd += '*';
484                         cur.recordUndo();
485                         setParam("type", docstring());
486                         setCmdName(cmd);
487                         break;
488                 }
489                 InsetCommandParams p(INDEX_PRINT_CODE);
490                 // FIXME UNICODE
491                 InsetCommand::string2params(to_utf8(cmd.argument()), p);
492                 if (p.getCmdName().empty()) {
493                         cur.noScreenUpdate();
494                         break;
495                 }
496                 cur.recordUndo();
497                 setParams(p);
498                 break;
499         }
500
501         default:
502                 InsetCommand::doDispatch(cur, cmd);
503                 break;
504         }
505 }
506
507
508 bool InsetPrintIndex::getStatus(Cursor & cur, FuncRequest const & cmd,
509         FuncStatus & status) const
510 {
511         switch (cmd.action()) {
512
513         case LFUN_INSET_MODIFY: {
514                 if (cmd.argument() == from_ascii("toggle-subindex")) {
515                         status.setEnabled(buffer().masterBuffer()->params().use_indices);
516                         status.setOnOff(contains(getCmdName(), "printsubindex"));
517                         return true;
518                 } else if (cmd.argument() == from_ascii("check-printindex*")) {
519                         status.setEnabled(buffer().masterBuffer()->params().use_indices);
520                         status.setOnOff(suffixIs(getCmdName(), '*'));
521                         return true;
522                 } if (cmd.getArg(0) == "index_print"
523                     && cmd.getArg(1) == "CommandInset") {
524                         InsetCommandParams p(INDEX_PRINT_CODE);
525                         InsetCommand::string2params(to_utf8(cmd.argument()), p);
526                         if (suffixIs(p.getCmdName(), '*')) {
527                                 status.setEnabled(true);
528                                 status.setOnOff(false);
529                                 return true;
530                         }
531                         Buffer const & realbuffer = *buffer().masterBuffer();
532                         IndicesList const & indiceslist =
533                                 realbuffer.params().indiceslist();
534                         Index const * index = indiceslist.findShortcut(p["type"]);
535                         status.setEnabled(index != 0);
536                         status.setOnOff(p["type"] == getParam("type"));
537                         return true;
538                 } else
539                         return InsetCommand::getStatus(cur, cmd, status);
540         }
541         
542         case LFUN_INSET_DIALOG_UPDATE: {
543                 status.setEnabled(buffer().masterBuffer()->params().use_indices);
544                 return true;
545         }
546
547         default:
548                 return InsetCommand::getStatus(cur, cmd, status);
549         }
550 }
551
552
553 void InsetPrintIndex::latex(otexstream & os, OutputParams const & runparams_in) const
554 {
555         if (!buffer().masterBuffer()->params().use_indices) {
556                 if (getParam("type") == from_ascii("idx"))
557                         os << "\\printindex{}";
558                 return;
559         }
560         OutputParams runparams = runparams_in;
561         os << getCommand(runparams);
562 }
563
564
565 void InsetPrintIndex::validate(LaTeXFeatures & features) const
566 {
567         features.require("makeidx");
568         if (buffer().masterBuffer()->params().use_indices)
569                 features.require("splitidx");
570 }
571
572
573 string InsetPrintIndex::contextMenuName() const
574 {
575         return buffer().masterBuffer()->params().use_indices ?
576                 "context-indexprint" : string();
577 }
578
579
580 bool InsetPrintIndex::hasSettings() const
581 {
582         return buffer().masterBuffer()->params().use_indices;
583 }
584
585
586 namespace {
587
588 void parseItem(docstring & s, bool for_output)
589 {
590         // this does not yet check for escaped things
591         size_type loc = s.find(from_ascii("@"));
592         if (loc != string::npos) {
593                 if (for_output)
594                         s.erase(0, loc + 1);
595                 else
596                         s.erase(loc);
597         }
598         loc = s.find(from_ascii("|"));
599         if (loc != string::npos)
600                 s.erase(loc);
601 }
602
603         
604 void extractSubentries(docstring const & entry, docstring & main,
605                 docstring & sub1, docstring & sub2)
606 {
607         if (entry.empty())
608                 return;
609         size_type const loc = entry.find(from_ascii(" ! "));
610         if (loc == string::npos)
611                 main = entry;
612         else {
613                 main = trim(entry.substr(0, loc));
614                 size_t const locend = loc + 3;
615                 size_type const loc2 = entry.find(from_ascii(" ! "), locend);
616                 if (loc2 == string::npos) {
617                         sub1 = trim(entry.substr(locend));
618                 } else {
619                         sub1 = trim(entry.substr(locend, loc2 - locend));
620                         sub2 = trim(entry.substr(loc2 + 3));
621                 }
622         }
623 }
624
625
626 struct IndexEntry
627 {
628         IndexEntry() 
629         {}
630         
631         IndexEntry(docstring const & s, DocIterator const & d) 
632                         : dit(d)
633         {
634                 extractSubentries(s, main, sub, subsub);
635                 parseItem(main, false);
636                 parseItem(sub, false);
637                 parseItem(subsub, false);
638         }
639         
640         bool equal(IndexEntry const & rhs) const
641         {
642                 return main == rhs.main && sub == rhs.sub && subsub == rhs.subsub;
643         }
644         
645         bool same_sub(IndexEntry const & rhs) const
646         {
647                 return main == rhs.main && sub == rhs.sub;
648         }
649         
650         bool same_main(IndexEntry const & rhs) const
651         {
652                 return main == rhs.main;
653         }
654         
655         docstring main;
656         docstring sub;
657         docstring subsub;
658         DocIterator dit;
659 };
660
661 bool operator<(IndexEntry const & lhs, IndexEntry const & rhs)
662 {
663         int comp = compare_no_case(lhs.main, rhs.main);
664         if (comp == 0)
665                 comp = compare_no_case(lhs.sub, rhs.sub);
666         if (comp == 0)
667                 comp = compare_no_case(lhs.subsub, rhs.subsub);
668         return (comp < 0);
669 }
670
671 } // anon namespace
672
673
674 docstring InsetPrintIndex::xhtml(XHTMLStream &, OutputParams const & op) const
675 {
676         BufferParams const & bp = buffer().masterBuffer()->params();
677
678         // we do not presently support multiple indices, so we refuse to print
679         // anything but the main index, so as not to generate multiple indices.
680         // NOTE Multiple index support would require some work. The reason
681         // is that the TOC does not know about multiple indices. Either it would
682         // need to be told about them (not a bad idea), or else the index entries
683         // would need to be collected differently, say, during validation.
684         if (bp.use_indices && getParam("type") != from_ascii("idx"))
685                 return docstring();
686         
687         Toc const & toc = buffer().tocBackend().toc("index");
688         if (toc.empty())
689                 return docstring();
690
691         // Collection the index entries in a form we can use them.
692         Toc::const_iterator it = toc.begin();
693         Toc::const_iterator const en = toc.end();
694         vector<IndexEntry> entries;
695         for (; it != en; ++it)
696                 entries.push_back(IndexEntry(it->str(), it->dit()));
697         stable_sort(entries.begin(), entries.end());
698
699         Layout const & lay = bp.documentClass().htmlTOCLayout();
700         string const & tocclass = lay.defaultCSSClass();
701         string const tocattr = "class='tochead " + tocclass + "'";
702
703         // we'll use our own stream, because we are going to defer everything.
704         // that's how we deal with the fact that we're probably inside a standard
705         // paragraph, and we don't want to be.
706         odocstringstream ods;
707         XHTMLStream xs(ods);
708
709         xs << html::StartTag("div", "class='index'");
710         xs << html::StartTag(lay.htmltag(), lay.htmlattr()) 
711                  << _("Index") 
712                  << html::EndTag(lay.htmltag());
713         xs << html::StartTag("ul", "class='main'");
714         Font const dummy;
715
716         vector<IndexEntry>::const_iterator eit = entries.begin();
717         vector<IndexEntry>::const_iterator const een = entries.end();
718         // tracks whether we are already inside a main entry (1),
719         // a sub-entry (2), or a sub-sub-entry (3). see below for the
720         // details.
721         int level = 1;
722         // the last one we saw
723         IndexEntry last;
724         int entry_number = -1;
725         for (; eit != een; ++eit) {
726                 Paragraph const & par = eit->dit.innerParagraph();
727                 if (entry_number == -1 || !eit->equal(last)) {
728                         if (entry_number != -1) {
729                                 // not the first time through the loop, so
730                                 // close last entry or entries, depending.
731                                 if (level == 3) {
732                                         // close this sub-sub-entry
733                                         xs << html::EndTag("li") << html::CR();
734                                         // is this another sub-sub-entry within the same sub-entry?
735                                         if (!eit->same_sub(last)) {
736                                                 // close this level
737                                                 xs << html::EndTag("ul") << html::CR();
738                                                 level = 2;
739                                         }
740                                 }
741                                 // the point of the second test here is that we might get
742                                 // here two ways: (i) by falling through from above; (ii) because,
743                                 // though the sub-entry hasn't changed, the sub-sub-entry has,
744                                 // which means that it is the first sub-sub-entry within this
745                                 // sub-entry. In that case, we do not want to close anything.
746                                 if (level == 2 && !eit->same_sub(last)) {
747                                         // close sub-entry 
748                                         xs << html::EndTag("li") << html::CR();
749                                         // is this another sub-entry with the same main entry?
750                                         if (!eit->same_main(last)) {
751                                                 // close this level
752                                                 xs << html::EndTag("ul") << html::CR();
753                                                 level = 1;
754                                         }
755                                 }
756                                 // again, we can get here two ways: from above, or because we have
757                                 // found the first sub-entry. in the latter case, we do not want to
758                                 // close the entry.
759                                 if (level == 1 && !eit->same_main(last)) {
760                                         // close entry
761                                         xs << html::EndTag("li") << html::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::ESCAPE_NONE << 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::ESCAPE_NONE << sub;
805                                 if (!subsub.empty()) {
806                                         // it's actually a subsubentry, so we need to start that list
807                                         xs << html::CR()
808                                            << html::StartTag("ul", "class='subsubentry'") 
809                                            << html::StartTag("li", "class='subsubentry'") 
810                                            << XHTMLStream::ESCAPE_NONE << 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 << html::CR()
829                                            << html::StartTag("ul", "class='subentry'") 
830                                            << html::StartTag("li", "class='subentry'") 
831                                            << XHTMLStream::ESCAPE_NONE << sub;
832                                         level = 2;
833                                         if (!subsub.empty()) {
834                                                 // and a sub-sub-entry
835                                                 xs << html::CR()
836                                                    << html::StartTag("ul", "class='subsubentry'") 
837                                                    << html::StartTag("li", "class='subsubentry'") 
838                                                    << XHTMLStream::ESCAPE_NONE << 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") << html::CR();
854                 --level;
855         }
856         xs << html::EndTag("div") << html::CR();
857         return ods.str();
858 }
859
860 } // namespace lyx