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