]> git.lyx.org Git - lyx.git/blob - src/insets/InsetIndex.cpp
InsetInfo: enable inset dissolve
[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 "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         : InsetCollapsible(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                 InsetCollapsible::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 InsetCollapsible::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 InsetCollapsible::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 InsetCollapsible::labelColor();
264         // FIXME UNICODE
265         ColorCode c = lcolor.getFromLyXName(to_utf8(params_.index));
266         if (c == Color_none)
267                 c = InsetCollapsible::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         InsetCollapsible::write(os);
319 }
320
321
322 void InsetIndex::read(Lexer & lex)
323 {
324         params_.read(lex);
325         InsetCollapsible::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         InsetCollapsible::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         InsetCollapsible::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_OPTIONAL,
441                                 ParamInfo::HANDLING_LATEXIFY);
442                 param_info_.add("literal", ParamInfo::LYX_INTERNAL);
443         }
444         return param_info_;
445 }
446
447
448 docstring InsetPrintIndex::screenLabel() const
449 {
450         bool const printall = suffixIs(getCmdName(), '*');
451         bool const multind = buffer().masterBuffer()->params().use_indices;
452         if ((!multind
453              && getParam("type") == from_ascii("idx"))
454             || (getParam("type").empty() && !printall))
455                 return _("Index");
456         Buffer const & realbuffer = *buffer().masterBuffer();
457         IndicesList const & indiceslist = realbuffer.params().indiceslist();
458         Index const * index = indiceslist.findShortcut(getParam("type"));
459         if (!index && !printall)
460                 return _("Unknown index type!");
461         docstring res = printall ? _("All indexes") : index->index();
462         if (!multind)
463                 res += " (" + _("non-active") + ")";
464         else if (contains(getCmdName(), "printsubindex"))
465                 res += " (" + _("subindex") + ")";
466         return res;
467 }
468
469
470 bool InsetPrintIndex::isCompatibleCommand(string const & s)
471 {
472         return s == "printindex" || s == "printsubindex"
473                 || s == "printindex*" || s == "printsubindex*";
474 }
475
476
477 void InsetPrintIndex::doDispatch(Cursor & cur, FuncRequest & cmd)
478 {
479         switch (cmd.action()) {
480
481         case LFUN_INSET_MODIFY: {
482                 if (cmd.argument() == from_ascii("toggle-subindex")) {
483                         string scmd = getCmdName();
484                         if (contains(scmd, "printindex"))
485                                 scmd = subst(scmd, "printindex", "printsubindex");
486                         else
487                                 scmd = subst(scmd, "printsubindex", "printindex");
488                         cur.recordUndo();
489                         setCmdName(scmd);
490                         break;
491                 } else if (cmd.argument() == from_ascii("check-printindex*")) {
492                         string scmd = getCmdName();
493                         if (suffixIs(scmd, '*'))
494                                 break;
495                         scmd += '*';
496                         cur.recordUndo();
497                         setParam("type", docstring());
498                         setCmdName(scmd);
499                         break;
500                 }
501                 InsetCommandParams p(INDEX_PRINT_CODE);
502                 // FIXME UNICODE
503                 InsetCommand::string2params(to_utf8(cmd.argument()), p);
504                 if (p.getCmdName().empty()) {
505                         cur.noScreenUpdate();
506                         break;
507                 }
508                 cur.recordUndo();
509                 setParams(p);
510                 break;
511         }
512
513         default:
514                 InsetCommand::doDispatch(cur, cmd);
515                 break;
516         }
517 }
518
519
520 bool InsetPrintIndex::getStatus(Cursor & cur, FuncRequest const & cmd,
521         FuncStatus & status) const
522 {
523         switch (cmd.action()) {
524
525         case LFUN_INSET_MODIFY: {
526                 if (cmd.argument() == from_ascii("toggle-subindex")) {
527                         status.setEnabled(buffer().masterBuffer()->params().use_indices);
528                         status.setOnOff(contains(getCmdName(), "printsubindex"));
529                         return true;
530                 } else if (cmd.argument() == from_ascii("check-printindex*")) {
531                         status.setEnabled(buffer().masterBuffer()->params().use_indices);
532                         status.setOnOff(suffixIs(getCmdName(), '*'));
533                         return true;
534                 } if (cmd.getArg(0) == "index_print"
535                     && cmd.getArg(1) == "CommandInset") {
536                         InsetCommandParams p(INDEX_PRINT_CODE);
537                         InsetCommand::string2params(to_utf8(cmd.argument()), p);
538                         if (suffixIs(p.getCmdName(), '*')) {
539                                 status.setEnabled(true);
540                                 status.setOnOff(false);
541                                 return true;
542                         }
543                         Buffer const & realbuffer = *buffer().masterBuffer();
544                         IndicesList const & indiceslist =
545                                 realbuffer.params().indiceslist();
546                         Index const * index = indiceslist.findShortcut(p["type"]);
547                         status.setEnabled(index != 0);
548                         status.setOnOff(p["type"] == getParam("type"));
549                         return true;
550                 } else
551                         return InsetCommand::getStatus(cur, cmd, status);
552         }
553
554         case LFUN_INSET_DIALOG_UPDATE: {
555                 status.setEnabled(buffer().masterBuffer()->params().use_indices);
556                 return true;
557         }
558
559         default:
560                 return InsetCommand::getStatus(cur, cmd, status);
561         }
562 }
563
564
565 void InsetPrintIndex::updateBuffer(ParIterator const &, UpdateType)
566 {
567         Index const * index =
568                 buffer().masterParams().indiceslist().findShortcut(getParam("type"));
569         if (index)
570                 setParam("name", index->index());
571 }
572
573
574 void InsetPrintIndex::latex(otexstream & os, OutputParams const & runparams_in) const
575 {
576         if (!buffer().masterBuffer()->params().use_indices) {
577                 if (getParam("type") == from_ascii("idx"))
578                         os << "\\printindex" << termcmd;
579                 return;
580         }
581         OutputParams runparams = runparams_in;
582         os << getCommand(runparams);
583 }
584
585
586 void InsetPrintIndex::validate(LaTeXFeatures & features) const
587 {
588         features.require("makeidx");
589         if (buffer().masterBuffer()->params().use_indices)
590                 features.require("splitidx");
591         InsetCommand::validate(features);
592 }
593
594
595 string InsetPrintIndex::contextMenuName() const
596 {
597         return buffer().masterBuffer()->params().use_indices ?
598                 "context-indexprint" : string();
599 }
600
601
602 bool InsetPrintIndex::hasSettings() const
603 {
604         return buffer().masterBuffer()->params().use_indices;
605 }
606
607
608 namespace {
609
610 void parseItem(docstring & s, bool for_output)
611 {
612         // this does not yet check for escaped things
613         size_type loc = s.find(from_ascii("@"));
614         if (loc != string::npos) {
615                 if (for_output)
616                         s.erase(0, loc + 1);
617                 else
618                         s.erase(loc);
619         }
620         loc = s.find(from_ascii("|"));
621         if (loc != string::npos)
622                 s.erase(loc);
623 }
624
625
626 void extractSubentries(docstring const & entry, docstring & main,
627                 docstring & sub1, docstring & sub2)
628 {
629         if (entry.empty())
630                 return;
631         size_type const loc = entry.find(from_ascii(" ! "));
632         if (loc == string::npos)
633                 main = entry;
634         else {
635                 main = trim(entry.substr(0, loc));
636                 size_t const locend = loc + 3;
637                 size_type const loc2 = entry.find(from_ascii(" ! "), locend);
638                 if (loc2 == string::npos) {
639                         sub1 = trim(entry.substr(locend));
640                 } else {
641                         sub1 = trim(entry.substr(locend, loc2 - locend));
642                         sub2 = trim(entry.substr(loc2 + 3));
643                 }
644         }
645 }
646
647
648 struct IndexEntry
649 {
650         IndexEntry()
651         {}
652
653         IndexEntry(docstring const & s, DocIterator const & d)
654                         : dit(d)
655         {
656                 extractSubentries(s, main, sub, subsub);
657                 parseItem(main, false);
658                 parseItem(sub, false);
659                 parseItem(subsub, false);
660         }
661
662         bool equal(IndexEntry const & rhs) const
663         {
664                 return main == rhs.main && sub == rhs.sub && subsub == rhs.subsub;
665         }
666
667         bool same_sub(IndexEntry const & rhs) const
668         {
669                 return main == rhs.main && sub == rhs.sub;
670         }
671
672         bool same_main(IndexEntry const & rhs) const
673         {
674                 return main == rhs.main;
675         }
676
677         docstring main;
678         docstring sub;
679         docstring subsub;
680         DocIterator dit;
681 };
682
683 bool operator<(IndexEntry const & lhs, IndexEntry const & rhs)
684 {
685         int comp = compare_no_case(lhs.main, rhs.main);
686         if (comp == 0)
687                 comp = compare_no_case(lhs.sub, rhs.sub);
688         if (comp == 0)
689                 comp = compare_no_case(lhs.subsub, rhs.subsub);
690         return (comp < 0);
691 }
692
693 } // namespace
694
695
696 docstring InsetPrintIndex::xhtml(XHTMLStream &, OutputParams const & op) const
697 {
698         BufferParams const & bp = buffer().masterBuffer()->params();
699
700         // we do not presently support multiple indices, so we refuse to print
701         // anything but the main index, so as not to generate multiple indices.
702         // NOTE Multiple index support would require some work. The reason
703         // is that the TOC does not know about multiple indices. Either it would
704         // need to be told about them (not a bad idea), or else the index entries
705         // would need to be collected differently, say, during validation.
706         if (bp.use_indices && getParam("type") != from_ascii("idx"))
707                 return docstring();
708
709         shared_ptr<Toc const> toc = buffer().tocBackend().toc("index");
710         if (toc->empty())
711                 return docstring();
712
713         // Collect the index entries in a form we can use them.
714         Toc::const_iterator it = toc->begin();
715         Toc::const_iterator const en = toc->end();
716         vector<IndexEntry> entries;
717         for (; it != en; ++it)
718                 if (it->isOutput())
719                         entries.push_back(IndexEntry(it->str(), it->dit()));
720
721         if (entries.empty())
722                 // not very likely that all the index entries are in notes or
723                 // whatever, but....
724                 return docstring();
725
726         stable_sort(entries.begin(), entries.end());
727
728         Layout const & lay = bp.documentClass().htmlTOCLayout();
729         string const & tocclass = lay.defaultCSSClass();
730         string const tocattr = "class='index " + tocclass + "'";
731
732         // we'll use our own stream, because we are going to defer everything.
733         // that's how we deal with the fact that we're probably inside a standard
734         // paragraph, and we don't want to be.
735         odocstringstream ods;
736         XHTMLStream xs(ods);
737
738         xs << html::StartTag("div", tocattr);
739         xs << html::StartTag(lay.htmltag(), lay.htmlattr())
740                  << translateIfPossible(from_ascii("Index"),
741                                   op.local_font->language()->lang())
742                  << html::EndTag(lay.htmltag());
743         xs << html::StartTag("ul", "class='main'");
744         Font const dummy;
745
746         vector<IndexEntry>::const_iterator eit = entries.begin();
747         vector<IndexEntry>::const_iterator const een = entries.end();
748         // tracks whether we are already inside a main entry (1),
749         // a sub-entry (2), or a sub-sub-entry (3). see below for the
750         // details.
751         int level = 1;
752         // the last one we saw
753         IndexEntry last;
754         int entry_number = -1;
755         for (; eit != een; ++eit) {
756                 Paragraph const & par = eit->dit.innerParagraph();
757                 if (entry_number == -1 || !eit->equal(last)) {
758                         if (entry_number != -1) {
759                                 // not the first time through the loop, so
760                                 // close last entry or entries, depending.
761                                 if (level == 3) {
762                                         // close this sub-sub-entry
763                                         xs << html::EndTag("li") << html::CR();
764                                         // is this another sub-sub-entry within the same sub-entry?
765                                         if (!eit->same_sub(last)) {
766                                                 // close this level
767                                                 xs << html::EndTag("ul") << html::CR();
768                                                 level = 2;
769                                         }
770                                 }
771                                 // the point of the second test here is that we might get
772                                 // here two ways: (i) by falling through from above; (ii) because,
773                                 // though the sub-entry hasn't changed, the sub-sub-entry has,
774                                 // which means that it is the first sub-sub-entry within this
775                                 // sub-entry. In that case, we do not want to close anything.
776                                 if (level == 2 && !eit->same_sub(last)) {
777                                         // close sub-entry
778                                         xs << html::EndTag("li") << html::CR();
779                                         // is this another sub-entry with the same main entry?
780                                         if (!eit->same_main(last)) {
781                                                 // close this level
782                                                 xs << html::EndTag("ul") << html::CR();
783                                                 level = 1;
784                                         }
785                                 }
786                                 // again, we can get here two ways: from above, or because we have
787                                 // found the first sub-entry. in the latter case, we do not want to
788                                 // close the entry.
789                                 if (level == 1 && !eit->same_main(last)) {
790                                         // close entry
791                                         xs << html::EndTag("li") << html::CR();
792                                 }
793                         }
794
795                         // we'll be starting new entries
796                         entry_number = 0;
797
798                         // We need to use our own stream, since we will have to
799                         // modify what we get back.
800                         odocstringstream ent;
801                         XHTMLStream entstream(ent);
802                         OutputParams ours = op;
803                         ours.for_toc = true;
804                         par.simpleLyXHTMLOnePar(buffer(), entstream, ours, dummy);
805
806                         // these will contain XHTML versions of the main entry, etc
807                         // remember that everything will already have been escaped,
808                         // so we'll need to use NextRaw() during output.
809                         docstring main;
810                         docstring sub;
811                         docstring subsub;
812                         extractSubentries(ent.str(), main, sub, subsub);
813                         parseItem(main, true);
814                         parseItem(sub, true);
815                         parseItem(subsub, true);
816
817                         if (level == 3) {
818                                 // another subsubentry
819                                 xs << html::StartTag("li", "class='subsubentry'")
820                                    << XHTMLStream::ESCAPE_NONE << subsub;
821                         } else if (level == 2) {
822                                 // there are two ways we can be here:
823                                 // (i) we can actually be inside a sub-entry already and be about
824                                 //     to output the first sub-sub-entry. in this case, our sub
825                                 //     and the last sub will be the same.
826                                 // (ii) we can just have closed a sub-entry, possibly after also
827                                 //     closing a list of sub-sub-entries. here our sub and the last
828                                 //     sub are different.
829                                 // only in the latter case do we need to output the new sub-entry.
830                                 // note that in this case, too, though, the sub-entry might already
831                                 // have a sub-sub-entry.
832                                 if (eit->sub != last.sub)
833                                         xs << html::StartTag("li", "class='subentry'")
834                                            << XHTMLStream::ESCAPE_NONE << sub;
835                                 if (!subsub.empty()) {
836                                         // it's actually a subsubentry, so we need to start that list
837                                         xs << html::CR()
838                                            << html::StartTag("ul", "class='subsubentry'")
839                                            << html::StartTag("li", "class='subsubentry'")
840                                            << XHTMLStream::ESCAPE_NONE << subsub;
841                                         level = 3;
842                                 }
843                         } else {
844                                 // there are also two ways we can be here:
845                                 // (i) we can actually be inside an entry already and be about
846                                 //     to output the first sub-entry. in this case, our main
847                                 //     and the last main will be the same.
848                                 // (ii) we can just have closed an entry, possibly after also
849                                 //     closing a list of sub-entries. here our main and the last
850                                 //     main are different.
851                                 // only in the latter case do we need to output the new main entry.
852                                 // note that in this case, too, though, the main entry might already
853                                 // have a sub-entry, or even a sub-sub-entry.
854                                 if (eit->main != last.main)
855                                         xs << html::StartTag("li", "class='main'") << main;
856                                 if (!sub.empty()) {
857                                         // there's a sub-entry, too
858                                         xs << html::CR()
859                                            << html::StartTag("ul", "class='subentry'")
860                                            << html::StartTag("li", "class='subentry'")
861                                            << XHTMLStream::ESCAPE_NONE << sub;
862                                         level = 2;
863                                         if (!subsub.empty()) {
864                                                 // and a sub-sub-entry
865                                                 xs << html::CR()
866                                                    << html::StartTag("ul", "class='subsubentry'")
867                                                    << html::StartTag("li", "class='subsubentry'")
868                                                    << XHTMLStream::ESCAPE_NONE << subsub;
869                                                 level = 3;
870                                         }
871                                 }
872                         }
873                 }
874                 // finally, then, we can output the index link itself
875                 string const parattr = "href='#" + par.magicLabel() + "'";
876                 xs << (entry_number == 0 ? ":" : ",");
877                 xs << " " << html::StartTag("a", parattr)
878                    << ++entry_number << html::EndTag("a");
879                 last = *eit;
880         }
881         // now we have to close all the open levels
882         while (level > 0) {
883                 xs << html::EndTag("li") << html::EndTag("ul") << html::CR();
884                 --level;
885         }
886         xs << html::EndTag("div") << html::CR();
887         return ods.str();
888 }
889
890 } // namespace lyx