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