]> git.lyx.org Git - features.git/blob - src/insets/InsetIndex.cpp
Guard some debug code
[features.git] / src / insets / InsetIndex.cpp
1 /**
2  * \file InsetIndex.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author Jürgen Spitzmüller
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11 #include <config.h>
12
13 #include "InsetIndex.h"
14 #include "InsetIndexMacro.h"
15
16 #include "Buffer.h"
17 #include "BufferParams.h"
18 #include "BufferView.h"
19 #include "ColorSet.h"
20 #include "Cursor.h"
21 #include "CutAndPaste.h"
22 #include "DispatchResult.h"
23 #include "Encoding.h"
24 #include "ErrorList.h"
25 #include "FuncRequest.h"
26 #include "FuncStatus.h"
27 #include "IndicesList.h"
28 #include "InsetList.h"
29 #include "Language.h"
30 #include "LaTeX.h"
31 #include "LaTeXFeatures.h"
32 #include "Lexer.h"
33 #include "LyX.h"
34 #include "output_latex.h"
35 #include "output_xhtml.h"
36 #include "xml.h"
37 #include "texstream.h"
38 #include "TextClass.h"
39 #include "TocBackend.h"
40
41 #include "support/debug.h"
42 #include "support/docstream.h"
43 #include "support/FileName.h"
44 #include "support/gettext.h"
45 #include "support/lstrings.h"
46 #include "support/Translator.h"
47
48 #include "frontends/alert.h"
49
50 #include <algorithm>
51 #include <set>
52 #include <iostream>
53
54 #include <QThreadStorage>
55
56 using namespace std;
57 using namespace lyx::support;
58
59 // Uncomment to enable InsetIndex-specific debugging mode: the tree for the index will be printed to std::cout.
60 // #define LYX_INSET_INDEX_DEBUG
61
62 namespace lyx {
63
64 namespace {
65
66 typedef Translator<string, InsetIndexParams::PageRange> PageRangeTranslator;
67 typedef Translator<docstring, InsetIndexParams::PageRange> PageRangeTranslatorLoc;
68
69 PageRangeTranslator const init_insetindexpagerangetranslator()
70 {
71         PageRangeTranslator translator("none", InsetIndexParams::None);
72         translator.addPair("start", InsetIndexParams::Start);
73         translator.addPair("end", InsetIndexParams::End);
74         return translator;
75 }
76
77 PageRangeTranslator const init_insetindexpagerangetranslator_latex()
78 {
79         PageRangeTranslator translator("", InsetIndexParams::None);
80         translator.addPair("(", InsetIndexParams::Start);
81         translator.addPair(")", InsetIndexParams::End);
82         return translator;
83 }
84
85
86 PageRangeTranslatorLoc const init_insetindexpagerangetranslator_loc()
87 {
88         PageRangeTranslatorLoc translator(docstring(), InsetIndexParams::None);
89         translator.addPair(_("Starts page range"), InsetIndexParams::Start);
90         translator.addPair(_("Ends page range"), InsetIndexParams::End);
91         return translator;
92 }
93
94
95 PageRangeTranslator const & insetindexpagerangetranslator()
96 {
97         static PageRangeTranslator const prtranslator =
98                         init_insetindexpagerangetranslator();
99         return prtranslator;
100 }
101
102
103 PageRangeTranslatorLoc const & insetindexpagerangetranslator_loc()
104 {
105         static PageRangeTranslatorLoc const translator =
106                         init_insetindexpagerangetranslator_loc();
107         return translator;
108 }
109
110
111 PageRangeTranslator const & insetindexpagerangetranslator_latex()
112 {
113         static PageRangeTranslator const lttranslator =
114                         init_insetindexpagerangetranslator_latex();
115         return lttranslator;
116 }
117
118 } // namespace anon
119
120 /////////////////////////////////////////////////////////////////////
121 //
122 // InsetIndex
123 //
124 ///////////////////////////////////////////////////////////////////////
125
126
127 InsetIndex::InsetIndex(Buffer * buf, InsetIndexParams const & params)
128         : InsetCollapsible(buf), params_(params)
129 {}
130
131
132 void InsetIndex::latex(otexstream & ios, OutputParams const & runparams_in) const
133 {
134         OutputParams runparams(runparams_in);
135         runparams.inIndexEntry = true;
136         if (runparams_in.postpone_fragile_stuff)
137                 // This is not needed and would impact sorting
138                 runparams.moving_arg = false;
139
140         otexstringstream os;
141
142         if (buffer().masterBuffer()->params().use_indices && !params_.index.empty()
143                 && params_.index != "idx") {
144                 os << "\\sindex[";
145                 os << escape(params_.index);
146                 os << "]{";
147         } else {
148                 os << "\\index";
149                 os << '{';
150         }
151
152         // Get the LaTeX output from InsetText. We need to deconstruct this later
153         // in order to check if we need to generate a sorting key
154         odocstringstream ourlatex;
155         otexstream ots(ourlatex);
156         InsetText::latex(ots, runparams);
157         if (runparams.find_effective()) {
158                 // No need for special handling, if we are only searching for some patterns
159                 os << ourlatex.str() << "}";
160                 return;
161         }
162
163         if (hasSortKey()) {
164                 getSortkey(os, runparams);
165                 os << "@";
166                 os << ourlatex.str();
167                 getSubentries(os, runparams, ourlatex.str());
168                 if (hasSeeRef()) {
169                         os << "|";
170                         os << insetindexpagerangetranslator_latex().find(params_.range);
171                         getSeeRefs(os, runparams);
172                 } else if (!params_.pagefmt.empty() && params_.pagefmt != "default") {
173                         os << "|";
174                         os << insetindexpagerangetranslator_latex().find(params_.range);
175                         os << from_utf8(params_.pagefmt);
176                 } else if (params_.range != InsetIndexParams::PageRange::None) {
177                         os << "|";
178                         os << insetindexpagerangetranslator_latex().find(params_.range);
179                 }
180         } else {
181                 // We check whether we need a sort key.
182                 // If so, we use the plaintext version
183                 odocstringstream ourplain;
184                 InsetText::plaintext(ourplain, runparams);
185
186                 // These are the LaTeX and plaintext representations
187                 docstring latexstr = ourlatex.str();
188                 docstring plainstr = ourplain.str();
189         
190                 // This will get what follows | if anything does,
191                 // the command (e.g., see, textbf) for pagination
192                 // formatting
193                 docstring cmd;
194
195                 if (hasSeeRef()) {
196                         odocstringstream seeref;
197                         otexstream otsee(seeref);
198                         getSeeRefs(otsee, runparams);
199                         cmd = seeref.str();
200                 } else if (!params_.pagefmt.empty() && params_.pagefmt != "default") {
201                         cmd = from_utf8(params_.pagefmt);
202                 } else {
203                         // Check for the | separator to strip the cmd.
204                         // This goes wrong on an escaped "|", but as the escape
205                         // character can be changed in style files, we cannot
206                         // prevent that.
207                         size_t pos = latexstr.find(from_ascii("|"));
208                         if (pos != docstring::npos) {
209                                 // Put the bit after "|" into cmd...
210                                 cmd = latexstr.substr(pos + 1);
211                                 // ...and erase that stuff from latexstr
212                                 latexstr = latexstr.erase(pos);
213                                 // ...as well as from plainstr
214                                 size_t ppos = plainstr.find(from_ascii("|"));
215                                 if (ppos < plainstr.size())
216                                         plainstr.erase(ppos);
217                                 else
218                                         LYXERR0("The `|' separator was not found in the plaintext version!");
219                         }
220                 }
221
222                 odocstringstream subentries;
223                 otexstream otsub(subentries);
224                 getSubentries(otsub, runparams, ourlatex.str());
225                 if (subentries.str().empty()) {
226                         // Separate the entries and subentries, i.e., split on "!".
227                         // This goes wrong on an escaped "!", but as the escape
228                         // character can be changed in style files, we cannot
229                         // prevent that.
230                         std::vector<docstring> const levels =
231                                         getVectorFromString(latexstr, from_ascii("!"), true);
232                         std::vector<docstring> const levels_plain =
233                                         getVectorFromString(plainstr, from_ascii("!"), true);
234                 
235                         vector<docstring>::const_iterator it = levels.begin();
236                         vector<docstring>::const_iterator end = levels.end();
237                         vector<docstring>::const_iterator it2 = levels_plain.begin();
238                         bool first = true;
239                         for (; it != end; ++it) {
240                                 if ((*it).empty()) {
241                                         emptySubentriesWarning(ourlatex.str());
242                                         if (it2 < levels_plain.end())
243                                                 ++it2;
244                                         continue;
245                                 }
246                                 // The separator needs to be put back when
247                                 // writing the levels, except for the first level
248                                 if (!first)
249                                         os << '!';
250                                 else
251                                         first = false;
252                 
253                                 // Now here comes the reason for this whole procedure:
254                                 // We try to correctly sort macros and formatted strings.
255                                 // If we find a command, prepend a plain text
256                                 // version of the content to get sorting right,
257                                 // e.g. \index{LyX@\LyX}, \index{text@\textbf{text}}.
258                                 // We do this on all levels.
259                                 // We don't do it if the level already contains a '@', though.
260                                 // Plaintext might return nothing (e.g. for ERTs).
261                                 // In that case, we use LaTeX.
262                                 docstring const spart = (levels_plain.empty() || (*it2).empty()) ? *it : *it2;
263                                 processLatexSorting(os, runparams, *it, spart);
264                                 if (it2 < levels_plain.end())
265                                         ++it2;
266                         }
267                 } else {
268                         processLatexSorting(os, runparams, latexstr, plainstr);
269                         os << subentries.str();
270                 }
271
272                 // At last, re-insert the command, separated by "|"
273                 if (!cmd.empty()) {
274                         os << "|"
275                            << insetindexpagerangetranslator_latex().find(params_.range)
276                            << cmd;
277                 } else if (params_.range != InsetIndexParams::PageRange::None) {
278                         os << "|";
279                         os << insetindexpagerangetranslator_latex().find(params_.range);
280                 }
281         }
282         os << '}';
283
284         // In macros with moving arguments, such as \section,
285         // we store the index and output it after the macro (#2154)
286         if (runparams_in.postpone_fragile_stuff)
287                 runparams_in.post_macro += os.str();
288         else
289                 ios << os.release();
290 }
291
292
293 void InsetIndex::processLatexSorting(otexstream & os, OutputParams const & runparams,
294                                 docstring const latex, docstring const spart) const
295 {
296         if (contains(latex, '\\') && !contains(latex, '@')) {
297                 // Now we need to validate that all characters in
298                 // the sorting part are representable in the current
299                 // encoding. If not try the LaTeX macro which might
300                 // or might not be a good choice, and issue a warning.
301                 pair<docstring, docstring> spart_latexed =
302                                 runparams.encoding->latexString(spart, runparams.dryrun);
303                 if (!spart_latexed.second.empty())
304                         LYXERR0("Uncodable character in index entry. Sorting might be wrong!");
305                 if (spart != spart_latexed.first && !runparams.dryrun) {
306                         TeXErrors terr;
307                         ErrorList & errorList = buffer().errorList("Export");
308                         docstring const s = bformat(_("LyX's automatic index sorting algorithm faced "
309                                                       "problems with the entry '%1$s'.\n"
310                                                       "Please specify the sorting of this entry manually, as "
311                                                       "explained in the User Guide."), spart);
312                         Paragraph const & par = buffer().paragraphs().front();
313                         errorList.push_back(ErrorItem(_("Index sorting failed"), s,
314                                                       {par.id(), 0}, {par.id(), -1}));
315                         buffer().bufferErrors(terr, errorList);
316                 }
317                 // Remove remaining \'s from the sort key
318                 docstring ppart = subst(spart_latexed.first, from_ascii("\\"), docstring());
319                 // Plain quotes need to be escaped, however (#10649), as this
320                 // is the default escape character
321                 ppart = subst(ppart, from_ascii("\""), from_ascii("\\\""));
322
323                 // Now insert the sortkey, separated by '@'.
324                 os << ppart;
325                 os << '@';
326         }
327         // Insert the actual level text
328         os << latex;
329 }
330
331
332 void InsetIndex::docbook(XMLStream & xs, OutputParams const & runparams) const
333 {
334         // Two ways of processing this inset are implemented:
335         // - the legacy one, based on parsing the raw LaTeX (before LyX 2.4) -- unlikely to be deprecated
336         // - the modern one, based on precise insets for indexing features
337         // Like the LaTeX implementation, consider the user chooses either of those options.
338
339         // Get the content of the inset as LaTeX, as some things may be encoded as ERT (like {}).
340         // TODO: if there is an ERT within the index term, its conversion should be tried, in case it becomes useful;
341         //  otherwise, ERTs should become comments. For now, they are just copied as-is, which is barely satisfactory.
342         odocstringstream odss;
343         otexstream ots(odss);
344         InsetText::latex(ots, runparams);
345         docstring latexString = trim(odss.str());
346
347         // Handle several indices (indicated in the inset instead of the raw latexString).
348         docstring indexType = from_utf8("");
349         if (buffer().masterBuffer()->params().use_indices) {
350                 indexType += " type=\"" + params_.index + "\"";
351         }
352
353         // Split the string into its main constituents: terms, and command (see, see also, range).
354         size_t positionVerticalBar = latexString.find(from_ascii("|")); // What comes before | is (sub)(sub)entries.
355         docstring indexTerms = latexString.substr(0, positionVerticalBar);
356         docstring command;
357         if (positionVerticalBar != lyx::docstring::npos) {
358                 command = latexString.substr(positionVerticalBar + 1);
359         }
360
361         // Handle sorting issues, with @.
362         docstring sortAs;
363         if (hasSortKey()) {
364                 sortAs = getSortkeyAsText(runparams);
365                 // indexTerms may contain a sort key if the user has both the inset and the manual key.
366         } else {
367                 vector<docstring> sortingElements = getVectorFromString(indexTerms, from_ascii("@"), false);
368                 if (sortingElements.size() == 2) {
369                         sortAs = sortingElements[0];
370                         indexTerms = sortingElements[1];
371                 }
372         }
373
374         // Handle primary, secondary, and tertiary terms (entries, subentries, and subsubentries, for LaTeX).
375         vector<docstring> terms;
376         if (const vector<docstring> potential_terms = getSubentriesAsText(runparams); !potential_terms.empty()) {
377                 terms = potential_terms;
378                 // The main term is not present in the vector, as it's not a subentry. The main index term is inserted raw in
379                 // the index inset. Considering that the user either uses the new or the legacy mechanism, the main term is the
380                 // full string within this inset (i.e. without the subinsets).
381                 terms.insert(terms.begin(), latexString);
382         } else {
383                 terms = getVectorFromString(indexTerms, from_ascii("!"), false);
384         }
385
386         // Handle ranges. Happily, in the raw LaTeX mode, (| and |) can only be at the end of the string!
387         const bool hasInsetRange = params_.range != InsetIndexParams::PageRange::None;
388         const bool hasStartRange = params_.range == InsetIndexParams::PageRange::Start ||
389                         latexString.find(from_ascii("|(")) != lyx::docstring::npos;
390         const bool hasEndRange = params_.range == InsetIndexParams::PageRange::End ||
391                         latexString.find(from_ascii("|)")) != lyx::docstring::npos;
392
393         if (hasInsetRange) {
394                 // Remove the ranges from the command if they do not appear at the beginning.
395                 size_t index = 0;
396                 while ((index = command.find(from_utf8("|("), index)) != std::string::npos)
397                         command.erase(index, 1);
398                 index = 0;
399                 while ((index = command.find(from_utf8("|)"), index)) != std::string::npos)
400                         command.erase(index, 1);
401
402                 // Remove the ranges when they are the only vertical bar in the complete string.
403                 if (command[0] == '(' || command[0] == ')')
404                         command.erase(0, 1);
405         }
406
407         // Handle see and seealso. As "see" is a prefix of "seealso", the order of the comparisons is important.
408         // Both commands are mutually exclusive!
409         docstring see = getSeeAsText(runparams);
410         vector<docstring> seeAlsoes = getSeeAlsoesAsText(runparams);
411
412         if (see.empty() && seeAlsoes.empty() && command.substr(0, 3) == "see") {
413                 // Unescape brackets.
414                 size_t index = 0;
415                 while ((index = command.find(from_utf8("\\{"), index)) != std::string::npos)
416                         command.erase(index, 1);
417                 index = 0;
418                 while ((index = command.find(from_utf8("\\}"), index)) != std::string::npos)
419                         command.erase(index, 1);
420
421                 // Retrieve the part between brackets, and remove the complete seealso.
422                 size_t positionOpeningBracket = command.find(from_ascii("{"));
423                 size_t positionClosingBracket = command.find(from_ascii("}"));
424                 docstring list = command.substr(positionOpeningBracket + 1, positionClosingBracket - positionOpeningBracket - 1);
425
426                 // Parse the list of referenced entries (or a single one for see).
427                 if (command.substr(0, 7) == "seealso") {
428                         seeAlsoes = getVectorFromString(list, from_ascii(","), false);
429                 } else {
430                         see = list;
431
432                         if (see.find(from_ascii(",")) != std::string::npos) {
433                                 docstring error = from_utf8("Several index terms found as \"see\"! Only one is acceptable. "
434                                                                                         "Complete entry: \"") + latexString + from_utf8("\"");
435                                 LYXERR0(error);
436                                 xs << XMLStream::ESCAPE_NONE << (from_utf8("<!-- Output Error: ") + error + from_utf8(" -->\n"));
437                         }
438                 }
439
440                 // Remove the complete see/seealso from the commands, in case there is something else to parse.
441                 command = command.substr(positionClosingBracket + 1);
442         }
443
444         // Some parts of the strings are not parsed, as they do not have anything matching in DocBook: things like
445         // formatting the entry or the page number, other strings for sorting. https://wiki.lyx.org/Tips/Indexing
446         // If there are such things in the index entry, then this code may miserably fail. For example, for "Peter|(textbf",
447         // no range will be detected.
448         // TODO: Could handle formatting as significance="preferred"?
449         if (!command.empty()) {
450                 docstring error = from_utf8("Unsupported feature: an index entry contains a | with an unsupported command, ")
451                                           + command + from_utf8(". ") + from_utf8("Complete entry: \"") + latexString + from_utf8("\"");
452                 LYXERR0(error);
453                 xs << XMLStream::ESCAPE_NONE << (from_utf8("<!-- Output Error: ") + error + from_utf8(" -->\n"));
454         }
455
456         // Write all of this down.
457         if (terms.empty() && !hasEndRange) {
458                 docstring error = from_utf8("No index term found! Complete entry: \"") + latexString + from_utf8("\"");
459                 LYXERR0(error);
460                 xs << XMLStream::ESCAPE_NONE << (from_utf8("<!-- Output Error: ") + error + from_utf8(" -->\n"));
461         } else {
462                 // Generate the attributes for ranges. It is based on the terms that are indexed, but the ID must be unique
463                 // to this indexing area (xml::cleanID does not guarantee this: for each call with the same arguments,
464                 // the same legal ID is produced; here, as the input would be the same, the output must be, by design).
465                 // Hence the thread-local storage, as the numbers must strictly be unique, and thus cannot be shared across
466                 // a paragraph (making the solution used for HTML worthless). This solution is very similar to the one used in
467                 // xml::cleanID.
468                 // indexType can only be used for singular and startofrange types!
469                 docstring attrs;
470                 if (!hasStartRange && !hasEndRange) {
471                         attrs = indexType;
472                 } else {
473                         // Append an ID if uniqueness is not guaranteed across the document.
474                         static QThreadStorage<set<docstring>> tKnownTermLists;
475                         static QThreadStorage<int> tID;
476
477                         set<docstring> &knownTermLists = tKnownTermLists.localData();
478                         int &ID = tID.localData();
479
480                         if (!tID.hasLocalData()) {
481                                 tID.localData() = 0;
482                         }
483
484                         // Modify the index terms to add the unique ID if needed.
485                         docstring newIndexTerms = indexTerms;
486                         if (knownTermLists.find(indexTerms) != knownTermLists.end()) {
487                                 newIndexTerms += from_ascii(string("-") + to_string(ID));
488
489                                 // Only increment for the end of range, so that the same number is used for the start of range.
490                                 if (hasEndRange) {
491                                         ID++;
492                                 }
493                         }
494
495                         // Term list not yet known: add it to the set AFTER the end of range. After
496                         if (knownTermLists.find(indexTerms) == knownTermLists.end() && hasEndRange) {
497                                 knownTermLists.insert(indexTerms);
498                         }
499
500                         // Generate the attributes.
501                         docstring id = xml::cleanID(newIndexTerms);
502                         if (hasStartRange) {
503                                 attrs = indexType + " class=\"startofrange\" xml:id=\"" + id + "\"";
504                         } else {
505                                 attrs = " class=\"endofrange\" startref=\"" + id + "\"";
506                         }
507                 }
508
509                 // Handle the index terms (including the specific index for this entry).
510                 if (hasEndRange) {
511                         xs << xml::CompTag("indexterm", attrs);
512                 } else {
513                         xs << xml::StartTag("indexterm", attrs);
514                         if (!terms.empty()) { // hasEndRange has no content.
515                                 docstring attr;
516                                 if (!sortAs.empty()) {
517                                         attr = from_utf8("sortas='") + sortAs + from_utf8("'");
518                                 }
519
520                                 xs << xml::StartTag("primary", attr);
521                                 xs << terms[0];
522                                 xs << xml::EndTag("primary");
523                         }
524                         if (terms.size() > 1) {
525                                 xs << xml::StartTag("secondary");
526                                 xs << terms[1];
527                                 xs << xml::EndTag("secondary");
528                         }
529                         if (terms.size() > 2) {
530                                 xs << xml::StartTag("tertiary");
531                                 xs << terms[2];
532                                 xs << xml::EndTag("tertiary");
533                         }
534
535                         // Handle see and see also.
536                         if (!see.empty()) {
537                                 xs << xml::StartTag("see");
538                                 xs << see;
539                                 xs << xml::EndTag("see");
540                         }
541
542                         if (!seeAlsoes.empty()) {
543                                 for (auto &entry : seeAlsoes) {
544                                         xs << xml::StartTag("seealso");
545                                         xs << entry;
546                                         xs << xml::EndTag("seealso");
547                                 }
548                         }
549
550                         // Close the entry.
551                         xs << xml::EndTag("indexterm");
552                 }
553         }
554 }
555
556
557 docstring InsetIndex::xhtml(XMLStream & xs, OutputParams const &) const
558 {
559         // we just print an anchor, taking the paragraph ID from
560         // our own interior paragraph, which doesn't get printed
561         std::string const magic = paragraphs().front().magicLabel();
562         std::string const attr = "id='" + magic + "'";
563         xs << xml::CompTag("a", attr);
564         return docstring();
565 }
566
567
568 bool InsetIndex::showInsetDialog(BufferView * bv) const
569 {
570         bv->showDialog("index", params2string(params_),
571                         const_cast<InsetIndex *>(this));
572         return true;
573 }
574
575
576 void InsetIndex::doDispatch(Cursor & cur, FuncRequest & cmd)
577 {
578         switch (cmd.action()) {
579
580         case LFUN_INSET_MODIFY: {
581                 if (cmd.getArg(0) == "changetype") {
582                         cur.recordUndoInset(this);
583                         params_.index = from_utf8(cmd.getArg(1));
584                         break;
585                 }
586                 if (cmd.getArg(0) == "changeparam") {
587                         string const p = cmd.getArg(1);
588                         string const v = cmd.getArg(2);
589                         cur.recordUndoInset(this);
590                         if (p == "range")
591                                 params_.range = insetindexpagerangetranslator().find(v);
592                         if (p == "pagefmt") {
593                                 if (v == "default" || v == "textbf"
594                                     || v == "textit" || v == "emph")
595                                         params_.pagefmt = v;
596                                 else
597                                         lyx::dispatch(FuncRequest(LFUN_INSET_SETTINGS, "index"));
598                         }
599                         break;
600                 }
601                 InsetIndexParams params;
602                 InsetIndex::string2params(to_utf8(cmd.argument()), params);
603                 cur.recordUndoInset(this);
604                 params_.index = params.index;
605                 params_.range = params.range;
606                 params_.pagefmt = params.pagefmt;
607                 // what we really want here is a TOC update, but that means
608                 // a full buffer update
609                 cur.forceBufferUpdate();
610                 break;
611         }
612
613         case LFUN_INSET_DIALOG_UPDATE:
614                 cur.bv().updateDialog("index", params2string(params_));
615                 break;
616
617         case LFUN_PARAGRAPH_BREAK: {
618                 // Since this inset in single-par anyway, let's use
619                 // return to enter subentries
620                 FuncRequest fr(LFUN_INDEXMACRO_INSERT, "subentry");
621                 lyx::dispatch(fr);
622                 break;
623         }
624
625         case LFUN_INSET_INSERT_COPY: {
626                 Cursor & bvcur = cur.bv().cursor();
627                 if (cmd.origin() == FuncRequest::TOC && bvcur.inTexted()) {
628                         cap::copyInsetToTemp(cur, clone());
629                         cap::pasteFromTemp(bvcur, bvcur.buffer()->errorList("Paste"));
630                 } else
631                         cur.undispatched();
632                 break;
633         }
634
635         default:
636                 InsetCollapsible::doDispatch(cur, cmd);
637                 break;
638         }
639 }
640
641
642 bool InsetIndex::getStatus(Cursor & cur, FuncRequest const & cmd,
643                 FuncStatus & flag) const
644 {
645         switch (cmd.action()) {
646
647         case LFUN_INSET_MODIFY:
648                 if (cmd.getArg(0) == "changetype") {
649                         docstring const newtype = from_utf8(cmd.getArg(1));
650                         Buffer const & realbuffer = *buffer().masterBuffer();
651                         IndicesList const & indiceslist = realbuffer.params().indiceslist();
652                         Index const * index = indiceslist.findShortcut(newtype);
653                         flag.setEnabled(index != 0);
654                         flag.setOnOff(
655                                 from_utf8(cmd.getArg(1)) == params_.index);
656                         return true;
657                 }
658                 if (cmd.getArg(0) == "changeparam") {
659                         string const p = cmd.getArg(1);
660                         string const v = cmd.getArg(2);
661                         if (p == "range") {
662                                 flag.setEnabled(v == "none" || v == "start" || v == "end");
663                                 flag.setOnOff(params_.range == insetindexpagerangetranslator().find(v));
664                         }
665                         if (p == "pagefmt") {
666                                 flag.setEnabled(!v.empty());
667                                 if (params_.pagefmt == "default" || params_.pagefmt == "textbf"
668                                     || params_.pagefmt == "textit" || params_.pagefmt == "emph")
669                                         flag.setOnOff(params_.pagefmt == v);
670                                 else
671                                         flag.setOnOff(v == "custom");
672                         }
673                         return true;
674                 }
675                 return InsetCollapsible::getStatus(cur, cmd, flag);
676
677         case LFUN_INSET_DIALOG_UPDATE: {
678                 Buffer const & realbuffer = *buffer().masterBuffer();
679                 flag.setEnabled(realbuffer.params().use_indices);
680                 return true;
681         }
682
683         case LFUN_INSET_INSERT_COPY:
684                 // This can only be invoked by ToC widget
685                 flag.setEnabled(cmd.origin() == FuncRequest::TOC
686                                 && cur.bv().cursor().inset().insetAllowed(lyxCode()));
687                 return true;
688
689         case LFUN_PARAGRAPH_BREAK:
690                 return macrosPossible("subentry");
691
692         case LFUN_INDEXMACRO_INSERT:
693                 return macrosPossible(cmd.getArg(0));
694
695         case LFUN_INDEX_TAG_ALL:
696                 return true;
697
698         default:
699                 return InsetCollapsible::getStatus(cur, cmd, flag);
700         }
701 }
702
703
704 void InsetIndex::getSortkey(otexstream & os, OutputParams const & runparams) const
705 {
706         Paragraph const & par = paragraphs().front();
707         InsetList::const_iterator it = par.insetList().begin();
708         for (; it != par.insetList().end(); ++it) {
709                 Inset & inset = *it->inset;
710                 if (inset.lyxCode() == INDEXMACRO_SORTKEY_CODE) {
711                         InsetIndexMacro const & iim =
712                                 static_cast<InsetIndexMacro const &>(inset);
713                         iim.getLatex(os, runparams);
714                         return;
715                 }
716         }
717 }
718
719
720 docstring InsetIndex::getSortkeyAsText(OutputParams const & runparams) const
721 {
722         Paragraph const & par = paragraphs().front();
723         InsetList::const_iterator it = par.insetList().begin();
724         for (; it != par.insetList().end(); ++it) {
725                 Inset & inset = *it->inset;
726                 if (inset.lyxCode() == INDEXMACRO_SORTKEY_CODE) {
727                         otexstringstream os;
728                         InsetIndexMacro const & iim =
729                                 static_cast<InsetIndexMacro const &>(inset);
730                         iim.getLatex(os, runparams);
731                         return os.str();
732                 }
733         }
734         return from_ascii("");
735 }
736
737
738 void InsetIndex::emptySubentriesWarning(docstring const & mainentry) const
739 {
740         // Empty subentries crash makeindex. So warn and ignore this.
741         TeXErrors terr;
742         ErrorList & errorList = buffer().errorList("Export");
743         docstring const s = bformat(_("There is an empty index subentry in the entry '%1$s'.\n"
744                                       "It will be ignored in the output."), mainentry);
745         Paragraph const & par = buffer().paragraphs().front();
746         errorList.push_back(ErrorItem(_("Empty index subentry!"), s,
747                                       {par.id(), 0}, {par.id(), -1}));
748         buffer().bufferErrors(terr, errorList);
749 }
750
751
752 void InsetIndex::getSubentries(otexstream & os, OutputParams const & runparams,
753                                docstring const & mainentry) const
754 {
755         Paragraph const & par = paragraphs().front();
756         InsetList::const_iterator it = par.insetList().begin();
757         int i = 0;
758         for (; it != par.insetList().end(); ++it) {
759                 Inset & inset = *it->inset;
760                 if (inset.lyxCode() == INDEXMACRO_CODE) {
761                         InsetIndexMacro const & iim =
762                                 static_cast<InsetIndexMacro const &>(inset);
763                         if (iim.params().type == InsetIndexMacroParams::Subentry) {
764                                 if (iim.hasNoContent()) {
765                                         emptySubentriesWarning(mainentry);
766                                         continue;
767                                 }
768                                 ++i;
769                                 if (i > 2)
770                                         return;
771                                 os << "!";
772                                 iim.getLatex(os, runparams);
773                         }
774                 }
775         }
776 }
777
778
779 std::vector<docstring> InsetIndex::getSubentriesAsText(OutputParams const & runparams,
780                                                        bool const asLabel) const
781 {
782         std::vector<docstring> subentries;
783
784         Paragraph const & par = paragraphs().front();
785         InsetList::const_iterator it = par.insetList().begin();
786         int i = 0;
787         for (; it != par.insetList().end(); ++it) {
788                 Inset & inset = *it->inset;
789                 if (inset.lyxCode() == INDEXMACRO_CODE) {
790                         InsetIndexMacro const & iim =
791                                 static_cast<InsetIndexMacro const &>(inset);
792                         if (iim.params().type == InsetIndexMacroParams::Subentry) {
793                                 ++i;
794                                 if (i > 2)
795                                         break;
796                                 if (asLabel) {
797                                         docstring const l;
798                                         docstring const sl = iim.getNewLabel(l);
799                                         subentries.emplace_back(sl);
800                                 } else {
801                                         otexstringstream os;
802                                         iim.getLatex(os, runparams);
803                                         subentries.emplace_back(os.str());
804                                 }
805                         }
806                 }
807         }
808
809         return subentries;
810 }
811
812
813 docstring InsetIndex::getMainSubentryAsText(OutputParams const & runparams) const
814 {
815         otexstringstream os;
816         InsetText::latex(os, runparams);
817         return os.str();
818 }
819
820
821 void InsetIndex::getSeeRefs(otexstream & os, OutputParams const & runparams) const
822 {
823         Paragraph const & par = paragraphs().front();
824         InsetList::const_iterator it = par.insetList().begin();
825         for (; it != par.insetList().end(); ++it) {
826                 Inset & inset = *it->inset;
827                 if (inset.lyxCode() == INDEXMACRO_CODE) {
828                         InsetIndexMacro const & iim =
829                                 static_cast<InsetIndexMacro const &>(inset);
830                         if (iim.params().type == InsetIndexMacroParams::See
831                             || iim.params().type == InsetIndexMacroParams::Seealso) {
832                                 iim.getLatex(os, runparams);
833                                 return;
834                         }
835                 }
836         }
837 }
838
839
840 docstring InsetIndex::getSeeAsText(OutputParams const & runparams,
841                                    bool const asLabel) const
842 {
843         Paragraph const & par = paragraphs().front();
844         InsetList::const_iterator it = par.insetList().begin();
845         for (; it != par.insetList().end(); ++it) {
846                 Inset & inset = *it->inset;
847                 if (inset.lyxCode() == INDEXMACRO_CODE) {
848                         InsetIndexMacro const & iim =
849                                 static_cast<InsetIndexMacro const &>(inset);
850                         if (iim.params().type == InsetIndexMacroParams::See) {
851                                 if (asLabel) {
852                                         docstring const l;
853                                         return iim.getNewLabel(l);
854                                 } else {
855                                         otexstringstream os;
856                                         iim.getLatex(os, runparams);
857                                         return os.str();
858                                 }
859                         }
860                 }
861         }
862         return from_ascii("");
863 }
864
865
866 std::vector<docstring> InsetIndex::getSeeAlsoesAsText(OutputParams const & runparams,
867                                                       bool const asLabel) const
868 {
869         std::vector<docstring> seeAlsoes;
870
871         Paragraph const & par = paragraphs().front();
872         InsetList::const_iterator it = par.insetList().begin();
873         for (; it != par.insetList().end(); ++it) {
874                 Inset & inset = *it->inset;
875                 if (inset.lyxCode() == INDEXMACRO_CODE) {
876                         InsetIndexMacro const & iim =
877                                 static_cast<InsetIndexMacro const &>(inset);
878                         if (iim.params().type == InsetIndexMacroParams::Seealso) {
879                                 if (asLabel) {
880                                         docstring const l;
881                                         seeAlsoes.emplace_back(iim.getNewLabel(l));
882                                 } else {
883                                         otexstringstream os;
884                                         iim.getLatex(os, runparams);
885                                         seeAlsoes.emplace_back(os.str());
886                                 }
887                         }
888                 }
889         }
890
891         return seeAlsoes;
892 }
893
894
895 namespace {
896
897 bool hasInsetWithCode(const InsetIndex * const inset_index, const InsetCode code,
898                                           const std::set<InsetIndexMacroParams::Type> types = {})
899 {
900         Paragraph const & par = inset_index->paragraphs().front();
901         InsetList::const_iterator it = par.insetList().begin();
902         for (; it != par.insetList().end(); ++it) {
903                 Inset & inset = *it->inset;
904                 if (inset.lyxCode() == code) {
905                         if (types.empty())
906                                 return true;
907
908                         LASSERT(code == INDEXMACRO_CODE, return false);
909                         InsetIndexMacro const & iim =
910                                         static_cast<InsetIndexMacro const &>(inset);
911                         if (types.find(iim.params().type) != types.end())
912                                 return true;
913                 }
914         }
915         return false;
916 }
917
918 } // namespace
919
920
921 bool InsetIndex::hasSubentries() const
922 {
923         return hasInsetWithCode(this, INDEXMACRO_CODE, {InsetIndexMacroParams::Subentry});
924 }
925
926
927 bool InsetIndex::hasSeeRef() const
928 {
929         return hasInsetWithCode(this, INDEXMACRO_CODE, {InsetIndexMacroParams::See, InsetIndexMacroParams::Seealso});
930 }
931
932
933 bool InsetIndex::hasSortKey() const
934 {
935         return hasInsetWithCode(this, INDEXMACRO_SORTKEY_CODE);
936 }
937
938
939 bool InsetIndex::macrosPossible(string const type) const
940 {
941         if (type != "see" && type != "seealso"
942             && type != "sortkey" && type != "subentry")
943                 return false;
944
945         Paragraph const & par = paragraphs().front();
946         InsetList::const_iterator it = par.insetList().begin();
947         int subidxs = 0;
948         for (; it != par.insetList().end(); ++it) {
949                 Inset & inset = *it->inset;
950                 if (type == "sortkey" && inset.lyxCode() == INDEXMACRO_SORTKEY_CODE)
951                         return false;
952                 if (inset.lyxCode() == INDEXMACRO_CODE) {
953                         InsetIndexMacro const & iim = static_cast<InsetIndexMacro const &>(inset);
954                         if ((type == "see" || type == "seealso")
955                              && (iim.params().type == InsetIndexMacroParams::See
956                                  || iim.params().type == InsetIndexMacroParams::Seealso))
957                                 return false;
958                         if (type == "subentry"
959                              && iim.params().type == InsetIndexMacroParams::Subentry) {
960                                 ++subidxs;
961                                 if (subidxs > 1)
962                                         return false;
963                         }
964                 }
965         }
966         return true;
967 }
968
969
970 ColorCode InsetIndex::labelColor() const
971 {
972         if (params_.index.empty() || params_.index == from_ascii("idx"))
973                 return InsetCollapsible::labelColor();
974         // FIXME UNICODE
975         ColorCode c = lcolor.getFromLyXName(to_utf8(params_.index)
976                                             + "@" + buffer().fileName().absFileName());
977         if (c == Color_none)
978                 c = InsetCollapsible::labelColor();
979         return c;
980 }
981
982
983 docstring InsetIndex::toolTip(BufferView const &, int, int) const
984 {
985         docstring tip = _("Index Entry");
986         if (buffer().params().use_indices && !params_.index.empty()) {
987                 Buffer const & realbuffer = *buffer().masterBuffer();
988                 IndicesList const & indiceslist = realbuffer.params().indiceslist();
989                 tip += " (";
990                 Index const * index = indiceslist.findShortcut(params_.index);
991                 if (!index)
992                         tip += _("unknown type!");
993                 else
994                         tip += index->index();
995                 tip += ")";
996         }
997         tip += ": ";
998         docstring res = toolTipText(tip);
999         if (!insetindexpagerangetranslator_loc().find(params_.range).empty())
1000                 res += "\n" + insetindexpagerangetranslator_loc().find(params_.range);
1001         if (!params_.pagefmt.empty() && params_.pagefmt != "default") {
1002                 res += "\n" + _("Pagination format:") + " ";
1003                 if (params_.pagefmt == "textbf")
1004                         res += _("bold");
1005                 else if (params_.pagefmt == "textit")
1006                         res += _("italic");
1007                 else if (params_.pagefmt == "emph")
1008                         res += _("emphasized");
1009                 else
1010                         res += from_utf8(params_.pagefmt);
1011         }
1012         return res;
1013 }
1014
1015
1016 docstring const InsetIndex::buttonLabel(BufferView const & bv) const
1017 {
1018         InsetLayout const & il = getLayout();
1019         docstring label = translateIfPossible(il.labelstring());
1020
1021         if (buffer().params().use_indices && !params_.index.empty()) {
1022                 Buffer const & realbuffer = *buffer().masterBuffer();
1023                 IndicesList const & indiceslist = realbuffer.params().indiceslist();
1024                 label += " (";
1025                 Index const * index = indiceslist.findShortcut(params_.index);
1026                 if (!index)
1027                         label += _("unknown type!");
1028                 else
1029                         label += index->index();
1030                 label += ")";
1031         }
1032
1033         docstring res;
1034         if (!il.contentaslabel() || geometry(bv) != ButtonOnly)
1035                 res = label;
1036         else {
1037                 res = getNewLabel(label);
1038                 OutputParams const rp(0);
1039                 vector<docstring> sublbls = getSubentriesAsText(rp, true);
1040                 for (auto const & sublbl : sublbls) {
1041                         res += " " + docstring(1, char_type(0x2023));// TRIANGULAR BULLET
1042                         res += " " + sublbl;
1043                 }
1044                 docstring see = getSeeAsText(rp, true);
1045                 if (see.empty() && !getSeeAlsoesAsText(rp, true).empty())
1046                         see = getSeeAlsoesAsText(rp, true).front();
1047                 if (!see.empty()) {
1048                         res += " " + docstring(1, char_type(0x261e));// WHITE RIGHT POINTING INDEX
1049                         res += " " + see;
1050                 }
1051         }
1052         if (!insetindexpagerangetranslator_latex().find(params_.range).empty())
1053                 res += " " + from_ascii(insetindexpagerangetranslator_latex().find(params_.range));
1054         return res;
1055 }
1056
1057
1058 void InsetIndex::write(ostream & os) const
1059 {
1060         os << to_utf8(layoutName());
1061         params_.write(os);
1062         InsetCollapsible::write(os);
1063 }
1064
1065
1066 void InsetIndex::read(Lexer & lex)
1067 {
1068         params_.read(lex);
1069         InsetCollapsible::read(lex);
1070 }
1071
1072
1073 string InsetIndex::params2string(InsetIndexParams const & params)
1074 {
1075         ostringstream data;
1076         data << "index";
1077         params.write(data);
1078         return data.str();
1079 }
1080
1081
1082 void InsetIndex::string2params(string const & in, InsetIndexParams & params)
1083 {
1084         params = InsetIndexParams();
1085         if (in.empty())
1086                 return;
1087
1088         istringstream data(in);
1089         Lexer lex;
1090         lex.setStream(data);
1091         lex.setContext("InsetIndex::string2params");
1092         lex >> "index";
1093         params.read(lex);
1094 }
1095
1096
1097 void InsetIndex::addToToc(DocIterator const & cpit, bool output_active,
1098                                                   UpdateType utype, TocBackend & backend) const
1099 {
1100         DocIterator pit = cpit;
1101         pit.push_back(CursorSlice(const_cast<InsetIndex &>(*this)));
1102         docstring str;
1103         InsetLayout const & il = getLayout();
1104         docstring label = translateIfPossible(il.labelstring());
1105         if (!il.contentaslabel())
1106                 str = label;
1107         else {
1108                 str = getNewLabel(label);
1109                 OutputParams const rp(0);
1110                 vector<docstring> sublbls = getSubentriesAsText(rp, true);
1111                 for (auto const & sublbl : sublbls) {
1112                         str += " " + docstring(1, char_type(0x2023));// TRIANGULAR BULLET
1113                         str += " " + sublbl;
1114                 }
1115                 docstring see = getSeeAsText(rp, true);
1116                 if (see.empty() && !getSeeAlsoesAsText(rp, true).empty())
1117                         see = getSeeAlsoesAsText(rp, true).front();
1118                 if (!see.empty()) {
1119                         str += " " + docstring(1, char_type(0x261e));// WHITE RIGHT POINTING INDEX
1120                         str += " " + see;
1121                 }
1122         }
1123         string type = "index";
1124         if (buffer().masterBuffer()->params().use_indices)
1125                 type += ":" + to_utf8(params_.index);
1126         TocBuilder & b = backend.builder(type);
1127         b.pushItem(pit, str, output_active);
1128         // Proceed with the rest of the inset.
1129         InsetCollapsible::addToToc(cpit, output_active, utype, backend);
1130         b.pop();
1131 }
1132
1133
1134 void InsetIndex::validate(LaTeXFeatures & features) const
1135 {
1136         if (buffer().masterBuffer()->params().use_indices
1137             && !params_.index.empty()
1138             && params_.index != "idx")
1139                 features.require("splitidx");
1140         InsetCollapsible::validate(features);
1141 }
1142
1143
1144 string InsetIndex::contextMenuName() const
1145 {
1146         return "context-index";
1147 }
1148
1149
1150 string InsetIndex::contextMenu(BufferView const & bv, int x, int y) const
1151 {
1152         // We override the implementation of InsetCollapsible,
1153         // because we have eytra entries.
1154         string owncm = "context-edit-index;";
1155         return owncm + InsetCollapsible::contextMenu(bv, x, y);
1156 }
1157
1158
1159 bool InsetIndex::hasSettings() const
1160 {
1161         return true;
1162 }
1163
1164
1165 bool InsetIndex::insetAllowed(InsetCode code) const
1166 {
1167         switch (code) {
1168         case INDEXMACRO_CODE:
1169         case INDEXMACRO_SORTKEY_CODE:
1170                 return true;
1171         case INDEX_CODE:
1172                 return false;
1173         default:
1174                 return InsetCollapsible::insetAllowed(code);
1175         }
1176 }
1177
1178
1179 /////////////////////////////////////////////////////////////////////
1180 //
1181 // InsetIndexParams
1182 //
1183 ///////////////////////////////////////////////////////////////////////
1184
1185
1186 void InsetIndexParams::write(ostream & os) const
1187 {
1188         os << ' ';
1189         if (!index.empty())
1190                 os << to_utf8(index);
1191         else
1192                 os << "idx";
1193         os << '\n';
1194         os << "range "
1195            << insetindexpagerangetranslator().find(range)
1196            << '\n';
1197         os << "pageformat "
1198            << pagefmt
1199            << '\n';
1200 }
1201
1202
1203 void InsetIndexParams::read(Lexer & lex)
1204 {
1205         if (lex.eatLine())
1206                 index = lex.getDocString();
1207         else
1208                 index = from_ascii("idx");
1209         if (lex.checkFor("range")) {
1210                 string st = lex.getString();
1211                 if (lex.eatLine()) {
1212                         st = lex.getString();
1213                         range = insetindexpagerangetranslator().find(lex.getString());
1214                 }
1215         }
1216         if (lex.checkFor("pageformat") && lex.eatLine()) {
1217                 pagefmt = lex.getString();
1218         }
1219 }
1220
1221
1222 /////////////////////////////////////////////////////////////////////
1223 //
1224 // InsetPrintIndex
1225 //
1226 ///////////////////////////////////////////////////////////////////////
1227
1228 InsetPrintIndex::InsetPrintIndex(Buffer * buf, InsetCommandParams const & p)
1229         : InsetCommand(buf, p)
1230 {}
1231
1232
1233 ParamInfo const & InsetPrintIndex::findInfo(string const & /* cmdName */)
1234 {
1235         static ParamInfo param_info_;
1236         if (param_info_.empty()) {
1237                 param_info_.add("type", ParamInfo::LATEX_OPTIONAL,
1238                                 ParamInfo::HANDLING_ESCAPE);
1239                 param_info_.add("name", ParamInfo::LATEX_OPTIONAL,
1240                                 ParamInfo::HANDLING_LATEXIFY);
1241                 param_info_.add("literal", ParamInfo::LYX_INTERNAL);
1242         }
1243         return param_info_;
1244 }
1245
1246
1247 docstring InsetPrintIndex::screenLabel() const
1248 {
1249         bool const printall = suffixIs(getCmdName(), '*');
1250         bool const multind = buffer().masterBuffer()->params().use_indices;
1251         if ((!multind
1252              && getParam("type") == from_ascii("idx"))
1253             || (getParam("type").empty() && !printall))
1254                 return _("Index");
1255         Buffer const & realbuffer = *buffer().masterBuffer();
1256         IndicesList const & indiceslist = realbuffer.params().indiceslist();
1257         Index const * index = indiceslist.findShortcut(getParam("type"));
1258         if (!index && !printall)
1259                 return _("Unknown index type!");
1260         docstring res = printall ? _("All indexes") : index->index();
1261         if (!multind)
1262                 res += " (" + _("non-active") + ")";
1263         else if (contains(getCmdName(), "printsubindex"))
1264                 res += " (" + _("subindex") + ")";
1265         return res;
1266 }
1267
1268
1269 bool InsetPrintIndex::isCompatibleCommand(string const & s)
1270 {
1271         return s == "printindex" || s == "printsubindex"
1272                 || s == "printindex*" || s == "printsubindex*";
1273 }
1274
1275
1276 void InsetPrintIndex::doDispatch(Cursor & cur, FuncRequest & cmd)
1277 {
1278         switch (cmd.action()) {
1279
1280         case LFUN_INSET_MODIFY: {
1281                 if (cmd.argument() == from_ascii("toggle-subindex")) {
1282                         string scmd = getCmdName();
1283                         if (contains(scmd, "printindex"))
1284                                 scmd = subst(scmd, "printindex", "printsubindex");
1285                         else
1286                                 scmd = subst(scmd, "printsubindex", "printindex");
1287                         cur.recordUndo();
1288                         setCmdName(scmd);
1289                         break;
1290                 } else if (cmd.argument() == from_ascii("check-printindex*")) {
1291                         string scmd = getCmdName();
1292                         if (suffixIs(scmd, '*'))
1293                                 break;
1294                         scmd += '*';
1295                         cur.recordUndo();
1296                         setParam("type", docstring());
1297                         setCmdName(scmd);
1298                         break;
1299                 }
1300                 InsetCommandParams p(INDEX_PRINT_CODE);
1301                 // FIXME UNICODE
1302                 InsetCommand::string2params(to_utf8(cmd.argument()), p);
1303                 if (p.getCmdName().empty()) {
1304                         cur.noScreenUpdate();
1305                         break;
1306                 }
1307                 cur.recordUndo();
1308                 setParams(p);
1309                 break;
1310         }
1311
1312         default:
1313                 InsetCommand::doDispatch(cur, cmd);
1314                 break;
1315         }
1316 }
1317
1318
1319 bool InsetPrintIndex::getStatus(Cursor & cur, FuncRequest const & cmd,
1320         FuncStatus & status) const
1321 {
1322         switch (cmd.action()) {
1323
1324         case LFUN_INSET_MODIFY: {
1325                 if (cmd.argument() == from_ascii("toggle-subindex")) {
1326                         status.setEnabled(buffer().masterBuffer()->params().use_indices);
1327                         status.setOnOff(contains(getCmdName(), "printsubindex"));
1328                         return true;
1329                 } else if (cmd.argument() == from_ascii("check-printindex*")) {
1330                         status.setEnabled(buffer().masterBuffer()->params().use_indices);
1331                         status.setOnOff(suffixIs(getCmdName(), '*'));
1332                         return true;
1333                 } if (cmd.getArg(0) == "index_print"
1334                     && cmd.getArg(1) == "CommandInset") {
1335                         InsetCommandParams p(INDEX_PRINT_CODE);
1336                         InsetCommand::string2params(to_utf8(cmd.argument()), p);
1337                         if (suffixIs(p.getCmdName(), '*')) {
1338                                 status.setEnabled(true);
1339                                 status.setOnOff(false);
1340                                 return true;
1341                         }
1342                         Buffer const & realbuffer = *buffer().masterBuffer();
1343                         IndicesList const & indiceslist =
1344                                 realbuffer.params().indiceslist();
1345                         Index const * index = indiceslist.findShortcut(p["type"]);
1346                         status.setEnabled(index != 0);
1347                         status.setOnOff(p["type"] == getParam("type"));
1348                         return true;
1349                 } else
1350                         return InsetCommand::getStatus(cur, cmd, status);
1351         }
1352
1353         case LFUN_INSET_DIALOG_UPDATE: {
1354                 status.setEnabled(buffer().masterBuffer()->params().use_indices);
1355                 return true;
1356         }
1357
1358         default:
1359                 return InsetCommand::getStatus(cur, cmd, status);
1360         }
1361 }
1362
1363
1364 void InsetPrintIndex::updateBuffer(ParIterator const &, UpdateType, bool const /*deleted*/)
1365 {
1366         Index const * index =
1367                 buffer().masterParams().indiceslist().findShortcut(getParam("type"));
1368         if (index)
1369                 setParam("name", index->index());
1370 }
1371
1372
1373 void InsetPrintIndex::latex(otexstream & os, OutputParams const & runparams_in) const
1374 {
1375         if (!buffer().masterBuffer()->params().use_indices) {
1376                 if (getParam("type") == from_ascii("idx"))
1377                         os << "\\printindex" << termcmd;
1378                 return;
1379         }
1380         OutputParams runparams = runparams_in;
1381         os << getCommand(runparams);
1382 }
1383
1384
1385 void InsetPrintIndex::validate(LaTeXFeatures & features) const
1386 {
1387         features.require("makeidx");
1388         if (buffer().masterBuffer()->params().use_indices)
1389                 features.require("splitidx");
1390         InsetCommand::validate(features);
1391 }
1392
1393
1394 string InsetPrintIndex::contextMenuName() const
1395 {
1396         return buffer().masterBuffer()->params().use_indices ?
1397                 "context-indexprint" : string();
1398 }
1399
1400
1401 bool InsetPrintIndex::hasSettings() const
1402 {
1403         return buffer().masterBuffer()->params().use_indices;
1404 }
1405
1406
1407 class IndexEntry
1408 {
1409 public:
1410         /// Builds an entry for the index.
1411         IndexEntry(const InsetIndex * inset, OutputParams const * runparams) : inset_(inset), runparams_(runparams)
1412         {
1413                 LASSERT(runparams, return);
1414
1415                 // Convert the inset as text. The resulting text usually only contains an XHTML anchor (<a id='...'/>) and text.
1416                 odocstringstream entry;
1417                 OutputParams ours = *runparams;
1418                 ours.for_toc = false;
1419                 inset_->plaintext(entry, ours);
1420                 entry_ = entry.str();
1421
1422                 // Determine in which index this entry belongs to.
1423                 if (inset_->buffer().masterBuffer()->params().use_indices) {
1424                         index_ = inset_->params_.index;
1425                 }
1426
1427                 // Attempt parsing the inset.
1428                 if (isModern())
1429                         parseAsModern();
1430                 else
1431                         parseAsLegacy();
1432         }
1433
1434         /// When parsing this entry, some errors may be found; they are reported as a single string.
1435         // It is up to the caller to send this string to LYXERR and the output file, as needed.
1436         const docstring & output_error() const
1437         {
1438                 return output_error_;
1439         }
1440
1441         void output_error(XMLStream xs) const
1442         {
1443                 LYXERR0(output_error());
1444                 xs << XMLStream::ESCAPE_NONE << (from_utf8("<!-- Output Error: ") + output_error() + from_utf8(" -->\n"));
1445         }
1446
1447
1448 private:
1449         bool isModern()
1450         {
1451 #ifdef LYX_INSET_INDEX_DEBUG
1452                 std::cout << to_utf8(entry_) << std::endl;
1453 #endif // LYX_INSET_INDEX_DEBUG
1454
1455                 // If a modern parameter is present, this is definitely a modern index inset. Similarly, if it contains the
1456                 // usual LaTeX symbols (!|@), then it is definitely a legacy index inset. Otherwise, if it has features of
1457                 // neither, it is both: consider this is a modern inset, to trigger the least complex code. Mixing both types
1458                 // is not allowed (i.e. behaviour is undefined).
1459                 const bool is_definitely_modern = inset_->hasSortKey() || inset_->hasSeeRef() || inset_->hasSubentries()
1460                                             || inset_->params_.range != InsetIndexParams::PageRange::None;
1461                 const bool is_definitely_legacy = entry_.find('@') != std::string::npos
1462                                 || entry_.find('|') != std::string::npos || entry_.find('!') != std::string::npos;
1463
1464                 if (is_definitely_legacy && is_definitely_modern)
1465                         output_error_ += from_utf8("Mix of index properties and raw LaTeX index commands is unsupported. ");
1466
1467                 // Truth table:
1468                 // - is_definitely_modern == true:
1469                 //   - is_definitely_legacy == true: error (return whatever)
1470                 //   - is_definitely_legacy == false: return modern
1471                 // - is_definitely_modern == false:
1472                 //   - is_definitely_legacy == true: return legacy
1473                 //   - is_definitely_legacy == false: return modern
1474                 return !is_definitely_legacy;
1475         }
1476
1477         void parseAsModern()
1478         {
1479                 LASSERT(runparams_, return);
1480
1481                 if (inset_->hasSortKey()) {
1482                         sort_as_ = inset_->getSortkeyAsText(*runparams_);
1483                 }
1484
1485                 terms_ = inset_->getSubentriesAsText(*runparams_);
1486                 // The main term is not present in the vector, as it's not a subentry. The main index term is inserted raw in
1487                 // the index inset. Considering that the user either uses the new or the legacy mechanism, the main term is the
1488                 // full string within this inset (i.e. without the subinsets).
1489                 terms_.insert(terms_.begin(), inset_->getMainSubentryAsText(*runparams_));
1490
1491                 has_start_range_ = inset_->params_.range == InsetIndexParams::PageRange::Start;
1492                 has_end_range_ = inset_->params_.range == InsetIndexParams::PageRange::End;
1493
1494                 see_ = inset_->getSeeAsText(*runparams_);
1495                 see_alsoes_ = inset_->getSeeAlsoesAsText(*runparams_);
1496         }
1497
1498         void parseAsLegacy() {
1499                 // Determine if some features are known not to be supported. For now, this is only formatting like
1500                 // \index{alpha@\textbf{alpha}} or \index{alpha@$\alpha$}.
1501                 // @ is supported, but only for sorting, without specific formatting.
1502                 if (entry_.find(from_utf8("@\\")) != lyx::docstring::npos) {
1503                         output_error_ += from_utf8("Unsupported feature: an index entry contains an @\\. "
1504                                                    "Complete entry: \"") + entry_ + from_utf8("\". ");
1505                 }
1506                 if (entry_.find(from_utf8("@$")) != lyx::docstring::npos) {
1507                         output_error_ += from_utf8("Unsupported feature: an index entry contains an @$. "
1508                                                    "Complete entry: \"") + entry_ + from_utf8("\". ");
1509                 }
1510
1511                 // Split the string into its main constituents: terms, and command (see, see also, range).
1512                 size_t positionVerticalBar = entry_.find(from_ascii("|")); // What comes before | is (sub)(sub)entries.
1513                 docstring indexTerms = entry_.substr(0, positionVerticalBar);
1514                 docstring command;
1515                 if (positionVerticalBar != lyx::docstring::npos) {
1516                         command = entry_.substr(positionVerticalBar + 1);
1517                 }
1518
1519                 // Handle sorting issues, with @.
1520                 vector<docstring> sortingElements = getVectorFromString(indexTerms, from_ascii("@"), false);
1521                 if (sortingElements.size() == 2) {
1522                         sort_as_ = sortingElements[0];
1523                         indexTerms = sortingElements[1];
1524                 }
1525
1526                 // Handle entries, subentries, and subsubentries.
1527                 terms_ = getVectorFromString(indexTerms, from_ascii("!"), false);
1528
1529                 // Handle ranges. Happily, (| and |) can only be at the end of the string!
1530                 has_start_range_ = entry_.find(from_ascii("|(")) != lyx::docstring::npos;
1531                 has_end_range_ = entry_.find(from_ascii("|)")) != lyx::docstring::npos;
1532
1533                 // - Remove the ranges from the command if they do not appear at the beginning.
1534                 size_t range_index = 0;
1535                 while ((range_index = command.find(from_utf8("|("), range_index)) != std::string::npos)
1536                         command.erase(range_index, 1);
1537                 range_index = 0;
1538                 while ((range_index = command.find(from_utf8("|)"), range_index)) != std::string::npos)
1539                         command.erase(range_index, 1);
1540
1541                 // - Remove the ranges when they are the only vertical bar in the complete string.
1542                 if (command[0] == '(' || command[0] == ')')
1543                         command.erase(0, 1);
1544
1545                 // Handle see and seealso. As "see" is a prefix of "seealso", the order of the comparisons is important.
1546                 // Both commands are mutually exclusive!
1547                 if (command.substr(0, 3) == "see") {
1548                         // Unescape brackets.
1549                         size_t index_argument_begin = 0;
1550                         while ((index_argument_begin = command.find(from_utf8("\\{"), index_argument_begin)) != std::string::npos)
1551                                 command.erase(index_argument_begin, 1);
1552                         size_t index_argument_end = 0;
1553                         while ((index_argument_end = command.find(from_utf8("\\}"), index_argument_end)) != std::string::npos)
1554                                 command.erase(index_argument_end, 1);
1555
1556                         // Retrieve the part between brackets, and remove the complete seealso.
1557                         size_t position_opening_bracket = command.find(from_ascii("{"));
1558                         size_t position_closing_bracket = command.find(from_ascii("}"));
1559                         docstring argument = command.substr(position_opening_bracket + 1,
1560                                                                                                 position_closing_bracket - position_opening_bracket - 1);
1561
1562                         // Parse the argument of referenced entries (or a single one for see).
1563                         if (command.substr(0, 7) == "seealso") {
1564                                 see_alsoes_ = getVectorFromString(argument, from_ascii(","), false);
1565                         } else {
1566                                 see_ = argument;
1567
1568                                 if (see_.find(from_ascii(",")) != std::string::npos) {
1569                                         output_error_ += from_utf8("Several index_argument_end terms found as \"see\"! Only one is "
1570                                                                    "acceptable. Complete entry: \"") + entry_ + from_utf8("\". ");
1571                                 }
1572                         }
1573
1574                         // Remove the complete see/seealso from the commands, in case there is something else to parse.
1575                         command = command.substr(position_closing_bracket + 1);
1576                 }
1577
1578                 // Some parts of the strings are not parsed, as they do not have anything matching in DocBook or XHTML:
1579                 // things like formatting the entry or the page number, other strings for sorting.
1580                 // https://wiki.lyx.org/Tips/Indexing
1581                 // If there are such things in the index entry, then this code may miserably fail. For example, for
1582                 // "Peter|(textbf", no range will be detected.
1583                 if (!command.empty()) {
1584                         output_error_ += from_utf8("Unsupported feature: an index entry contains a | with an unsupported command, ")
1585                                          + command + from_utf8(". Complete entry: \"") + entry_ + from_utf8("\". ");
1586                 }
1587         }
1588
1589 public:
1590         int level() const {
1591                 return terms_.size();
1592         }
1593
1594         const std::vector<docstring>& terms() const {
1595                 return terms_;
1596         }
1597
1598         std::vector<docstring>& terms() {
1599                 return terms_;
1600         }
1601
1602         const InsetIndex* inset() const {
1603                 return inset_;
1604         }
1605
1606 private:
1607         // Input inset. These should only be used when parsing the inset (either parseAsModern or parseAsLegacy, called in
1608         // the constructor).
1609         const InsetIndex * inset_;
1610         OutputParams const * runparams_;
1611         docstring entry_;
1612         docstring index_; // Useful when there are multiple indices in the same document.
1613
1614         // Errors, concatenated as a single string, available as soon as parsing is done, const afterwards (i.e. once
1615         // constructor is done).
1616         docstring output_error_;
1617
1618         // Parsed index entry.
1619         std::vector<docstring> terms_; // Up to three entries, in general.
1620         docstring sort_as_;
1621         docstring command_;
1622         bool has_start_range_;
1623         bool has_end_range_;
1624         docstring see_;
1625         vector<docstring> see_alsoes_;
1626
1627         // Operators used for sorting entries (alphabetical order).
1628         friend bool operator<(IndexEntry const & lhs, IndexEntry const & rhs);
1629 };
1630
1631 bool operator<(IndexEntry const & lhs, IndexEntry const & rhs)
1632 {
1633         if (lhs.terms_.empty())
1634                 return false;
1635
1636         for (unsigned i = 0; i < min(rhs.terms_.size(), lhs.terms_.size()); ++i) {
1637                 int comp = compare_no_case(lhs.terms_[i], rhs.terms_[i]);
1638                 if (comp != 0)
1639                         return comp < 0;
1640         }
1641         return false;
1642 }
1643
1644
1645 namespace {
1646 std::string generateCssClassAtDepth(unsigned depth) {
1647         std::string css_class = "entry";
1648
1649         while (depth > 0) {
1650                 depth -= 1;
1651                 css_class.insert(0, "sub");
1652         }
1653
1654         return css_class;
1655 }
1656
1657 struct IndexNode {
1658         std::vector<IndexEntry> entries;
1659         std::vector<IndexNode*> children;
1660 };
1661
1662 docstring termAtLevel(const IndexNode* node, unsigned depth)
1663 {
1664         // The typical entry has a depth of 1 to 3: the call stack would then be at most 4 (due to the root node). This
1665         // function could be made constant time by copying the term in each node, but that would make data duplication that
1666         // may fall out of sync; the performance benefit would probably be negligible.
1667         if (!node->entries.empty()) {
1668                 LASSERT(node->entries.begin()->terms().size() >= depth + 1, return from_ascii(""));
1669                 return node->entries.begin()->terms()[depth];
1670         }
1671
1672         if (!node->children.empty()) {
1673                 return termAtLevel(*node->children.begin(), depth);
1674         }
1675
1676         LASSERT(false, return from_ascii(""));
1677 }
1678
1679 void insertIntoNode(const IndexEntry& entry, IndexNode* node, unsigned depth = 0)
1680 {
1681         // depth == 0 is for the root, not yet the index, hence the increase when going to vector size.
1682         for (IndexNode* child : node->children) {
1683                 if (entry.terms()[depth] == termAtLevel(child, depth)) {
1684                         if (depth + 1 == entry.terms().size()) { // == child.entries.begin()->terms().size()
1685                                 // All term entries match: it's an entry.
1686                                 child->entries.emplace_back(entry);
1687                                 return;
1688                         } else {
1689                                 insertIntoNode(entry, child, depth + 1);
1690                                 return;
1691                         }
1692                 }
1693         }
1694
1695         // Out of the loop: no matching child found, create a new (possibly nested) child for this entry. Due to the
1696         // possibility of nestedness, only insert the current entry when the right level is reached. This is needed if the
1697         // first entry for a word has several levels that never appeared.
1698         // In particular, this case is called for the first entry.
1699         IndexNode* new_node = node;
1700         do {
1701                 new_node->children.emplace_back(new IndexNode{{}, {}});
1702                 new_node = new_node->children.back();
1703                 depth += 1;
1704         } while (depth + 1 <= entry.terms().size()); // depth == 0: root node, no text associated.
1705         new_node->entries.emplace_back(entry);
1706 }
1707
1708 IndexNode* buildIndexTree(vector<IndexEntry>& entries)
1709 {
1710         // Sort the entries, first on the main entry, then the subentry, then the subsubentry,
1711         // thanks to the implementation of operator<.
1712         // If this operation is not performed, the algorithm below is no more correct (and ensuring that it works with
1713         // unsorted entries would make its complexity blow up).
1714         stable_sort(entries.begin(), entries.end());
1715
1716         // Cook the index into a nice tree data structure: entries at a given level in the index as a node, with subentries
1717         // as children.
1718         auto* index_root = new IndexNode{{}, {}};
1719         for (const IndexEntry& entry : entries) {
1720                 insertIntoNode(entry, index_root);
1721         }
1722
1723         return index_root;
1724 }
1725
1726 void outputIndexPage(XMLStream & xs, const IndexNode* root_node, unsigned depth = 0) // NOLINT(misc-no-recursion)
1727 {
1728         LASSERT(root_node->entries.size() + root_node->children.size() > 0, return);
1729
1730         xs << xml::StartTag("li", "class='" + generateCssClassAtDepth(depth) + "'");
1731         xs << xml::CR();
1732         xs << XMLStream::ESCAPE_NONE << termAtLevel(root_node, depth);
1733         // By tree assumption, all the entries at this node have the same set of terms.
1734
1735         if (!root_node->entries.empty()) {
1736                 xs << XMLStream::ESCAPE_NONE << " &#8212; "; // Em dash, i.e. long (---).
1737                 unsigned entry_number = 1;
1738
1739                 auto writeLinkToEntry = [&xs](const IndexEntry &entry, unsigned entry_number) {
1740                         std::string const link_attr = "href='#" + entry.inset()->paragraphs()[0].magicLabel() + "'";
1741                         xs << xml::StartTag("a", link_attr);
1742                         xs << from_ascii(std::to_string(entry_number));
1743                         xs << xml::EndTag("a");
1744                 };
1745
1746                 for (unsigned i = 0; i < root_node->entries.size(); ++i) {
1747                         const IndexEntry &entry = root_node->entries[i];
1748
1749                         switch (entry.inset()->params().range) {
1750                                 case InsetIndexParams::PageRange::None:
1751                                         writeLinkToEntry(entry, entry_number);
1752                                         break;
1753                                 case InsetIndexParams::PageRange::Start: {
1754                                         // Try to find the end of the range, if it is just after. Otherwise, the output will be slightly
1755                                         // scrambled, but understandable. Doing better would mean implementing more of the indexing logic here
1756                                         // and more complex indexing here (skipping the end is not just incrementing i). Worst case output:
1757                                         //     1--, 2, --3
1758                                         const bool nextEntryIsEnd = i + 1 < root_node->entries.size() &&
1759                                                                     root_node->entries[i + 1].inset()->params().range ==
1760                                                                     InsetIndexParams::PageRange::End;
1761                                         // No need to check if both entries are for the same terms: they are in the same IndexNode.
1762
1763                                         writeLinkToEntry(entry, entry_number);
1764                                         xs << XMLStream::ESCAPE_NONE << " &#8211; "; // En dash, i.e. semi-long (--).
1765
1766                                         if (nextEntryIsEnd) {
1767                                                 // Skip the next entry in the loop, write it right now, after the dash.
1768                                                 entry_number += 1;
1769                                                 i += 1;
1770                                                 writeLinkToEntry(root_node->entries[i], entry_number);
1771                                         }
1772                                 }
1773                                         break;
1774                                 case InsetIndexParams::PageRange::End:
1775                                         // This range end was not caught by the range start, do it now to avoid losing content.
1776                                         xs << XMLStream::ESCAPE_NONE << " &#8211; "; // En dash, i.e. semi-long (--).
1777                                         writeLinkToEntry(root_node->entries[i], entry_number);
1778                         }
1779
1780                         if (i < root_node->entries.size() - 1) {
1781                                 xs << ", ";
1782                         }
1783                         entry_number += 1;
1784                 }
1785         }
1786
1787         if (!root_node->entries.empty() && !root_node->children.empty()) {
1788                 xs << xml::CR();
1789         }
1790
1791         if (!root_node->children.empty()) {
1792                 xs << xml::StartTag("ul", "class='" + generateCssClassAtDepth(depth) + "'");
1793                 xs << xml::CR();
1794
1795                 for (const IndexNode* child : root_node->children) {
1796                         outputIndexPage(xs, child, depth + 1);
1797                 }
1798
1799                 xs << xml::EndTag("ul");
1800                 xs << xml::CR();
1801         }
1802
1803         xs << xml::EndTag("li");
1804         xs << xml::CR();
1805 }
1806
1807 #ifdef LYX_INSET_INDEX_DEBUG
1808 void printTree(const IndexNode* root_node, unsigned depth = 0)
1809 {
1810         static const std::string pattern = "    ";
1811         std::string prefix;
1812         for (unsigned i = 0; i < depth; ++i) {
1813                 prefix += pattern;
1814         }
1815         const std::string prefix_long = prefix + pattern + pattern;
1816
1817         docstring term_at_level;
1818         if (depth == 0) {
1819                 // The root has no term.
1820                 std::cout << "<ROOT>" << std::endl;
1821         } else {
1822                 LASSERT(depth - 1 <= 10, return); // Check for overflows.
1823                 term_at_level = termAtLevel(root_node, depth - 1);
1824                 std::cout << prefix << to_utf8(term_at_level) << " (x " << std::to_string(root_node->entries.size()) << ")"
1825                           << std::endl;
1826         }
1827
1828         for (const IndexEntry& entry : root_node->entries) {
1829                 if (entry.terms().size() != depth) {
1830                         std::cout << prefix_long << "ERROR: an entry doesn't have the same number of terms" << std::endl;
1831                 }
1832                 if (depth > 0 && entry.terms()[depth - 1] != term_at_level) {
1833                         std::cout << prefix_long << "ERROR: an entry doesn't have the right term at depth " << std::to_string(depth)
1834                                 << std::endl;
1835                 }
1836         }
1837
1838         for (const IndexNode* node : root_node->children) {
1839                 printTree(node, depth + 1);
1840         }
1841 }
1842 #endif // LYX_INSET_INDEX_DEBUG
1843 }
1844
1845
1846 docstring InsetPrintIndex::xhtml(XMLStream &, OutputParams const & op) const
1847 {
1848         BufferParams const & bp = buffer().masterBuffer()->params();
1849
1850         shared_ptr<Toc const> toc = buffer().tocBackend().toc("index");
1851         if (toc->empty())
1852                 return docstring();
1853
1854         // Collect the index entries in a form we can use them.
1855         vector<IndexEntry> entries;
1856         const docstring & indexType = params().getParamOr("type", from_ascii("idx"));
1857         for (const TocItem& item : *toc) {
1858                 const auto* inset = static_cast<const InsetIndex*>(&(item.dit().inset()));
1859                 if (item.isOutput() && inset->params().index == indexType)
1860                         entries.emplace_back(IndexEntry{inset, &op});
1861         }
1862
1863         // If all the index entries are in notes or not displayed, get out sooner.
1864         if (entries.empty())
1865                 return docstring();
1866
1867         const IndexNode* index_root = buildIndexTree(entries);
1868 #ifdef LYX_INSET_INDEX_DEBUG
1869         printTree(index_root);
1870 #endif
1871
1872         // Start generating the XHTML index.
1873         Layout const & lay = bp.documentClass().htmlTOCLayout();
1874         string const & tocclass = lay.defaultCSSClass();
1875         string const tocattr = "class='index " + tocclass + "'";
1876         docstring const indexName = params().getParamOr("name", from_ascii("Index"));
1877
1878         // we'll use our own stream, because we are going to defer everything.
1879         // that's how we deal with the fact that we're probably inside a standard
1880         // paragraph, and we don't want to be.
1881         odocstringstream ods;
1882         XMLStream xs(ods);
1883
1884         xs << xml::StartTag("div", tocattr);
1885         xs << xml::CR();
1886         xs << xml::StartTag(lay.htmltag(), lay.htmlattr());
1887         xs << translateIfPossible(indexName, op.local_font->language()->lang());
1888         xs << xml::EndTag(lay.htmltag());
1889         xs << xml::CR();
1890         xs << xml::StartTag("ul", "class='main'");
1891         xs << xml::CR();
1892
1893         LASSERT(index_root->entries.empty(), return docstring()); // No index entry should have zero terms.
1894         for (const IndexNode* node : index_root->children) {
1895                 outputIndexPage(xs, node);
1896         }
1897
1898         xs << xml::EndTag("ul");
1899         xs << xml::CR();
1900         xs << xml::EndTag("div");
1901
1902         return ods.str();
1903 }
1904
1905 } // namespace lyx