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