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