]> git.lyx.org Git - features.git/blob - src/insets/InsetIndex.cpp
839d09472a42744375bcc4fa9264cd34e9e398d6
[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         default:
696                 return InsetCollapsible::getStatus(cur, cmd, flag);
697         }
698 }
699
700
701 void InsetIndex::getSortkey(otexstream & os, OutputParams const & runparams) const
702 {
703         Paragraph const & par = paragraphs().front();
704         InsetList::const_iterator it = par.insetList().begin();
705         for (; it != par.insetList().end(); ++it) {
706                 Inset & inset = *it->inset;
707                 if (inset.lyxCode() == INDEXMACRO_SORTKEY_CODE) {
708                         InsetIndexMacro const & iim =
709                                 static_cast<InsetIndexMacro const &>(inset);
710                         iim.getLatex(os, runparams);
711                         return;
712                 }
713         }
714 }
715
716
717 docstring InsetIndex::getSortkeyAsText(OutputParams const & runparams) const
718 {
719         Paragraph const & par = paragraphs().front();
720         InsetList::const_iterator it = par.insetList().begin();
721         for (; it != par.insetList().end(); ++it) {
722                 Inset & inset = *it->inset;
723                 if (inset.lyxCode() == INDEXMACRO_SORTKEY_CODE) {
724                         otexstringstream os;
725                         InsetIndexMacro const & iim =
726                                 static_cast<InsetIndexMacro const &>(inset);
727                         iim.getLatex(os, runparams);
728                         return os.str();
729                 }
730         }
731         return from_ascii("");
732 }
733
734
735 void InsetIndex::emptySubentriesWarning(docstring const & mainentry) const
736 {
737         // Empty subentries crash makeindex. So warn and ignore this.
738         TeXErrors terr;
739         ErrorList & errorList = buffer().errorList("Export");
740         docstring const s = bformat(_("There is an empty index subentry in the entry '%1$s'.\n"
741                                       "It will be ignored in the output."), mainentry);
742         Paragraph const & par = buffer().paragraphs().front();
743         errorList.push_back(ErrorItem(_("Empty index subentry!"), s,
744                                       {par.id(), 0}, {par.id(), -1}));
745         buffer().bufferErrors(terr, errorList);
746 }
747
748
749 void InsetIndex::getSubentries(otexstream & os, OutputParams const & runparams,
750                                docstring const & mainentry) const
751 {
752         Paragraph const & par = paragraphs().front();
753         InsetList::const_iterator it = par.insetList().begin();
754         int i = 0;
755         for (; it != par.insetList().end(); ++it) {
756                 Inset & inset = *it->inset;
757                 if (inset.lyxCode() == INDEXMACRO_CODE) {
758                         InsetIndexMacro const & iim =
759                                 static_cast<InsetIndexMacro const &>(inset);
760                         if (iim.params().type == InsetIndexMacroParams::Subentry) {
761                                 if (iim.hasNoContent()) {
762                                         emptySubentriesWarning(mainentry);
763                                         continue;
764                                 }
765                                 ++i;
766                                 if (i > 2)
767                                         return;
768                                 os << "!";
769                                 iim.getLatex(os, runparams);
770                         }
771                 }
772         }
773 }
774
775
776 std::vector<docstring> InsetIndex::getSubentriesAsText(OutputParams const & runparams,
777                                                        bool const asLabel) const
778 {
779         std::vector<docstring> subentries;
780
781         Paragraph const & par = paragraphs().front();
782         InsetList::const_iterator it = par.insetList().begin();
783         int i = 0;
784         for (; it != par.insetList().end(); ++it) {
785                 Inset & inset = *it->inset;
786                 if (inset.lyxCode() == INDEXMACRO_CODE) {
787                         InsetIndexMacro const & iim =
788                                 static_cast<InsetIndexMacro const &>(inset);
789                         if (iim.params().type == InsetIndexMacroParams::Subentry) {
790                                 ++i;
791                                 if (i > 2)
792                                         break;
793                                 if (asLabel) {
794                                         docstring const l;
795                                         docstring const sl = iim.getNewLabel(l);
796                                         subentries.emplace_back(sl);
797                                 } else {
798                                         otexstringstream os;
799                                         iim.getLatex(os, runparams);
800                                         subentries.emplace_back(os.str());
801                                 }
802                         }
803                 }
804         }
805
806         return subentries;
807 }
808
809
810 docstring InsetIndex::getMainSubentryAsText(OutputParams const & runparams) const
811 {
812         otexstringstream os;
813         InsetText::latex(os, runparams);
814         return os.str();
815 }
816
817
818 void InsetIndex::getSeeRefs(otexstream & os, OutputParams const & runparams) const
819 {
820         Paragraph const & par = paragraphs().front();
821         InsetList::const_iterator it = par.insetList().begin();
822         for (; it != par.insetList().end(); ++it) {
823                 Inset & inset = *it->inset;
824                 if (inset.lyxCode() == INDEXMACRO_CODE) {
825                         InsetIndexMacro const & iim =
826                                 static_cast<InsetIndexMacro const &>(inset);
827                         if (iim.params().type == InsetIndexMacroParams::See
828                             || iim.params().type == InsetIndexMacroParams::Seealso) {
829                                 iim.getLatex(os, runparams);
830                                 return;
831                         }
832                 }
833         }
834 }
835
836
837 docstring InsetIndex::getSeeAsText(OutputParams const & runparams,
838                                    bool const asLabel) const
839 {
840         Paragraph const & par = paragraphs().front();
841         InsetList::const_iterator it = par.insetList().begin();
842         for (; it != par.insetList().end(); ++it) {
843                 Inset & inset = *it->inset;
844                 if (inset.lyxCode() == INDEXMACRO_CODE) {
845                         InsetIndexMacro const & iim =
846                                 static_cast<InsetIndexMacro const &>(inset);
847                         if (iim.params().type == InsetIndexMacroParams::See) {
848                                 if (asLabel) {
849                                         docstring const l;
850                                         return iim.getNewLabel(l);
851                                 } else {
852                                         otexstringstream os;
853                                         iim.getLatex(os, runparams);
854                                         return os.str();
855                                 }
856                         }
857                 }
858         }
859         return from_ascii("");
860 }
861
862
863 std::vector<docstring> InsetIndex::getSeeAlsoesAsText(OutputParams const & runparams,
864                                                       bool const asLabel) const
865 {
866         std::vector<docstring> seeAlsoes;
867
868         Paragraph const & par = paragraphs().front();
869         InsetList::const_iterator it = par.insetList().begin();
870         for (; it != par.insetList().end(); ++it) {
871                 Inset & inset = *it->inset;
872                 if (inset.lyxCode() == INDEXMACRO_CODE) {
873                         InsetIndexMacro const & iim =
874                                 static_cast<InsetIndexMacro const &>(inset);
875                         if (iim.params().type == InsetIndexMacroParams::Seealso) {
876                                 if (asLabel) {
877                                         docstring const l;
878                                         seeAlsoes.emplace_back(iim.getNewLabel(l));
879                                 } else {
880                                         otexstringstream os;
881                                         iim.getLatex(os, runparams);
882                                         seeAlsoes.emplace_back(os.str());
883                                 }
884                         }
885                 }
886         }
887
888         return seeAlsoes;
889 }
890
891
892 namespace {
893
894 bool hasInsetWithCode(const InsetIndex * const inset_index, const InsetCode code,
895                                           const std::set<InsetIndexMacroParams::Type> types = {})
896 {
897         Paragraph const & par = inset_index->paragraphs().front();
898         InsetList::const_iterator it = par.insetList().begin();
899         for (; it != par.insetList().end(); ++it) {
900                 Inset & inset = *it->inset;
901                 if (inset.lyxCode() == code) {
902                         if (types.empty())
903                                 return true;
904
905                         LASSERT(code == INDEXMACRO_CODE, return false);
906                         InsetIndexMacro const & iim =
907                                         static_cast<InsetIndexMacro const &>(inset);
908                         if (types.find(iim.params().type) != types.end())
909                                 return true;
910                 }
911         }
912         return false;
913 }
914
915 } // namespace
916
917
918 bool InsetIndex::hasSubentries() const
919 {
920         return hasInsetWithCode(this, INDEXMACRO_CODE, {InsetIndexMacroParams::Subentry});
921 }
922
923
924 bool InsetIndex::hasSeeRef() const
925 {
926         return hasInsetWithCode(this, INDEXMACRO_CODE, {InsetIndexMacroParams::See, InsetIndexMacroParams::Seealso});
927 }
928
929
930 bool InsetIndex::hasSortKey() const
931 {
932         return hasInsetWithCode(this, INDEXMACRO_SORTKEY_CODE);
933 }
934
935
936 bool InsetIndex::macrosPossible(string const type) const
937 {
938         if (type != "see" && type != "seealso"
939             && type != "sortkey" && type != "subentry")
940                 return false;
941
942         Paragraph const & par = paragraphs().front();
943         InsetList::const_iterator it = par.insetList().begin();
944         int subidxs = 0;
945         for (; it != par.insetList().end(); ++it) {
946                 Inset & inset = *it->inset;
947                 if (type == "sortkey" && inset.lyxCode() == INDEXMACRO_SORTKEY_CODE)
948                         return false;
949                 if (inset.lyxCode() == INDEXMACRO_CODE) {
950                         InsetIndexMacro const & iim = static_cast<InsetIndexMacro const &>(inset);
951                         if ((type == "see" || type == "seealso")
952                              && (iim.params().type == InsetIndexMacroParams::See
953                                  || iim.params().type == InsetIndexMacroParams::Seealso))
954                                 return false;
955                         if (type == "subentry"
956                              && iim.params().type == InsetIndexMacroParams::Subentry) {
957                                 ++subidxs;
958                                 if (subidxs > 1)
959                                         return false;
960                         }
961                 }
962         }
963         return true;
964 }
965
966
967 ColorCode InsetIndex::labelColor() const
968 {
969         if (params_.index.empty() || params_.index == from_ascii("idx"))
970                 return InsetCollapsible::labelColor();
971         // FIXME UNICODE
972         ColorCode c = lcolor.getFromLyXName(to_utf8(params_.index)
973                                             + "@" + buffer().fileName().absFileName());
974         if (c == Color_none)
975                 c = InsetCollapsible::labelColor();
976         return c;
977 }
978
979
980 docstring InsetIndex::toolTip(BufferView const &, int, int) const
981 {
982         docstring tip = _("Index Entry");
983         if (buffer().params().use_indices && !params_.index.empty()) {
984                 Buffer const & realbuffer = *buffer().masterBuffer();
985                 IndicesList const & indiceslist = realbuffer.params().indiceslist();
986                 tip += " (";
987                 Index const * index = indiceslist.findShortcut(params_.index);
988                 if (!index)
989                         tip += _("unknown type!");
990                 else
991                         tip += index->index();
992                 tip += ")";
993         }
994         tip += ": ";
995         docstring res = toolTipText(tip);
996         if (!insetindexpagerangetranslator_loc().find(params_.range).empty())
997                 res += "\n" + insetindexpagerangetranslator_loc().find(params_.range);
998         if (!params_.pagefmt.empty() && params_.pagefmt != "default") {
999                 res += "\n" + _("Pagination format:") + " ";
1000                 if (params_.pagefmt == "textbf")
1001                         res += _("bold");
1002                 else if (params_.pagefmt == "textit")
1003                         res += _("italic");
1004                 else if (params_.pagefmt == "emph")
1005                         res += _("emphasized");
1006                 else
1007                         res += from_utf8(params_.pagefmt);
1008         }
1009         return res;
1010 }
1011
1012
1013 docstring const InsetIndex::buttonLabel(BufferView const & bv) const
1014 {
1015         InsetLayout const & il = getLayout();
1016         docstring label = translateIfPossible(il.labelstring());
1017
1018         if (buffer().params().use_indices && !params_.index.empty()) {
1019                 Buffer const & realbuffer = *buffer().masterBuffer();
1020                 IndicesList const & indiceslist = realbuffer.params().indiceslist();
1021                 label += " (";
1022                 Index const * index = indiceslist.findShortcut(params_.index);
1023                 if (!index)
1024                         label += _("unknown type!");
1025                 else
1026                         label += index->index();
1027                 label += ")";
1028         }
1029
1030         docstring res;
1031         if (!il.contentaslabel() || geometry(bv) != ButtonOnly)
1032                 res = label;
1033         else {
1034                 res = getNewLabel(label);
1035                 OutputParams const rp(0);
1036                 vector<docstring> sublbls = getSubentriesAsText(rp, true);
1037                 for (auto const & sublbl : sublbls) {
1038                         res += " " + docstring(1, char_type(0x2023));// TRIANGULAR BULLET
1039                         res += " " + sublbl;
1040                 }
1041                 docstring see = getSeeAsText(rp, true);
1042                 if (see.empty() && !getSeeAlsoesAsText(rp, true).empty())
1043                         see = getSeeAlsoesAsText(rp, true).front();
1044                 if (!see.empty()) {
1045                         res += " " + docstring(1, char_type(0x261e));// WHITE RIGHT POINTING INDEX
1046                         res += " " + see;
1047                 }
1048         }
1049         if (!insetindexpagerangetranslator_latex().find(params_.range).empty())
1050                 res += " " + from_ascii(insetindexpagerangetranslator_latex().find(params_.range));
1051         return res;
1052 }
1053
1054
1055 void InsetIndex::write(ostream & os) const
1056 {
1057         os << to_utf8(layoutName());
1058         params_.write(os);
1059         InsetCollapsible::write(os);
1060 }
1061
1062
1063 void InsetIndex::read(Lexer & lex)
1064 {
1065         params_.read(lex);
1066         InsetCollapsible::read(lex);
1067 }
1068
1069
1070 string InsetIndex::params2string(InsetIndexParams const & params)
1071 {
1072         ostringstream data;
1073         data << "index";
1074         params.write(data);
1075         return data.str();
1076 }
1077
1078
1079 void InsetIndex::string2params(string const & in, InsetIndexParams & params)
1080 {
1081         params = InsetIndexParams();
1082         if (in.empty())
1083                 return;
1084
1085         istringstream data(in);
1086         Lexer lex;
1087         lex.setStream(data);
1088         lex.setContext("InsetIndex::string2params");
1089         lex >> "index";
1090         params.read(lex);
1091 }
1092
1093
1094 void InsetIndex::addToToc(DocIterator const & cpit, bool output_active,
1095                                                   UpdateType utype, TocBackend & backend) const
1096 {
1097         DocIterator pit = cpit;
1098         pit.push_back(CursorSlice(const_cast<InsetIndex &>(*this)));
1099         docstring str;
1100         InsetLayout const & il = getLayout();
1101         docstring label = translateIfPossible(il.labelstring());
1102         if (!il.contentaslabel())
1103                 str = label;
1104         else {
1105                 str = getNewLabel(label);
1106                 OutputParams const rp(0);
1107                 vector<docstring> sublbls = getSubentriesAsText(rp, true);
1108                 for (auto const & sublbl : sublbls) {
1109                         str += " " + docstring(1, char_type(0x2023));// TRIANGULAR BULLET
1110                         str += " " + sublbl;
1111                 }
1112                 docstring see = getSeeAsText(rp, true);
1113                 if (see.empty() && !getSeeAlsoesAsText(rp, true).empty())
1114                         see = getSeeAlsoesAsText(rp, true).front();
1115                 if (!see.empty()) {
1116                         str += " " + docstring(1, char_type(0x261e));// WHITE RIGHT POINTING INDEX
1117                         str += " " + see;
1118                 }
1119         }
1120         string type = "index";
1121         if (buffer().masterBuffer()->params().use_indices)
1122                 type += ":" + to_utf8(params_.index);
1123         TocBuilder & b = backend.builder(type);
1124         b.pushItem(pit, str, output_active);
1125         // Proceed with the rest of the inset.
1126         InsetCollapsible::addToToc(cpit, output_active, utype, backend);
1127         b.pop();
1128 }
1129
1130
1131 void InsetIndex::validate(LaTeXFeatures & features) const
1132 {
1133         if (buffer().masterBuffer()->params().use_indices
1134             && !params_.index.empty()
1135             && params_.index != "idx")
1136                 features.require("splitidx");
1137         InsetCollapsible::validate(features);
1138 }
1139
1140
1141 string InsetIndex::contextMenuName() const
1142 {
1143         return "context-index";
1144 }
1145
1146
1147 string InsetIndex::contextMenu(BufferView const & bv, int x, int y) const
1148 {
1149         // We override the implementation of InsetCollapsible,
1150         // because we have eytra entries.
1151         string owncm = "context-edit-index;";
1152         return owncm + InsetCollapsible::contextMenu(bv, x, y);
1153 }
1154
1155
1156 bool InsetIndex::hasSettings() const
1157 {
1158         return true;
1159 }
1160
1161
1162 bool InsetIndex::insetAllowed(InsetCode code) const
1163 {
1164         switch (code) {
1165         case INDEXMACRO_CODE:
1166         case INDEXMACRO_SORTKEY_CODE:
1167                 return true;
1168         case INDEX_CODE:
1169                 return false;
1170         default:
1171                 return InsetCollapsible::insetAllowed(code);
1172         }
1173 }
1174
1175
1176 /////////////////////////////////////////////////////////////////////
1177 //
1178 // InsetIndexParams
1179 //
1180 ///////////////////////////////////////////////////////////////////////
1181
1182
1183 void InsetIndexParams::write(ostream & os) const
1184 {
1185         os << ' ';
1186         if (!index.empty())
1187                 os << to_utf8(index);
1188         else
1189                 os << "idx";
1190         os << '\n';
1191         os << "range "
1192            << insetindexpagerangetranslator().find(range)
1193            << '\n';
1194         os << "pageformat "
1195            << pagefmt
1196            << '\n';
1197 }
1198
1199
1200 void InsetIndexParams::read(Lexer & lex)
1201 {
1202         if (lex.eatLine())
1203                 index = lex.getDocString();
1204         else
1205                 index = from_ascii("idx");
1206         if (lex.checkFor("range")) {
1207                 string st = lex.getString();
1208                 if (lex.eatLine()) {
1209                         st = lex.getString();
1210                         range = insetindexpagerangetranslator().find(lex.getString());
1211                 }
1212         }
1213         if (lex.checkFor("pageformat") && lex.eatLine()) {
1214                 pagefmt = lex.getString();
1215         }
1216 }
1217
1218
1219 /////////////////////////////////////////////////////////////////////
1220 //
1221 // InsetPrintIndex
1222 //
1223 ///////////////////////////////////////////////////////////////////////
1224
1225 InsetPrintIndex::InsetPrintIndex(Buffer * buf, InsetCommandParams const & p)
1226         : InsetCommand(buf, p)
1227 {}
1228
1229
1230 ParamInfo const & InsetPrintIndex::findInfo(string const & /* cmdName */)
1231 {
1232         static ParamInfo param_info_;
1233         if (param_info_.empty()) {
1234                 param_info_.add("type", ParamInfo::LATEX_OPTIONAL,
1235                                 ParamInfo::HANDLING_ESCAPE);
1236                 param_info_.add("name", ParamInfo::LATEX_OPTIONAL,
1237                                 ParamInfo::HANDLING_LATEXIFY);
1238                 param_info_.add("literal", ParamInfo::LYX_INTERNAL);
1239         }
1240         return param_info_;
1241 }
1242
1243
1244 docstring InsetPrintIndex::screenLabel() const
1245 {
1246         bool const printall = suffixIs(getCmdName(), '*');
1247         bool const multind = buffer().masterBuffer()->params().use_indices;
1248         if ((!multind
1249              && getParam("type") == from_ascii("idx"))
1250             || (getParam("type").empty() && !printall))
1251                 return _("Index");
1252         Buffer const & realbuffer = *buffer().masterBuffer();
1253         IndicesList const & indiceslist = realbuffer.params().indiceslist();
1254         Index const * index = indiceslist.findShortcut(getParam("type"));
1255         if (!index && !printall)
1256                 return _("Unknown index type!");
1257         docstring res = printall ? _("All indexes") : index->index();
1258         if (!multind)
1259                 res += " (" + _("non-active") + ")";
1260         else if (contains(getCmdName(), "printsubindex"))
1261                 res += " (" + _("subindex") + ")";
1262         return res;
1263 }
1264
1265
1266 bool InsetPrintIndex::isCompatibleCommand(string const & s)
1267 {
1268         return s == "printindex" || s == "printsubindex"
1269                 || s == "printindex*" || s == "printsubindex*";
1270 }
1271
1272
1273 void InsetPrintIndex::doDispatch(Cursor & cur, FuncRequest & cmd)
1274 {
1275         switch (cmd.action()) {
1276
1277         case LFUN_INSET_MODIFY: {
1278                 if (cmd.argument() == from_ascii("toggle-subindex")) {
1279                         string scmd = getCmdName();
1280                         if (contains(scmd, "printindex"))
1281                                 scmd = subst(scmd, "printindex", "printsubindex");
1282                         else
1283                                 scmd = subst(scmd, "printsubindex", "printindex");
1284                         cur.recordUndo();
1285                         setCmdName(scmd);
1286                         break;
1287                 } else if (cmd.argument() == from_ascii("check-printindex*")) {
1288                         string scmd = getCmdName();
1289                         if (suffixIs(scmd, '*'))
1290                                 break;
1291                         scmd += '*';
1292                         cur.recordUndo();
1293                         setParam("type", docstring());
1294                         setCmdName(scmd);
1295                         break;
1296                 }
1297                 InsetCommandParams p(INDEX_PRINT_CODE);
1298                 // FIXME UNICODE
1299                 InsetCommand::string2params(to_utf8(cmd.argument()), p);
1300                 if (p.getCmdName().empty()) {
1301                         cur.noScreenUpdate();
1302                         break;
1303                 }
1304                 cur.recordUndo();
1305                 setParams(p);
1306                 break;
1307         }
1308
1309         default:
1310                 InsetCommand::doDispatch(cur, cmd);
1311                 break;
1312         }
1313 }
1314
1315
1316 bool InsetPrintIndex::getStatus(Cursor & cur, FuncRequest const & cmd,
1317         FuncStatus & status) const
1318 {
1319         switch (cmd.action()) {
1320
1321         case LFUN_INSET_MODIFY: {
1322                 if (cmd.argument() == from_ascii("toggle-subindex")) {
1323                         status.setEnabled(buffer().masterBuffer()->params().use_indices);
1324                         status.setOnOff(contains(getCmdName(), "printsubindex"));
1325                         return true;
1326                 } else if (cmd.argument() == from_ascii("check-printindex*")) {
1327                         status.setEnabled(buffer().masterBuffer()->params().use_indices);
1328                         status.setOnOff(suffixIs(getCmdName(), '*'));
1329                         return true;
1330                 } if (cmd.getArg(0) == "index_print"
1331                     && cmd.getArg(1) == "CommandInset") {
1332                         InsetCommandParams p(INDEX_PRINT_CODE);
1333                         InsetCommand::string2params(to_utf8(cmd.argument()), p);
1334                         if (suffixIs(p.getCmdName(), '*')) {
1335                                 status.setEnabled(true);
1336                                 status.setOnOff(false);
1337                                 return true;
1338                         }
1339                         Buffer const & realbuffer = *buffer().masterBuffer();
1340                         IndicesList const & indiceslist =
1341                                 realbuffer.params().indiceslist();
1342                         Index const * index = indiceslist.findShortcut(p["type"]);
1343                         status.setEnabled(index != 0);
1344                         status.setOnOff(p["type"] == getParam("type"));
1345                         return true;
1346                 } else
1347                         return InsetCommand::getStatus(cur, cmd, status);
1348         }
1349
1350         case LFUN_INSET_DIALOG_UPDATE: {
1351                 status.setEnabled(buffer().masterBuffer()->params().use_indices);
1352                 return true;
1353         }
1354
1355         default:
1356                 return InsetCommand::getStatus(cur, cmd, status);
1357         }
1358 }
1359
1360
1361 void InsetPrintIndex::updateBuffer(ParIterator const &, UpdateType, bool const /*deleted*/)
1362 {
1363         Index const * index =
1364                 buffer().masterParams().indiceslist().findShortcut(getParam("type"));
1365         if (index)
1366                 setParam("name", index->index());
1367 }
1368
1369
1370 void InsetPrintIndex::latex(otexstream & os, OutputParams const & runparams_in) const
1371 {
1372         if (!buffer().masterBuffer()->params().use_indices) {
1373                 if (getParam("type") == from_ascii("idx"))
1374                         os << "\\printindex" << termcmd;
1375                 return;
1376         }
1377         OutputParams runparams = runparams_in;
1378         os << getCommand(runparams);
1379 }
1380
1381
1382 void InsetPrintIndex::validate(LaTeXFeatures & features) const
1383 {
1384         features.require("makeidx");
1385         if (buffer().masterBuffer()->params().use_indices)
1386                 features.require("splitidx");
1387         InsetCommand::validate(features);
1388 }
1389
1390
1391 string InsetPrintIndex::contextMenuName() const
1392 {
1393         return buffer().masterBuffer()->params().use_indices ?
1394                 "context-indexprint" : string();
1395 }
1396
1397
1398 bool InsetPrintIndex::hasSettings() const
1399 {
1400         return buffer().masterBuffer()->params().use_indices;
1401 }
1402
1403
1404 class IndexEntry
1405 {
1406 public:
1407         /// Builds an entry for the index.
1408         IndexEntry(const InsetIndex * inset, OutputParams const * runparams) : inset_(inset), runparams_(runparams)
1409         {
1410                 LASSERT(runparams, return);
1411
1412                 // Convert the inset as text. The resulting text usually only contains an XHTML anchor (<a id='...'/>) and text.
1413                 odocstringstream entry;
1414                 OutputParams ours = *runparams;
1415                 ours.for_toc = false;
1416                 inset_->plaintext(entry, ours);
1417                 entry_ = entry.str();
1418
1419                 // Determine in which index this entry belongs to.
1420                 if (inset_->buffer().masterBuffer()->params().use_indices) {
1421                         index_ = inset_->params_.index;
1422                 }
1423
1424                 // Attempt parsing the inset.
1425                 if (isModern())
1426                         parseAsModern();
1427                 else
1428                         parseAsLegacy();
1429         }
1430
1431         /// When parsing this entry, some errors may be found; they are reported as a single string.
1432         // It is up to the caller to send this string to LYXERR and the output file, as needed.
1433         const docstring & output_error() const
1434         {
1435                 return output_error_;
1436         }
1437
1438         void output_error(XMLStream xs) const
1439         {
1440                 LYXERR0(output_error());
1441                 xs << XMLStream::ESCAPE_NONE << (from_utf8("<!-- Output Error: ") + output_error() + from_utf8(" -->\n"));
1442         }
1443
1444
1445 private:
1446         bool isModern()
1447         {
1448                 std::cout << to_utf8(entry_) << std::endl;
1449
1450                 // If a modern parameter is present, this is definitely a modern index inset. Similarly, if it contains the
1451                 // usual LaTeX symbols (!|@), then it is definitely a legacy index inset. Otherwise, if it has features of
1452                 // neither, it is both: consider this is a modern inset, to trigger the least complex code. Mixing both types
1453                 // is not allowed (i.e. behaviour is undefined).
1454                 const bool is_definitely_modern = inset_->hasSortKey() || inset_->hasSeeRef() || inset_->hasSubentries()
1455                                             || inset_->params_.range != InsetIndexParams::PageRange::None;
1456                 const bool is_definitely_legacy = entry_.find('@') != std::string::npos
1457                                 || entry_.find('|') != std::string::npos || entry_.find('!') != std::string::npos;
1458
1459                 if (is_definitely_legacy && is_definitely_modern)
1460                         output_error_ += from_utf8("Mix of index properties and raw LaTeX index commands is unsupported. ");
1461
1462                 // Truth table:
1463                 // - is_definitely_modern == true:
1464                 //   - is_definitely_legacy == true: error (return whatever)
1465                 //   - is_definitely_legacy == false: return modern
1466                 // - is_definitely_modern == false:
1467                 //   - is_definitely_legacy == true: return legacy
1468                 //   - is_definitely_legacy == false: return modern
1469                 return !is_definitely_legacy;
1470         }
1471
1472         void parseAsModern()
1473         {
1474                 LASSERT(runparams_, return);
1475
1476                 if (inset_->hasSortKey()) {
1477                         sort_as_ = inset_->getSortkeyAsText(*runparams_);
1478                 }
1479
1480                 terms_ = inset_->getSubentriesAsText(*runparams_);
1481                 // The main term is not present in the vector, as it's not a subentry. The main index term is inserted raw in
1482                 // the index inset. Considering that the user either uses the new or the legacy mechanism, the main term is the
1483                 // full string within this inset (i.e. without the subinsets).
1484                 terms_.insert(terms_.begin(), inset_->getMainSubentryAsText(*runparams_));
1485
1486                 has_start_range_ = inset_->params_.range == InsetIndexParams::PageRange::Start;
1487                 has_end_range_ = inset_->params_.range == InsetIndexParams::PageRange::End;
1488
1489                 see_ = inset_->getSeeAsText(*runparams_);
1490                 see_alsoes_ = inset_->getSeeAlsoesAsText(*runparams_);
1491         }
1492
1493         void parseAsLegacy() {
1494                 // Determine if some features are known not to be supported. For now, this is only formatting like
1495                 // \index{alpha@\textbf{alpha}} or \index{alpha@$\alpha$}.
1496                 // @ is supported, but only for sorting, without specific formatting.
1497                 if (entry_.find(from_utf8("@\\")) != lyx::docstring::npos) {
1498                         output_error_ += from_utf8("Unsupported feature: an index entry contains an @\\. "
1499                                                    "Complete entry: \"") + entry_ + from_utf8("\". ");
1500                 }
1501                 if (entry_.find(from_utf8("@$")) != lyx::docstring::npos) {
1502                         output_error_ += from_utf8("Unsupported feature: an index entry contains an @$. "
1503                                                    "Complete entry: \"") + entry_ + from_utf8("\". ");
1504                 }
1505
1506                 // Split the string into its main constituents: terms, and command (see, see also, range).
1507                 size_t positionVerticalBar = entry_.find(from_ascii("|")); // What comes before | is (sub)(sub)entries.
1508                 docstring indexTerms = entry_.substr(0, positionVerticalBar);
1509                 docstring command;
1510                 if (positionVerticalBar != lyx::docstring::npos) {
1511                         command = entry_.substr(positionVerticalBar + 1);
1512                 }
1513
1514                 // Handle sorting issues, with @.
1515                 vector<docstring> sortingElements = getVectorFromString(indexTerms, from_ascii("@"), false);
1516                 if (sortingElements.size() == 2) {
1517                         sort_as_ = sortingElements[0];
1518                         indexTerms = sortingElements[1];
1519                 }
1520
1521                 // Handle entries, subentries, and subsubentries.
1522                 terms_ = getVectorFromString(indexTerms, from_ascii("!"), false);
1523
1524                 // Handle ranges. Happily, (| and |) can only be at the end of the string!
1525                 has_start_range_ = entry_.find(from_ascii("|(")) != lyx::docstring::npos;
1526                 has_end_range_ = entry_.find(from_ascii("|)")) != lyx::docstring::npos;
1527
1528                 // - Remove the ranges from the command if they do not appear at the beginning.
1529                 size_t range_index = 0;
1530                 while ((range_index = command.find(from_utf8("|("), range_index)) != std::string::npos)
1531                         command.erase(range_index, 1);
1532                 range_index = 0;
1533                 while ((range_index = command.find(from_utf8("|)"), range_index)) != std::string::npos)
1534                         command.erase(range_index, 1);
1535
1536                 // - Remove the ranges when they are the only vertical bar in the complete string.
1537                 if (command[0] == '(' || command[0] == ')')
1538                         command.erase(0, 1);
1539
1540                 // Handle see and seealso. As "see" is a prefix of "seealso", the order of the comparisons is important.
1541                 // Both commands are mutually exclusive!
1542                 if (command.substr(0, 3) == "see") {
1543                         // Unescape brackets.
1544                         size_t index_argument_begin = 0;
1545                         while ((index_argument_begin = command.find(from_utf8("\\{"), index_argument_begin)) != std::string::npos)
1546                                 command.erase(index_argument_begin, 1);
1547                         size_t index_argument_end = 0;
1548                         while ((index_argument_end = command.find(from_utf8("\\}"), index_argument_end)) != std::string::npos)
1549                                 command.erase(index_argument_end, 1);
1550
1551                         // Retrieve the part between brackets, and remove the complete seealso.
1552                         size_t position_opening_bracket = command.find(from_ascii("{"));
1553                         size_t position_closing_bracket = command.find(from_ascii("}"));
1554                         docstring argument = command.substr(position_opening_bracket + 1,
1555                                                                                                 position_closing_bracket - position_opening_bracket - 1);
1556
1557                         // Parse the argument of referenced entries (or a single one for see).
1558                         if (command.substr(0, 7) == "seealso") {
1559                                 see_alsoes_ = getVectorFromString(argument, from_ascii(","), false);
1560                         } else {
1561                                 see_ = argument;
1562
1563                                 if (see_.find(from_ascii(",")) != std::string::npos) {
1564                                         output_error_ += from_utf8("Several index_argument_end terms found as \"see\"! Only one is "
1565                                                                    "acceptable. Complete entry: \"") + entry_ + from_utf8("\". ");
1566                                 }
1567                         }
1568
1569                         // Remove the complete see/seealso from the commands, in case there is something else to parse.
1570                         command = command.substr(position_closing_bracket + 1);
1571                 }
1572
1573                 // Some parts of the strings are not parsed, as they do not have anything matching in DocBook or XHTML:
1574                 // things like formatting the entry or the page number, other strings for sorting.
1575                 // https://wiki.lyx.org/Tips/Indexing
1576                 // If there are such things in the index entry, then this code may miserably fail. For example, for
1577                 // "Peter|(textbf", no range will be detected.
1578                 if (!command.empty()) {
1579                         output_error_ += from_utf8("Unsupported feature: an index entry contains a | with an unsupported command, ")
1580                                          + command + from_utf8(". Complete entry: \"") + entry_ + from_utf8("\". ");
1581                 }
1582         }
1583
1584 public:
1585         int level() const {
1586                 return terms_.size();
1587         }
1588
1589         const std::vector<docstring>& terms() const {
1590                 return terms_;
1591         }
1592
1593         std::vector<docstring>& terms() {
1594                 return terms_;
1595         }
1596
1597         const InsetIndex* inset() const {
1598                 return inset_;
1599         }
1600
1601 private:
1602         // Input inset. These should only be used when parsing the inset (either parseAsModern or parseAsLegacy, called in
1603         // the constructor).
1604         const InsetIndex * inset_;
1605         OutputParams const * runparams_;
1606         docstring entry_;
1607         docstring index_; // Useful when there are multiple indices in the same document.
1608
1609         // Errors, concatenated as a single string, available as soon as parsing is done, const afterwards (i.e. once
1610         // constructor is done).
1611         docstring output_error_;
1612
1613         // Parsed index entry.
1614         std::vector<docstring> terms_; // Up to three entries, in general.
1615         docstring sort_as_;
1616         docstring command_;
1617         bool has_start_range_;
1618         bool has_end_range_;
1619         docstring see_;
1620         vector<docstring> see_alsoes_;
1621
1622         // Operators used for sorting entries (alphabetical order).
1623         friend bool operator<(IndexEntry const & lhs, IndexEntry const & rhs);
1624 };
1625
1626 bool operator<(IndexEntry const & lhs, IndexEntry const & rhs)
1627 {
1628         if (lhs.terms_.empty())
1629                 return false;
1630
1631         for (unsigned i = 0; i < min(rhs.terms_.size(), lhs.terms_.size()); ++i) {
1632                 int comp = compare_no_case(lhs.terms_[i], rhs.terms_[i]);
1633                 if (comp != 0)
1634                         return comp < 0;
1635         }
1636         return false;
1637 }
1638
1639
1640 namespace {
1641 std::string generateCssClassAtDepth(unsigned depth) {
1642         std::string css_class = "entry";
1643
1644         while (depth > 0) {
1645                 depth -= 1;
1646                 css_class.insert(0, "sub");
1647         }
1648
1649         return css_class;
1650 }
1651
1652 struct IndexNode {
1653         std::vector<IndexEntry> entries;
1654         std::vector<IndexNode*> children;
1655 };
1656
1657 docstring termAtLevel(const IndexNode* node, unsigned depth)
1658 {
1659         // 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
1660         // function could be made constant time by copying the term in each node, but that would make data duplication that
1661         // may fall out of sync; the performance benefit would probably be negligible.
1662         if (!node->entries.empty()) {
1663                 LASSERT(node->entries.begin()->terms().size() >= depth + 1, return from_ascii(""));
1664                 return node->entries.begin()->terms()[depth];
1665         }
1666
1667         if (!node->children.empty()) {
1668                 return termAtLevel(*node->children.begin(), depth);
1669         }
1670
1671         LASSERT(false, return from_ascii(""));
1672 }
1673
1674 void insertIntoNode(const IndexEntry& entry, IndexNode* node, unsigned depth = 0)
1675 {
1676         // depth == 0 is for the root, not yet the index, hence the increase when going to vector size.
1677         for (IndexNode* child : node->children) {
1678                 if (entry.terms()[depth] == termAtLevel(child, depth)) {
1679                         if (depth + 1 == entry.terms().size()) { // == child.entries.begin()->terms().size()
1680                                 // All term entries match: it's an entry.
1681                                 child->entries.emplace_back(entry);
1682                                 return;
1683                         } else {
1684                                 insertIntoNode(entry, child, depth + 1);
1685                                 return;
1686                         }
1687                 }
1688         }
1689
1690         // Out of the loop: no matching child found, create a new (possibly nested) child for this entry. Due to the
1691         // possibility of nestedness, only insert the current entry when the right level is reached. This is needed if the
1692         // first entry for a word has several levels that never appeared.
1693         // In particular, this case is called for the first entry.
1694         IndexNode* new_node = node;
1695         do {
1696                 new_node->children.emplace_back(new IndexNode{{}, {}});
1697                 new_node = new_node->children.back();
1698                 depth += 1;
1699         } while (depth + 1 <= entry.terms().size()); // depth == 0: root node, no text associated.
1700         new_node->entries.emplace_back(entry);
1701 }
1702
1703 IndexNode* buildIndexTree(vector<IndexEntry>& entries)
1704 {
1705         // Sort the entries, first on the main entry, then the subentry, then the subsubentry,
1706         // thanks to the implementation of operator<.
1707         // If this operation is not performed, the algorithm below is no more correct (and ensuring that it works with
1708         // unsorted entries would make its complexity blow up).
1709         stable_sort(entries.begin(), entries.end());
1710
1711         // Cook the index into a nice tree data structure: entries at a given level in the index as a node, with subentries
1712         // as children.
1713         auto* index_root = new IndexNode{{}, {}};
1714         for (const IndexEntry& entry : entries) {
1715                 insertIntoNode(entry, index_root);
1716         }
1717
1718         return index_root;
1719 }
1720
1721 void outputIndexPage(XMLStream & xs, const IndexNode* root_node, unsigned depth = 0) // NOLINT(misc-no-recursion)
1722 {
1723         LASSERT(root_node->entries.size() + root_node->children.size() > 0, return);
1724
1725         xs << xml::StartTag("li", "class='" + generateCssClassAtDepth(depth) + "'");
1726         xs << xml::CR();
1727         xs << XMLStream::ESCAPE_NONE << termAtLevel(root_node, depth);
1728         // By tree assumption, all the entries at this node have the same set of terms.
1729
1730         if (!root_node->entries.empty()) {
1731                 xs << XMLStream::ESCAPE_NONE << " &#8212; "; // Em dash, i.e. long (---).
1732                 unsigned entry_number = 1;
1733
1734                 auto writeLinkToEntry = [&xs](const IndexEntry &entry, unsigned entry_number) {
1735                         std::string const link_attr = "href='#" + entry.inset()->paragraphs()[0].magicLabel() + "'";
1736                         xs << xml::StartTag("a", link_attr);
1737                         xs << from_ascii(std::to_string(entry_number));
1738                         xs << xml::EndTag("a");
1739                 };
1740
1741                 for (unsigned i = 0; i < root_node->entries.size(); ++i) {
1742                         const IndexEntry &entry = root_node->entries[i];
1743
1744                         switch (entry.inset()->params().range) {
1745                                 case InsetIndexParams::PageRange::None:
1746                                         writeLinkToEntry(entry, entry_number);
1747                                         break;
1748                                 case InsetIndexParams::PageRange::Start: {
1749                                         // Try to find the end of the range, if it is just after. Otherwise, the output will be slightly
1750                                         // scrambled, but understandable. Doing better would mean implementing more of the indexing logic here
1751                                         // and more complex indexing here (skipping the end is not just incrementing i). Worst case output:
1752                                         //     1--, 2, --3
1753                                         const bool nextEntryIsEnd = i + 1 < root_node->entries.size() &&
1754                                                                     root_node->entries[i + 1].inset()->params().range ==
1755                                                                     InsetIndexParams::PageRange::End;
1756                                         // No need to check if both entries are for the same terms: they are in the same IndexNode.
1757
1758                                         writeLinkToEntry(entry, entry_number);
1759                                         xs << XMLStream::ESCAPE_NONE << " &#8211; "; // En dash, i.e. semi-long (--).
1760
1761                                         if (nextEntryIsEnd) {
1762                                                 // Skip the next entry in the loop, write it right now, after the dash.
1763                                                 entry_number += 1;
1764                                                 i += 1;
1765                                                 writeLinkToEntry(root_node->entries[i], entry_number);
1766                                         }
1767                                 }
1768                                         break;
1769                                 case InsetIndexParams::PageRange::End:
1770                                         // This range end was not caught by the range start, do it now to avoid losing content.
1771                                         xs << XMLStream::ESCAPE_NONE << " &#8211; "; // En dash, i.e. semi-long (--).
1772                                         writeLinkToEntry(root_node->entries[i], entry_number);
1773                         }
1774
1775                         if (i < root_node->entries.size() - 1) {
1776                                 xs << ", ";
1777                         }
1778                         entry_number += 1;
1779                 }
1780         }
1781
1782         if (!root_node->entries.empty() && !root_node->children.empty()) {
1783                 xs << xml::CR();
1784         }
1785
1786         if (!root_node->children.empty()) {
1787                 xs << xml::StartTag("ul", "class='" + generateCssClassAtDepth(depth) + "'");
1788                 xs << xml::CR();
1789
1790                 for (const IndexNode* child : root_node->children) {
1791                         outputIndexPage(xs, child, depth + 1);
1792                 }
1793
1794                 xs << xml::EndTag("ul");
1795                 xs << xml::CR();
1796         }
1797
1798         xs << xml::EndTag("li");
1799         xs << xml::CR();
1800 }
1801
1802 #ifdef LYX_INSET_INDEX_DEBUG
1803 void printTree(const IndexNode* root_node, unsigned depth = 0)
1804 {
1805         static const std::string pattern = "    ";
1806         std::string prefix;
1807         for (unsigned i = 0; i < depth; ++i) {
1808                 prefix += pattern;
1809         }
1810         const std::string prefix_long = prefix + pattern + pattern;
1811
1812         docstring term_at_level;
1813         if (depth == 0) {
1814                 // The root has no term.
1815                 std::cout << "<ROOT>" << std::endl;
1816         } else {
1817                 LASSERT(depth - 1 <= 10, return); // Check for overflows.
1818                 term_at_level = termAtLevel(root_node, depth - 1);
1819                 std::cout << prefix << to_utf8(term_at_level) << " (x " << std::to_string(root_node->entries.size()) << ")"
1820                           << std::endl;
1821         }
1822
1823         for (const IndexEntry& entry : root_node->entries) {
1824                 if (entry.terms().size() != depth) {
1825                         std::cout << prefix_long << "ERROR: an entry doesn't have the same number of terms" << std::endl;
1826                 }
1827                 if (depth > 0 && entry.terms()[depth - 1] != term_at_level) {
1828                         std::cout << prefix_long << "ERROR: an entry doesn't have the right term at depth " << std::to_string(depth)
1829                                 << std::endl;
1830                 }
1831         }
1832
1833         for (const IndexNode* node : root_node->children) {
1834                 printTree(node, depth + 1);
1835         }
1836 }
1837 #endif // LYX_INSET_INDEX_DEBUG
1838 }
1839
1840
1841 docstring InsetPrintIndex::xhtml(XMLStream &, OutputParams const & op) const
1842 {
1843         BufferParams const & bp = buffer().masterBuffer()->params();
1844
1845         shared_ptr<Toc const> toc = buffer().tocBackend().toc("index");
1846         if (toc->empty())
1847                 return docstring();
1848
1849         // Collect the index entries in a form we can use them.
1850         vector<IndexEntry> entries;
1851         const docstring & indexType = params().getParamOr("type", from_ascii("idx"));
1852         for (const TocItem& item : *toc) {
1853                 const auto* inset = static_cast<const InsetIndex*>(&(item.dit().inset()));
1854                 if (item.isOutput() && inset->params().index == indexType)
1855                         entries.emplace_back(IndexEntry{inset, &op});
1856         }
1857
1858         // If all the index entries are in notes or not displayed, get out sooner.
1859         if (entries.empty())
1860                 return docstring();
1861
1862         const IndexNode* index_root = buildIndexTree(entries);
1863 #ifdef LYX_INSET_INDEX_DEBUG
1864         printTree(index_root);
1865 #endif
1866
1867         // Start generating the XHTML index.
1868         Layout const & lay = bp.documentClass().htmlTOCLayout();
1869         string const & tocclass = lay.defaultCSSClass();
1870         string const tocattr = "class='index " + tocclass + "'";
1871         docstring const indexName = params().getParamOr("name", from_ascii("Index"));
1872
1873         // we'll use our own stream, because we are going to defer everything.
1874         // that's how we deal with the fact that we're probably inside a standard
1875         // paragraph, and we don't want to be.
1876         odocstringstream ods;
1877         XMLStream xs(ods);
1878
1879         xs << xml::StartTag("div", tocattr);
1880         xs << xml::CR();
1881         xs << xml::StartTag(lay.htmltag(), lay.htmlattr());
1882         xs << translateIfPossible(indexName, op.local_font->language()->lang());
1883         xs << xml::EndTag(lay.htmltag());
1884         xs << xml::CR();
1885         xs << xml::StartTag("ul", "class='main'");
1886         xs << xml::CR();
1887
1888         LASSERT(index_root->entries.empty(), return docstring()); // No index entry should have zero terms.
1889         for (const IndexNode* node : index_root->children) {
1890                 outputIndexPage(xs, node);
1891         }
1892
1893         xs << xml::EndTag("ul");
1894         xs << xml::CR();
1895         xs << xml::EndTag("div");
1896
1897         return ods.str();
1898 }
1899
1900 } // namespace lyx