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