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