]> git.lyx.org Git - lyx.git/blob - src/tex2lyx/text.cpp
tex2lyx: support qualified citation lists (biblatex)
[lyx.git] / src / tex2lyx / text.cpp
1 /**
2  * \file tex2lyx/text.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author André Pönitz
7  * \author Jean-Marc Lasgouttes
8  * \author Uwe Stöhr
9  *
10  * Full author contact details are available in file CREDITS.
11  */
12
13 // {[(
14
15 #include <config.h>
16
17 #include "tex2lyx.h"
18
19 #include "Context.h"
20 #include "Encoding.h"
21 #include "FloatList.h"
22 #include "LaTeXPackages.h"
23 #include "Layout.h"
24 #include "Length.h"
25 #include "Preamble.h"
26
27 #include "insets/ExternalTemplate.h"
28
29 #include "support/lassert.h"
30 #include "support/convert.h"
31 #include "support/FileName.h"
32 #include "support/filetools.h"
33 #include "support/lstrings.h"
34 #include "support/lyxtime.h"
35
36 #include <algorithm>
37 #include <iostream>
38 #include <map>
39 #include <sstream>
40 #include <vector>
41
42 using namespace std;
43 using namespace lyx::support;
44
45 namespace lyx {
46
47
48 namespace {
49
50 void output_arguments(ostream &, Parser &, bool, bool, bool, Context &,
51                       Layout::LaTeXArgMap const &);
52
53 }
54
55
56 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
57                 Context const & context, InsetLayout const * layout)
58 {
59         bool const forcePlainLayout =
60                 layout ? layout->forcePlainLayout() : false;
61         Context newcontext(true, context.textclass);
62         if (forcePlainLayout)
63                 newcontext.layout = &context.textclass.plainLayout();
64         else
65                 newcontext.font = context.font;
66         if (layout)
67                 output_arguments(os, p, outer, false, false, newcontext,
68                                  layout->latexargs());
69         parse_text(p, os, flags, outer, newcontext);
70         if (layout)
71                 output_arguments(os, p, outer, false, true, newcontext,
72                                  layout->postcommandargs());
73         newcontext.check_end_layout(os);
74 }
75
76
77 namespace {
78
79 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
80                 Context const & context, string const & name)
81 {
82         InsetLayout const * layout = 0;
83         DocumentClass::InsetLayouts::const_iterator it =
84                 context.textclass.insetLayouts().find(from_ascii(name));
85         if (it != context.textclass.insetLayouts().end())
86                 layout = &(it->second);
87         parse_text_in_inset(p, os, flags, outer, context, layout);
88 }
89
90 /// parses a paragraph snippet, useful for example for \\emph{...}
91 void parse_text_snippet(Parser & p, ostream & os, unsigned flags, bool outer,
92                 Context & context)
93 {
94         Context newcontext(context);
95         // Don't inherit the paragraph-level extra stuff
96         newcontext.par_extra_stuff.clear();
97         parse_text(p, os, flags, outer, newcontext);
98         // Make sure that we don't create invalid .lyx files
99         context.need_layout = newcontext.need_layout;
100         context.need_end_layout = newcontext.need_end_layout;
101 }
102
103
104 /*!
105  * Thin wrapper around parse_text_snippet() using a string.
106  *
107  * We completely ignore \c context.need_layout and \c context.need_end_layout,
108  * because our return value is not used directly (otherwise the stream version
109  * of parse_text_snippet() could be used). That means that the caller needs
110  * to do layout management manually.
111  * This is intended to parse text that does not create any layout changes.
112  */
113 string parse_text_snippet(Parser & p, unsigned flags, const bool outer,
114                   Context & context)
115 {
116         Context newcontext(context);
117         newcontext.need_layout = false;
118         newcontext.need_end_layout = false;
119         newcontext.new_layout_allowed = false;
120         // Avoid warning by Context::~Context()
121         newcontext.par_extra_stuff.clear();
122         ostringstream os;
123         parse_text_snippet(p, os, flags, outer, newcontext);
124         return os.str();
125 }
126
127 string fboxrule = "";
128 string fboxsep = "";
129 string shadow_size = "";
130
131 char const * const known_ref_commands[] = { "ref", "pageref", "vref",
132  "vpageref", "prettyref", "nameref", "eqref", 0 };
133
134 char const * const known_coded_ref_commands[] = { "ref", "pageref", "vref",
135  "vpageref", "formatted", "nameref", "eqref", 0 };
136
137 char const * const known_refstyle_commands[] = { "algref", "chapref", "corref",
138  "eqref", "enuref", "figref", "fnref", "lemref", "parref", "partref", "propref",
139  "secref", "subsecref", "tabref", "thmref", 0 };
140
141 char const * const known_refstyle_prefixes[] = { "alg", "chap", "cor",
142  "eq", "enu", "fig", "fn", "lem", "par", "part", "prop",
143  "sec", "subsec", "tab", "thm", 0 };
144
145
146 /**
147  * supported CJK encodings
148  * JIS does not work with LyX's encoding conversion
149  */
150 const char * const supported_CJK_encodings[] = {
151 "EUC-JP", "KS", "GB", "UTF8",
152 "Bg5", /*"JIS",*/ "SJIS", 0};
153
154 /**
155  * the same as supported_CJK_encodings with their corresponding LyX language name
156  * FIXME: The mapping "UTF8" => "chinese-traditional" is only correct for files
157  *        created by LyX.
158  * NOTE: "Bg5", "JIS" and "SJIS" are not supported by LyX, on re-export the
159  *       encodings "UTF8", "EUC-JP" and "EUC-JP" will be used.
160  * please keep this in sync with supported_CJK_encodings line by line!
161  */
162 const char * const supported_CJK_languages[] = {
163 "japanese-cjk", "korean", "chinese-simplified", "chinese-traditional",
164 "chinese-traditional", /*"japanese-cjk",*/ "japanese-cjk", 0};
165
166 /*!
167  * natbib commands.
168  * The starred forms are also known except for "citefullauthor",
169  * "citeyear" and "citeyearpar".
170  */
171 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
172 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
173 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
174
175 /*!
176  * jurabib commands.
177  * No starred form other than "cite*" known.
178  */
179 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
180 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
181 // jurabib commands not (yet) supported by LyX:
182 // "fullcite",
183 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
184 // "footciteauthor", "footciteyear", "footciteyearpar",
185 "citefield", "citetitle", 0 };
186
187 /*!
188  * biblatex commands.
189  * Known starred forms: \cite*, \citeauthor*, \Citeauthor*, \parencite*, \citetitle*.
190  */
191 char const * const known_biblatex_commands[] = { "cite", "Cite", "textcite", "Textcite",
192 "parencite", "Parencite", "citeauthor", "Citeauthor", "citeyear", "smartcite", "Smartcite",
193  "footcite", "Footcite", "autocite", "Autocite", "citetitle", "fullcite", "footfullcite",
194 "supercite", "cites", "Cites", "textcites", "Textcites", "parencites", "Parencites",
195 "smartcites", "Smartcites", "autocites", "Autocites", 0 };
196
197 // Whether we need to insert a bibtex inset in a comment
198 bool need_commentbib = false;
199
200 /// LaTeX names for quotes
201 char const * const known_quotes[] = { "dq", "guillemotleft", "flqq", "og",
202 "guillemotright", "frqq", "fg", "glq", "glqq", "textquoteleft", "grq", "grqq",
203 "quotedblbase", "textquotedblleft", "quotesinglbase", "textquoteright", "flq",
204 "guilsinglleft", "frq", "guilsinglright", 0};
205
206 /// the same as known_quotes with .lyx names
207 char const * const known_coded_quotes[] = { "prd", "ard", "ard", "ard",
208 "ald", "ald", "ald", "gls", "gld", "els", "els", "grd",
209 "gld", "grd", "gls", "ers", "fls",
210 "fls", "frs", "frs", 0};
211
212 /// LaTeX names for font sizes
213 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
214 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
215
216 /// the same as known_sizes with .lyx names
217 char const * const known_coded_sizes[] = { "tiny", "scriptsize", "footnotesize",
218 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
219
220 /// LaTeX 2.09 names for font families
221 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
222
223 /// LaTeX names for font families
224 char const * const known_font_families[] = { "rmfamily", "sffamily",
225 "ttfamily", 0};
226
227 /// LaTeX names for font family changing commands
228 char const * const known_text_font_families[] = { "textrm", "textsf",
229 "texttt", 0};
230
231 /// The same as known_old_font_families, known_font_families and
232 /// known_text_font_families with .lyx names
233 char const * const known_coded_font_families[] = { "roman", "sans",
234 "typewriter", 0};
235
236 /// LaTeX 2.09 names for font series
237 char const * const known_old_font_series[] = { "bf", 0};
238
239 /// LaTeX names for font series
240 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
241
242 /// LaTeX names for font series changing commands
243 char const * const known_text_font_series[] = { "textbf", "textmd", 0};
244
245 /// The same as known_old_font_series, known_font_series and
246 /// known_text_font_series with .lyx names
247 char const * const known_coded_font_series[] = { "bold", "medium", 0};
248
249 /// LaTeX 2.09 names for font shapes
250 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
251
252 /// LaTeX names for font shapes
253 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
254 "upshape", 0};
255
256 /// LaTeX names for font shape changing commands
257 char const * const known_text_font_shapes[] = { "textit", "textsl", "textsc",
258 "textup", 0};
259
260 /// The same as known_old_font_shapes, known_font_shapes and
261 /// known_text_font_shapes with .lyx names
262 char const * const known_coded_font_shapes[] = { "italic", "slanted",
263 "smallcaps", "up", 0};
264
265 /// Known special characters which need skip_spaces_braces() afterwards
266 char const * const known_special_chars[] = {"ldots",
267 "lyxarrow", "textcompwordmark",
268 "slash", "textasciitilde", "textasciicircum", "textbackslash",
269 "LyX", "TeX", "LaTeXe",
270 "LaTeX", 0};
271
272 /// special characters from known_special_chars which may have a \\protect before
273 char const * const known_special_protect_chars[] = {"LyX", "TeX",
274 "LaTeXe", "LaTeX", 0};
275
276 /// the same as known_special_chars with .lyx names
277 char const * const known_coded_special_chars[] = {"\\SpecialChar ldots\n",
278 "\\SpecialChar menuseparator\n", "\\SpecialChar ligaturebreak\n",
279 "\\SpecialChar breakableslash\n", "~", "^", "\n\\backslash\n",
280 "\\SpecialChar LyX\n", "\\SpecialChar TeX\n", "\\SpecialChar LaTeX2e\n",
281 "\\SpecialChar LaTeX\n", 0};
282
283 /*!
284  * Graphics file extensions known by the dvips driver of the graphics package.
285  * These extensions are used to complete the filename of an included
286  * graphics file if it does not contain an extension.
287  * The order must be the same that latex uses to find a file, because we
288  * will use the first extension that matches.
289  * This is only an approximation for the common cases. If we would want to
290  * do it right in all cases, we would need to know which graphics driver is
291  * used and know the extensions of every driver of the graphics package.
292  */
293 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
294 "ps.gz", "eps.Z", "ps.Z", 0};
295
296 /*!
297  * Graphics file extensions known by the pdftex driver of the graphics package.
298  * \sa known_dvips_graphics_formats
299  */
300 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
301 "mps", "tif", 0};
302
303 /*!
304  * Known file extensions for TeX files as used by \\include.
305  */
306 char const * const known_tex_extensions[] = {"tex", 0};
307
308 /// spaces known by InsetSpace
309 char const * const known_spaces[] = { " ", "space", ",",
310 "thinspace", "quad", "qquad", "enspace", "enskip",
311 "negthinspace", "negmedspace", "negthickspace", "textvisiblespace",
312 "hfill", "dotfill", "hrulefill", "leftarrowfill", "rightarrowfill",
313 "upbracefill", "downbracefill", 0};
314
315 /// the same as known_spaces with .lyx names
316 char const * const known_coded_spaces[] = { "space{}", "space{}",
317 "thinspace{}", "thinspace{}", "quad{}", "qquad{}", "enspace{}", "enskip{}",
318 "negthinspace{}", "negmedspace{}", "negthickspace{}", "textvisiblespace{}",
319 "hfill{}", "dotfill{}", "hrulefill{}", "leftarrowfill{}", "rightarrowfill{}",
320 "upbracefill{}", "downbracefill{}", 0};
321
322 /// known TIPA combining diacritical marks
323 char const * const known_tipa_marks[] = {"textsubwedge", "textsubumlaut",
324 "textsubtilde", "textseagull", "textsubbridge", "textinvsubbridge",
325 "textsubsquare", "textsubrhalfring", "textsublhalfring", "textsubplus",
326 "textovercross", "textsubarch", "textsuperimposetilde", "textraising",
327 "textlowering", "textadvancing", "textretracting", "textdoublegrave",
328 "texthighrise", "textlowrise", "textrisefall", "textsyllabic",
329 "textsubring", "textsubbar", 0};
330
331 /// TIPA tones that need special handling
332 char const * const known_tones[] = {"15", "51", "45", "12", "454", 0};
333
334 // string to store the float type to be able to determine the type of subfloats
335 string float_type = "";
336
337 // string to store the float status of minted listings
338 string minted_float = "";
339
340 // whether a caption has been parsed for a floating minted listing
341 bool minted_float_has_caption = false;
342
343 // The caption for non-floating minted listings
344 string minted_nonfloat_caption = "";
345
346
347 /// splits "x=z, y=b" into a map and an ordered keyword vector
348 void split_map(string const & s, map<string, string> & res, vector<string> & keys)
349 {
350         vector<string> v;
351         split(s, v);
352         res.clear();
353         keys.resize(v.size());
354         for (size_t i = 0; i < v.size(); ++i) {
355                 size_t const pos   = v[i].find('=');
356                 string const index = trimSpaceAndEol(v[i].substr(0, pos));
357                 string const value = trimSpaceAndEol(v[i].substr(pos + 1, string::npos));
358                 res[index] = value;
359                 keys[i] = index;
360         }
361 }
362
363
364 /*!
365  * Split a LaTeX length into value and unit.
366  * The latter can be a real unit like "pt", or a latex length variable
367  * like "\textwidth". The unit may contain additional stuff like glue
368  * lengths, but we don't care, because such lengths are ERT anyway.
369  * \returns true if \p value and \p unit are valid.
370  */
371 bool splitLatexLength(string const & len, string & value, string & unit)
372 {
373         if (len.empty())
374                 return false;
375         const string::size_type i = len.find_first_not_of(" -+0123456789.,");
376         //'4,5' is a valid LaTeX length number. Change it to '4.5'
377         string const length = subst(len, ',', '.');
378         if (i == string::npos)
379                 return false;
380         if (i == 0) {
381                 if (len[0] == '\\') {
382                         // We had something like \textwidth without a factor
383                         value = "1.0";
384                 } else {
385                         return false;
386                 }
387         } else {
388                 value = trimSpaceAndEol(string(length, 0, i));
389         }
390         if (value == "-")
391                 value = "-1.0";
392         // 'cM' is a valid LaTeX length unit. Change it to 'cm'
393         if (contains(len, '\\'))
394                 unit = trimSpaceAndEol(string(len, i));
395         else
396                 unit = ascii_lowercase(trimSpaceAndEol(string(len, i)));
397         return true;
398 }
399
400
401 /// A simple function to translate a latex length to something LyX can
402 /// understand. Not perfect, but rather best-effort.
403 bool translate_len(string const & length, string & valstring, string & unit)
404 {
405         if (!splitLatexLength(length, valstring, unit))
406                 return false;
407         // LyX uses percent values
408         double value;
409         istringstream iss(valstring);
410         iss >> value;
411         value *= 100;
412         ostringstream oss;
413         oss << value;
414         string const percentval = oss.str();
415         // a normal length
416         if (unit.empty() || unit[0] != '\\')
417                 return true;
418         string::size_type const i = unit.find(' ');
419         string const endlen = (i == string::npos) ? string() : string(unit, i);
420         if (unit == "\\textwidth") {
421                 valstring = percentval;
422                 unit = "text%" + endlen;
423         } else if (unit == "\\columnwidth") {
424                 valstring = percentval;
425                 unit = "col%" + endlen;
426         } else if (unit == "\\paperwidth") {
427                 valstring = percentval;
428                 unit = "page%" + endlen;
429         } else if (unit == "\\linewidth") {
430                 valstring = percentval;
431                 unit = "line%" + endlen;
432         } else if (unit == "\\paperheight") {
433                 valstring = percentval;
434                 unit = "pheight%" + endlen;
435         } else if (unit == "\\textheight") {
436                 valstring = percentval;
437                 unit = "theight%" + endlen;
438         } else if (unit == "\\baselineskip") {
439                 valstring = percentval;
440                 unit = "baselineskip%" + endlen;
441         }
442         return true;
443 }
444
445 } // namespace
446
447
448 string translate_len(string const & length)
449 {
450         string unit;
451         string value;
452         if (translate_len(length, value, unit))
453                 return value + unit;
454         // If the input is invalid, return what we have.
455         return length;
456 }
457
458
459 namespace {
460
461 /*!
462  * Translates a LaTeX length into \p value, \p unit and
463  * \p special parts suitable for a box inset.
464  * The difference from translate_len() is that a box inset knows about
465  * some special "units" that are stored in \p special.
466  */
467 void translate_box_len(string const & length, string & value, string & unit, string & special)
468 {
469         if (translate_len(length, value, unit)) {
470                 if (unit == "\\height" || unit == "\\depth" ||
471                     unit == "\\totalheight" || unit == "\\width") {
472                         special = unit.substr(1);
473                         // The unit is not used, but LyX requires a dummy setting
474                         unit = "in";
475                 } else
476                         special = "none";
477         } else {
478                 value.clear();
479                 unit = length;
480                 special = "none";
481         }
482 }
483
484
485 /*!
486  * Find a file with basename \p name in path \p path and an extension
487  * in \p extensions.
488  */
489 string find_file(string const & name, string const & path,
490                  char const * const * extensions)
491 {
492         for (char const * const * what = extensions; *what; ++what) {
493                 string const trial = addExtension(name, *what);
494                 if (makeAbsPath(trial, path).exists())
495                         return trial;
496         }
497         return string();
498 }
499
500
501 void begin_inset(ostream & os, string const & name)
502 {
503         os << "\n\\begin_inset " << name;
504 }
505
506
507 void begin_command_inset(ostream & os, string const & name,
508                          string const & latexname)
509 {
510         begin_inset(os, "CommandInset ");
511         os << name << "\nLatexCommand " << latexname << '\n';
512 }
513
514
515 void end_inset(ostream & os)
516 {
517         os << "\n\\end_inset\n\n";
518 }
519
520
521 bool skip_braces(Parser & p)
522 {
523         if (p.next_token().cat() != catBegin)
524                 return false;
525         p.get_token();
526         if (p.next_token().cat() == catEnd) {
527                 p.get_token();
528                 return true;
529         }
530         p.putback();
531         return false;
532 }
533
534
535 /// replace LaTeX commands in \p s from the unicodesymbols file with their
536 /// unicode points
537 docstring convert_unicodesymbols(docstring s)
538 {
539         odocstringstream os;
540         for (size_t i = 0; i < s.size();) {
541                 if (s[i] != '\\') {
542                         os.put(s[i++]);
543                         continue;
544                 }
545                 s = s.substr(i);
546                 bool termination;
547                 docstring rem;
548                 set<string> req;
549                 docstring parsed = normalize_c(encodings.fromLaTeXCommand(s,
550                                 Encodings::TEXT_CMD, termination, rem, &req));
551                 set<string>::const_iterator it = req.begin();
552                 set<string>::const_iterator en = req.end();
553                 for (; it != en; ++it)
554                         preamble.registerAutomaticallyLoadedPackage(*it);
555                 os << parsed;
556                 s = rem;
557                 if (s.empty() || s[0] != '\\')
558                         i = 0;
559                 else
560                         i = 1;
561         }
562         return os.str();
563 }
564
565
566 /// try to convert \p s to a valid InsetCommand argument
567 string convert_command_inset_arg(string s)
568 {
569         if (isAscii(s))
570                 // since we don't know the input encoding we can't use from_utf8
571                 s = to_utf8(convert_unicodesymbols(from_ascii(s)));
572         // LyX cannot handle newlines in a latex command
573         return subst(s, "\n", " ");
574 }
575
576
577 void output_ert(ostream & os, string const & s, Context & context)
578 {
579         context.check_layout(os);
580         for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
581                 if (*it == '\\')
582                         os << "\n\\backslash\n";
583                 else if (*it == '\n') {
584                         context.new_paragraph(os);
585                         context.check_layout(os);
586                 } else
587                         os << *it;
588         }
589         context.check_end_layout(os);
590 }
591
592
593 void output_ert_inset(ostream & os, string const & s, Context & context)
594 {
595         // We must have a valid layout before outputting the ERT inset.
596         context.check_layout(os);
597         Context newcontext(true, context.textclass);
598         InsetLayout const & layout = context.textclass.insetLayout(from_ascii("ERT"));
599         if (layout.forcePlainLayout())
600                 newcontext.layout = &context.textclass.plainLayout();
601         begin_inset(os, "ERT");
602         os << "\nstatus collapsed\n";
603         output_ert(os, s, newcontext);
604         end_inset(os);
605 }
606
607
608 void output_comment(Parser & p, ostream & os, string const & s,
609                     Context & context)
610 {
611         if (p.next_token().cat() == catNewline)
612                 output_ert_inset(os, '%' + s, context);
613         else
614                 output_ert_inset(os, '%' + s + '\n', context);
615 }
616
617
618 Layout const * findLayout(TextClass const & textclass, string const & name, bool command)
619 {
620         Layout const * layout = findLayoutWithoutModule(textclass, name, command);
621         if (layout)
622                 return layout;
623         if (checkModule(name, command))
624                 return findLayoutWithoutModule(textclass, name, command);
625         return layout;
626 }
627
628
629 InsetLayout const * findInsetLayout(TextClass const & textclass, string const & name, bool command)
630 {
631         InsetLayout const * insetlayout = findInsetLayoutWithoutModule(textclass, name, command);
632         if (insetlayout)
633                 return insetlayout;
634         if (checkModule(name, command))
635                 return findInsetLayoutWithoutModule(textclass, name, command);
636         return insetlayout;
637 }
638
639
640 void eat_whitespace(Parser &, ostream &, Context &, bool);
641
642
643 /*!
644  * Skips whitespace and braces.
645  * This should be called after a command has been parsed that is not put into
646  * ERT, and where LyX adds "{}" if needed.
647  */
648 void skip_spaces_braces(Parser & p, bool keepws = false)
649 {
650         /* The following four examples produce the same typeset output and
651            should be handled by this function:
652            - abc \j{} xyz
653            - abc \j {} xyz
654            - abc \j
655              {} xyz
656            - abc \j %comment
657              {} xyz
658          */
659         // Unfortunately we need to skip comments, too.
660         // We can't use eat_whitespace since writing them after the {}
661         // results in different output in some cases.
662         bool const skipped_spaces = p.skip_spaces(true);
663         bool const skipped_braces = skip_braces(p);
664         if (keepws && skipped_spaces && !skipped_braces)
665                 // put back the space (it is better handled by check_space)
666                 p.unskip_spaces(true);
667 }
668
669
670 void output_arguments(ostream & os, Parser & p, bool outer, bool need_layout, bool post,
671                       Context & context, Layout::LaTeXArgMap const & latexargs)
672 {
673         if (need_layout) {
674                 context.check_layout(os);
675                 need_layout = false;
676         } else
677                 need_layout = true;
678         int i = 0;
679         Layout::LaTeXArgMap::const_iterator lait = latexargs.begin();
680         Layout::LaTeXArgMap::const_iterator const laend = latexargs.end();
681         for (; lait != laend; ++lait) {
682                 ++i;
683                 eat_whitespace(p, os, context, false);
684                 if (lait->second.mandatory) {
685                         if (p.next_token().cat() != catBegin)
686                                 break;
687                         p.get_token(); // eat '{'
688                         if (need_layout) {
689                                 context.check_layout(os);
690                                 need_layout = false;
691                         }
692                         begin_inset(os, "Argument ");
693                         if (post)
694                                 os << "post:";
695                         os << i << "\nstatus collapsed\n\n";
696                         parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
697                         end_inset(os);
698                 } else {
699                         if (p.next_token().cat() == catEscape ||
700                             p.next_token().character() != '[')
701                                 continue;
702                         p.get_token(); // eat '['
703                         if (need_layout) {
704                                 context.check_layout(os);
705                                 need_layout = false;
706                         }
707                         begin_inset(os, "Argument ");
708                         if (post)
709                                 os << "post:";
710                         os << i << "\nstatus collapsed\n\n";
711                         parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
712                         end_inset(os);
713                 }
714                 eat_whitespace(p, os, context, false);
715         }
716 }
717
718
719 void output_command_layout(ostream & os, Parser & p, bool outer,
720                            Context & parent_context,
721                            Layout const * newlayout)
722 {
723         TeXFont const oldFont = parent_context.font;
724         // save the current font size
725         string const size = oldFont.size;
726         // reset the font size to default, because the font size switches
727         // don't affect section headings and the like
728         parent_context.font.size = Context::normalfont.size;
729         // we only need to write the font change if we have an open layout
730         if (!parent_context.atParagraphStart())
731                 output_font_change(os, oldFont, parent_context.font);
732         parent_context.check_end_layout(os);
733         Context context(true, parent_context.textclass, newlayout,
734                         parent_context.layout, parent_context.font);
735         if (parent_context.deeper_paragraph) {
736                 // We are beginning a nested environment after a
737                 // deeper paragraph inside the outer list environment.
738                 // Therefore we don't need to output a "begin deeper".
739                 context.need_end_deeper = true;
740         }
741         context.check_deeper(os);
742         output_arguments(os, p, outer, true, false, context,
743                          context.layout->latexargs());
744         parse_text(p, os, FLAG_ITEM, outer, context);
745         output_arguments(os, p, outer, false, true, context,
746                          context.layout->postcommandargs());
747         context.check_end_layout(os);
748         if (parent_context.deeper_paragraph) {
749                 // We must suppress the "end deeper" because we
750                 // suppressed the "begin deeper" above.
751                 context.need_end_deeper = false;
752         }
753         context.check_end_deeper(os);
754         // We don't need really a new paragraph, but
755         // we must make sure that the next item gets a \begin_layout.
756         parent_context.new_paragraph(os);
757         // Set the font size to the original value. No need to output it here
758         // (Context::begin_layout() will do that if needed)
759         parent_context.font.size = size;
760 }
761
762
763 /*!
764  * Output a space if necessary.
765  * This function gets called for every whitespace token.
766  *
767  * We have three cases here:
768  * 1. A space must be suppressed. Example: The lyxcode case below
769  * 2. A space may be suppressed. Example: Spaces before "\par"
770  * 3. A space must not be suppressed. Example: A space between two words
771  *
772  * We currently handle only 1. and 3 and from 2. only the case of
773  * spaces before newlines as a side effect.
774  *
775  * 2. could be used to suppress as many spaces as possible. This has two effects:
776  * - Reimporting LyX generated LaTeX files changes almost no whitespace
777  * - Superflous whitespace from non LyX generated LaTeX files is removed.
778  * The drawback is that the logic inside the function becomes
779  * complicated, and that is the reason why it is not implemented.
780  */
781 void check_space(Parser & p, ostream & os, Context & context)
782 {
783         Token const next = p.next_token();
784         Token const curr = p.curr_token();
785         // A space before a single newline and vice versa must be ignored
786         // LyX emits a newline before \end{lyxcode}.
787         // This newline must be ignored,
788         // otherwise LyX will add an additional protected space.
789         if (next.cat() == catSpace ||
790             next.cat() == catNewline ||
791             (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
792                 return;
793         }
794         context.check_layout(os);
795         os << ' ';
796 }
797
798
799 /*!
800  * Parse all arguments of \p command
801  */
802 void parse_arguments(string const & command,
803                      vector<ArgumentType> const & template_arguments,
804                      Parser & p, ostream & os, bool outer, Context & context)
805 {
806         string ert = command;
807         size_t no_arguments = template_arguments.size();
808         for (size_t i = 0; i < no_arguments; ++i) {
809                 switch (template_arguments[i]) {
810                 case required:
811                 case req_group:
812                         // This argument contains regular LaTeX
813                         output_ert_inset(os, ert + '{', context);
814                         eat_whitespace(p, os, context, false);
815                         if (template_arguments[i] == required)
816                                 parse_text(p, os, FLAG_ITEM, outer, context);
817                         else
818                                 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
819                         ert = "}";
820                         break;
821                 case item:
822                         // This argument consists only of a single item.
823                         // The presence of '{' or not must be preserved.
824                         p.skip_spaces();
825                         if (p.next_token().cat() == catBegin)
826                                 ert += '{' + p.verbatim_item() + '}';
827                         else
828                                 ert += p.verbatim_item();
829                         break;
830                 case displaymath:
831                 case verbatim:
832                         // This argument may contain special characters
833                         ert += '{' + p.verbatim_item() + '}';
834                         break;
835                 case optional:
836                 case opt_group:
837                         // true because we must not eat whitespace
838                         // if an optional arg follows we must not strip the
839                         // brackets from this one
840                         if (i < no_arguments - 1 &&
841                             template_arguments[i+1] == optional)
842                                 ert += p.getFullOpt(true);
843                         else
844                                 ert += p.getOpt(true);
845                         break;
846                 }
847         }
848         output_ert_inset(os, ert, context);
849 }
850
851
852 /*!
853  * Check whether \p command is a known command. If yes,
854  * handle the command with all arguments.
855  * \return true if the command was parsed, false otherwise.
856  */
857 bool parse_command(string const & command, Parser & p, ostream & os,
858                    bool outer, Context & context)
859 {
860         if (known_commands.find(command) != known_commands.end()) {
861                 parse_arguments(command, known_commands[command], p, os,
862                                 outer, context);
863                 return true;
864         }
865         return false;
866 }
867
868
869 /// Parses a minipage or parbox
870 void parse_box(Parser & p, ostream & os, unsigned outer_flags,
871                unsigned inner_flags, bool outer, Context & parent_context,
872                string const & outer_type, string const & special,
873                string inner_type, string const & frame_color,
874                string const & background_color)
875 {
876         string position;
877         string inner_pos;
878         string hor_pos = "l";
879         // We need to set the height to the LaTeX default of 1\\totalheight
880         // for the case when no height argument is given
881         string height_value = "1";
882         string height_unit = "in";
883         string height_special = "totalheight";
884         string latex_height;
885         string width_value;
886         string width_unit;
887         string latex_width;
888         string width_special = "none";
889         string thickness = "0.4pt";
890         if (!fboxrule.empty())
891                 thickness = fboxrule;
892         else
893                 thickness = "0.4pt";
894         string separation;
895         if (!fboxsep.empty())
896                 separation = fboxsep;
897         else
898                 separation = "3pt";
899         string shadowsize;
900         if (!shadow_size.empty())
901                 shadowsize = shadow_size;
902         else
903                 shadowsize = "4pt";
904         string framecolor = "black";
905         string backgroundcolor = "none";
906         if (!frame_color.empty())
907                 framecolor = frame_color;
908         if (!background_color.empty())
909                 backgroundcolor = background_color;
910         // if there is a color box around the \begin statements have not yet been parsed
911         // so do this now
912         if (!frame_color.empty() || !background_color.empty()) {
913                 eat_whitespace(p, os, parent_context, false);
914                 p.get_token().asInput(); // the '{'
915                 // parse minipage
916                 if (p.next_token().asInput() == "\\begin") {
917                         p.get_token().asInput();
918                         p.getArg('{', '}');
919                         inner_type = "minipage";
920                         inner_flags = FLAG_END;
921                         active_environments.push_back("minipage");
922                 }
923                 // parse parbox
924                 else if (p.next_token().asInput() == "\\parbox") {
925                         p.get_token().asInput();
926                         inner_type = "parbox";
927                         inner_flags = FLAG_ITEM;
928                 }
929                 // parse makebox
930                 else if (p.next_token().asInput() == "\\makebox") {
931                         p.get_token().asInput();
932                         inner_type = "makebox";
933                         inner_flags = FLAG_ITEM;
934                 }
935                 // in case there is just \colorbox{color}{text}
936                 else {
937                         latex_width = "";
938                         inner_type = "makebox";
939                         inner_flags = FLAG_BRACE_LAST;
940                         position = "t";
941                         inner_pos = "t";
942                 }
943         }
944         if (!p.hasOpt() && (inner_type == "makebox" || outer_type == "mbox"))
945                 hor_pos = "c";
946         if (!inner_type.empty() && p.hasOpt()) {
947                 if (inner_type != "makebox")
948                         position = p.getArg('[', ']');
949                 else {
950                         latex_width = p.getArg('[', ']');
951                         translate_box_len(latex_width, width_value, width_unit, width_special);
952                         position = "t";
953                 }
954                 if (position != "t" && position != "c" && position != "b") {
955                         cerr << "invalid position " << position << " for "
956                              << inner_type << endl;
957                         position = "c";
958                 }
959                 if (p.hasOpt()) {
960                         if (inner_type != "makebox") {
961                                 latex_height = p.getArg('[', ']');
962                                 translate_box_len(latex_height, height_value, height_unit, height_special);
963                         } else {
964                                 string const opt = p.getArg('[', ']');
965                                 if (!opt.empty()) {
966                                         hor_pos = opt;
967                                         if (hor_pos != "l" && hor_pos != "c" &&
968                                             hor_pos != "r" && hor_pos != "s") {
969                                                 cerr << "invalid hor_pos " << hor_pos
970                                                      << " for " << inner_type << endl;
971                                                 hor_pos = "c";
972                                         }
973                                 }
974                         }
975
976                         if (p.hasOpt()) {
977                                 inner_pos = p.getArg('[', ']');
978                                 if (inner_pos != "c" && inner_pos != "t" &&
979                                     inner_pos != "b" && inner_pos != "s") {
980                                         cerr << "invalid inner_pos "
981                                              << inner_pos << " for "
982                                              << inner_type << endl;
983                                         inner_pos = position;
984                                 }
985                         }
986                 } else {
987                         if (inner_type == "makebox")
988                                 hor_pos = "c";
989                 }
990         }
991         if (inner_type.empty()) {
992                 if (special.empty() && outer_type != "framebox")
993                         latex_width = "1\\columnwidth";
994                 else {
995                         Parser p2(special);
996                         latex_width = p2.getArg('[', ']');
997                         string const opt = p2.getArg('[', ']');
998                         if (!opt.empty()) {
999                                 hor_pos = opt;
1000                                 if (hor_pos != "l" && hor_pos != "c" &&
1001                                     hor_pos != "r" && hor_pos != "s") {
1002                                         cerr << "invalid hor_pos " << hor_pos
1003                                              << " for " << outer_type << endl;
1004                                         hor_pos = "c";
1005                                 }
1006                         } else {
1007                                 if (outer_type == "framebox")
1008                                         hor_pos = "c";
1009                         }
1010                 }
1011         } else if (inner_type != "makebox")
1012                 latex_width = p.verbatim_item();
1013         // if e.g. only \ovalbox{content} was used, set the width to 1\columnwidth
1014         // as this is LyX's standard for such cases (except for makebox)
1015         // \framebox is more special and handled below
1016         if (latex_width.empty() && inner_type != "makebox"
1017                 && outer_type != "framebox")
1018                 latex_width = "1\\columnwidth";
1019
1020         translate_len(latex_width, width_value, width_unit);
1021
1022         bool shadedparbox = false;
1023         if (inner_type == "shaded") {
1024                 eat_whitespace(p, os, parent_context, false);
1025                 if (outer_type == "parbox") {
1026                         // Eat '{'
1027                         if (p.next_token().cat() == catBegin)
1028                                 p.get_token();
1029                         eat_whitespace(p, os, parent_context, false);
1030                         shadedparbox = true;
1031                 }
1032                 p.get_token();
1033                 p.getArg('{', '}');
1034         }
1035         // If we already read the inner box we have to push the inner env
1036         if (!outer_type.empty() && !inner_type.empty() &&
1037             (inner_flags & FLAG_END))
1038                 active_environments.push_back(inner_type);
1039         bool use_ert = false;
1040         if (!outer_type.empty() && !inner_type.empty()) {
1041                 // Look whether there is some content after the end of the
1042                 // inner box, but before the end of the outer box.
1043                 // If yes, we need to output ERT.
1044                 p.pushPosition();
1045                 if (inner_flags & FLAG_END)
1046                         p.ertEnvironment(inner_type);
1047                 else
1048                         p.verbatim_item();
1049                 p.skip_spaces(true);
1050                 bool const outer_env(outer_type == "framed" || outer_type == "minipage");
1051                 if ((outer_env && p.next_token().asInput() != "\\end") ||
1052                     (!outer_env && p.next_token().cat() != catEnd)) {
1053                         // something is between the end of the inner box and
1054                         // the end of the outer box, so we need to use ERT.
1055                         use_ert = true;
1056                 }
1057                 p.popPosition();
1058         }
1059
1060         if (use_ert) {
1061                 ostringstream ss;
1062                 if (!outer_type.empty()) {
1063                         if (outer_flags & FLAG_END)
1064                                 ss << "\\begin{" << outer_type << '}';
1065                         else {
1066                                 ss << '\\' << outer_type << '{';
1067                                 if (!special.empty())
1068                                         ss << special;
1069                         }
1070                 }
1071                 if (!inner_type.empty()) {
1072                         if (inner_type != "shaded") {
1073                                 if (inner_flags & FLAG_END)
1074                                         ss << "\\begin{" << inner_type << '}';
1075                                 else
1076                                         ss << '\\' << inner_type;
1077                         }
1078                         if (!position.empty())
1079                                 ss << '[' << position << ']';
1080                         if (!latex_height.empty())
1081                                 ss << '[' << latex_height << ']';
1082                         if (!inner_pos.empty())
1083                                 ss << '[' << inner_pos << ']';
1084                         ss << '{' << latex_width << '}';
1085                         if (!(inner_flags & FLAG_END))
1086                                 ss << '{';
1087                 }
1088                 if (inner_type == "shaded")
1089                         ss << "\\begin{shaded}";
1090                 output_ert_inset(os, ss.str(), parent_context);
1091                 if (!inner_type.empty()) {
1092                         parse_text(p, os, inner_flags, outer, parent_context);
1093                         if (inner_flags & FLAG_END)
1094                                 output_ert_inset(os, "\\end{" + inner_type + '}',
1095                                            parent_context);
1096                         else
1097                                 output_ert_inset(os, "}", parent_context);
1098                 }
1099                 if (!outer_type.empty()) {
1100                         // If we already read the inner box we have to pop
1101                         // the inner env
1102                         if (!inner_type.empty() && (inner_flags & FLAG_END))
1103                                 active_environments.pop_back();
1104
1105                         // Ensure that the end of the outer box is parsed correctly:
1106                         // The opening brace has been eaten by parse_outer_box()
1107                         if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1108                                 outer_flags &= ~FLAG_ITEM;
1109                                 outer_flags |= FLAG_BRACE_LAST;
1110                         }
1111                         parse_text(p, os, outer_flags, outer, parent_context);
1112                         if (outer_flags & FLAG_END)
1113                                 output_ert_inset(os, "\\end{" + outer_type + '}',
1114                                            parent_context);
1115                         else
1116                                 output_ert_inset(os, "}", parent_context);
1117                 }
1118         } else {
1119                 // LyX does not like empty positions, so we have
1120                 // to set them to the LaTeX default values here.
1121                 if (position.empty())
1122                         position = "c";
1123                 if (inner_pos.empty())
1124                         inner_pos = position;
1125                 parent_context.check_layout(os);
1126                 begin_inset(os, "Box ");
1127                 if (outer_type == "framed")
1128                         os << "Framed\n";
1129                 else if (outer_type == "framebox" || outer_type == "fbox" || !frame_color.empty())
1130                         os << "Boxed\n";
1131                 else if (outer_type == "shadowbox")
1132                         os << "Shadowbox\n";
1133                 else if ((outer_type == "shaded" && inner_type.empty()) ||
1134                              (outer_type == "minipage" && inner_type == "shaded") ||
1135                              (outer_type == "parbox" && inner_type == "shaded")) {
1136                         os << "Shaded\n";
1137                         preamble.registerAutomaticallyLoadedPackage("color");
1138                 } else if (outer_type == "doublebox")
1139                         os << "Doublebox\n";
1140                 else if (outer_type.empty() || outer_type == "mbox")
1141                         os << "Frameless\n";
1142                 else
1143                         os << outer_type << '\n';
1144                 os << "position \"" << position << "\"\n";
1145                 os << "hor_pos \"" << hor_pos << "\"\n";
1146                 if (outer_type == "mbox")
1147                         os << "has_inner_box 1\n";
1148                 else if (!frame_color.empty() && inner_type == "makebox")
1149                         os << "has_inner_box 0\n";
1150                 else
1151                         os << "has_inner_box " << !inner_type.empty() << "\n";
1152                 os << "inner_pos \"" << inner_pos << "\"\n";
1153                 os << "use_parbox " << (inner_type == "parbox" || shadedparbox)
1154                    << '\n';
1155                 if (outer_type == "mbox")
1156                         os << "use_makebox 1\n";
1157                 else if (!frame_color.empty())
1158                         os << "use_makebox 0\n";
1159                 else
1160                         os << "use_makebox " << (inner_type == "makebox") << '\n';
1161                 if (outer_type == "mbox" || (outer_type == "fbox" && inner_type.empty()))
1162                         os << "width \"\"\n";
1163                 // for values like "1.5\width" LyX uses "1.5in" as width ad sets "width" as sepecial
1164                 else if (contains(width_unit, '\\'))
1165                         os << "width \"" << width_value << "in" << "\"\n";
1166                 else
1167                         os << "width \"" << width_value << width_unit << "\"\n";
1168                 if (contains(width_unit, '\\')) {
1169                         width_unit.erase (0,1); // remove the leading '\'
1170                         os << "special \"" << width_unit << "\"\n";
1171                 } else
1172                         os << "special \"" << width_special << "\"\n";
1173                 if (contains(height_unit, '\\'))
1174                         os << "height \"" << height_value << "in" << "\"\n";
1175                 else
1176                         os << "height \"" << height_value << height_unit << "\"\n";
1177                 os << "height_special \"" << height_special << "\"\n";
1178                 os << "thickness \"" << thickness << "\"\n";
1179                 os << "separation \"" << separation << "\"\n";
1180                 os << "shadowsize \"" << shadowsize << "\"\n";
1181                 os << "framecolor \"" << framecolor << "\"\n";
1182                 os << "backgroundcolor \"" << backgroundcolor << "\"\n";
1183                 os << "status open\n\n";
1184
1185                 // Unfortunately we can't use parse_text_in_inset:
1186                 // InsetBox::forcePlainLayout() is hard coded and does not
1187                 // use the inset layout. Apart from that do we call parse_text
1188                 // up to two times, but need only one check_end_layout.
1189                 bool const forcePlainLayout =
1190                         (!inner_type.empty() || inner_type == "makebox") &&
1191                         outer_type != "shaded" && outer_type != "framed";
1192                 Context context(true, parent_context.textclass);
1193                 if (forcePlainLayout)
1194                         context.layout = &context.textclass.plainLayout();
1195                 else
1196                         context.font = parent_context.font;
1197
1198                 // If we have no inner box the contents will be read with the outer box
1199                 if (!inner_type.empty())
1200                         parse_text(p, os, inner_flags, outer, context);
1201
1202                 // Ensure that the end of the outer box is parsed correctly:
1203                 // The opening brace has been eaten by parse_outer_box()
1204                 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1205                         outer_flags &= ~FLAG_ITEM;
1206                         outer_flags |= FLAG_BRACE_LAST;
1207                 }
1208
1209                 // Find end of outer box, output contents if inner_type is
1210                 // empty and output possible comments
1211                 if (!outer_type.empty()) {
1212                         // If we already read the inner box we have to pop
1213                         // the inner env
1214                         if (!inner_type.empty() && (inner_flags & FLAG_END))
1215                                 active_environments.pop_back();
1216                         // This does not output anything but comments if
1217                         // inner_type is not empty (see use_ert)
1218                         parse_text(p, os, outer_flags, outer, context);
1219                 }
1220
1221                 context.check_end_layout(os);
1222                 end_inset(os);
1223 #ifdef PRESERVE_LAYOUT
1224                 // LyX puts a % after the end of the minipage
1225                 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
1226                         // new paragraph
1227                         //output_comment(p, os, "dummy", parent_context);
1228                         p.get_token();
1229                         p.skip_spaces();
1230                         parent_context.new_paragraph(os);
1231                 }
1232                 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
1233                         //output_comment(p, os, "dummy", parent_context);
1234                         p.get_token();
1235                         p.skip_spaces();
1236                         // We add a protected space if something real follows
1237                         if (p.good() && p.next_token().cat() != catComment) {
1238                                 begin_inset(os, "space ~\n");
1239                                 end_inset(os);
1240                         }
1241                 }
1242 #endif
1243         }
1244         if (inner_type == "minipage" && (!frame_color.empty() || !background_color.empty()))
1245                 active_environments.pop_back();
1246         if (inner_flags != FLAG_BRACE_LAST && (!frame_color.empty() || !background_color.empty())) {
1247                 // in this case we have to eat the the closing brace of the color box
1248                 p.get_token().asInput(); // the '}'
1249         }
1250         if (p.next_token().asInput() == "}") {
1251                 // in this case we assume that the closing brace is from the box settings
1252                 // therefore reset these values for the next box
1253                 fboxrule = "";
1254                 fboxsep = "";
1255                 shadow_size = "";
1256         }
1257
1258         // all boxes except of Frameless and Shaded require calc
1259         if (!(outer_type.empty() || outer_type == "mbox") &&
1260                 !((outer_type == "shaded" && inner_type.empty()) ||
1261                              (outer_type == "minipage" && inner_type == "shaded") ||
1262                              (outer_type == "parbox" && inner_type == "shaded")))
1263                 preamble.registerAutomaticallyLoadedPackage("calc");
1264 }
1265
1266
1267 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
1268                      Context & parent_context, string const & outer_type,
1269                      string const & special)
1270 {
1271         eat_whitespace(p, os, parent_context, false);
1272         if (flags & FLAG_ITEM) {
1273                 // Eat '{'
1274                 if (p.next_token().cat() == catBegin)
1275                         p.get_token();
1276                 else
1277                         cerr << "Warning: Ignoring missing '{' after \\"
1278                              << outer_type << '.' << endl;
1279                 eat_whitespace(p, os, parent_context, false);
1280         }
1281         string inner;
1282         unsigned int inner_flags = 0;
1283         p.pushPosition();
1284         if (outer_type == "minipage" || outer_type == "parbox") {
1285                 p.skip_spaces(true);
1286                 while (p.hasOpt()) {
1287                         p.getArg('[', ']');
1288                         p.skip_spaces(true);
1289                 }
1290                 p.getArg('{', '}');
1291                 p.skip_spaces(true);
1292                 if (outer_type == "parbox") {
1293                         // Eat '{'
1294                         if (p.next_token().cat() == catBegin)
1295                                 p.get_token();
1296                         p.skip_spaces(true);
1297                 }
1298         }
1299         if (outer_type == "shaded" || outer_type == "mbox") {
1300                 // These boxes never have an inner box
1301                 ;
1302         } else if (p.next_token().asInput() == "\\parbox") {
1303                 inner = p.get_token().cs();
1304                 inner_flags = FLAG_ITEM;
1305         } else if (p.next_token().asInput() == "\\begin") {
1306                 // Is this a minipage or shaded box?
1307                 p.pushPosition();
1308                 p.get_token();
1309                 inner = p.getArg('{', '}');
1310                 p.popPosition();
1311                 if (inner == "minipage" || inner == "shaded")
1312                         inner_flags = FLAG_END;
1313                 else
1314                         inner = "";
1315         }
1316         p.popPosition();
1317         if (inner_flags == FLAG_END) {
1318                 if (inner != "shaded")
1319                 {
1320                         p.get_token();
1321                         p.getArg('{', '}');
1322                         eat_whitespace(p, os, parent_context, false);
1323                 }
1324                 parse_box(p, os, flags, FLAG_END, outer, parent_context,
1325                           outer_type, special, inner, "", "");
1326         } else {
1327                 if (inner_flags == FLAG_ITEM) {
1328                         p.get_token();
1329                         eat_whitespace(p, os, parent_context, false);
1330                 }
1331                 parse_box(p, os, flags, inner_flags, outer, parent_context,
1332                           outer_type, special, inner, "", "");
1333         }
1334 }
1335
1336
1337 void parse_listings(Parser & p, ostream & os, Context & parent_context,
1338                     bool in_line, bool use_minted)
1339 {
1340         parent_context.check_layout(os);
1341         begin_inset(os, "listings\n");
1342         string arg = p.hasOpt() ? subst(p.verbatimOption(), "\n", "") : string();
1343         size_t i;
1344         while ((i = arg.find(", ")) != string::npos
1345                         || (i = arg.find(",\t")) != string::npos)
1346                 arg.erase(i + 1, 1);
1347
1348         if (use_minted) {
1349                 string const language = p.getArg('{', '}');
1350                 p.skip_spaces(true);
1351                 arg += string(arg.empty() ? "" : ",") + "language=" + language;
1352                 if (!minted_float.empty()) {
1353                         arg += string(arg.empty() ? "" : ",") + minted_float;
1354                         minted_nonfloat_caption.clear();
1355                 }
1356         }
1357         if (!arg.empty()) {
1358                 os << "lstparams " << '"' << arg << '"' << '\n';
1359                 if (arg.find("\\color") != string::npos)
1360                         preamble.registerAutomaticallyLoadedPackage("color");
1361         }
1362         if (in_line)
1363                 os << "inline true\n";
1364         else
1365                 os << "inline false\n";
1366         os << "status collapsed\n";
1367         Context context(true, parent_context.textclass);
1368         context.layout = &parent_context.textclass.plainLayout();
1369         if (use_minted && prefixIs(minted_nonfloat_caption, "[t]")) {
1370                 minted_nonfloat_caption.erase(0,3);
1371                 os << "\n\\begin_layout Plain Layout\n";
1372                 begin_inset(os, "Caption Standard\n");
1373                 Context newcontext(true, context.textclass,
1374                                    context.layout, 0, context.font);
1375                 newcontext.check_layout(os);
1376                 os << minted_nonfloat_caption << "\n";
1377                 newcontext.check_end_layout(os);
1378                 end_inset(os);
1379                 os << "\n\\end_layout\n";
1380                 minted_nonfloat_caption.clear();
1381         }
1382         string s;
1383         if (in_line) {
1384                 // set catcodes to verbatim early, just in case.
1385                 p.setCatcodes(VERBATIM_CATCODES);
1386                 string delim = p.get_token().asInput();
1387                 //FIXME: handler error condition
1388                 s = p.verbatimStuff(delim).second;
1389 //              context.new_paragraph(os);
1390         } else if (use_minted) {
1391                 s = p.verbatimEnvironment("minted");
1392         } else {
1393                 s = p.verbatimEnvironment("lstlisting");
1394         }
1395         output_ert(os, s, context);
1396         if (use_minted && prefixIs(minted_nonfloat_caption, "[b]")) {
1397                 minted_nonfloat_caption.erase(0,3);
1398                 os << "\n\\begin_layout Plain Layout\n";
1399                 begin_inset(os, "Caption Standard\n");
1400                 Context newcontext(true, context.textclass,
1401                                    context.layout, 0, context.font);
1402                 newcontext.check_layout(os);
1403                 os << minted_nonfloat_caption << "\n";
1404                 newcontext.check_end_layout(os);
1405                 end_inset(os);
1406                 os << "\n\\end_layout\n";
1407                 minted_nonfloat_caption.clear();
1408         }
1409         // Don't close the inset here for floating minted listings.
1410         // It will be closed at the end of the listing environment.
1411         if (!use_minted || minted_float.empty())
1412                 end_inset(os);
1413         else {
1414                 eat_whitespace(p, os, parent_context, true);
1415                 Token t = p.get_token();
1416                 if (t.asInput() != "\\end") {
1417                         // If anything follows, collect it into a caption.
1418                         minted_float_has_caption = true;
1419                         os << "\n\\begin_layout Plain Layout\n"; // outer layout
1420                         begin_inset(os, "Caption Standard\n");
1421                         os << "\n\\begin_layout Plain Layout\n"; // inner layout
1422                 }
1423                 p.putback();
1424         }
1425 }
1426
1427
1428 /// parse an unknown environment
1429 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
1430                                unsigned flags, bool outer,
1431                                Context & parent_context)
1432 {
1433         if (name == "tabbing")
1434                 // We need to remember that we have to handle '\=' specially
1435                 flags |= FLAG_TABBING;
1436
1437         // We need to translate font changes and paragraphs inside the
1438         // environment to ERT if we have a non standard font.
1439         // Otherwise things like
1440         // \large\begin{foo}\huge bar\end{foo}
1441         // will not work.
1442         bool const specialfont =
1443                 (parent_context.font != parent_context.normalfont);
1444         bool const new_layout_allowed = parent_context.new_layout_allowed;
1445         if (specialfont)
1446                 parent_context.new_layout_allowed = false;
1447         output_ert_inset(os, "\\begin{" + name + "}", parent_context);
1448         parse_text_snippet(p, os, flags, outer, parent_context);
1449         output_ert_inset(os, "\\end{" + name + "}", parent_context);
1450         if (specialfont)
1451                 parent_context.new_layout_allowed = new_layout_allowed;
1452 }
1453
1454
1455 void parse_environment(Parser & p, ostream & os, bool outer,
1456                        string & last_env, Context & parent_context)
1457 {
1458         Layout const * newlayout;
1459         InsetLayout const * newinsetlayout = 0;
1460         string const name = p.getArg('{', '}');
1461         const bool is_starred = suffixIs(name, '*');
1462         string const unstarred_name = rtrim(name, "*");
1463         active_environments.push_back(name);
1464
1465         if (is_math_env(name)) {
1466                 parent_context.check_layout(os);
1467                 begin_inset(os, "Formula ");
1468                 os << "\\begin{" << name << "}";
1469                 parse_math(p, os, FLAG_END, MATH_MODE);
1470                 os << "\\end{" << name << "}";
1471                 end_inset(os);
1472                 if (is_display_math_env(name)) {
1473                         // Prevent the conversion of a line break to a space
1474                         // (bug 7668). This does not change the output, but
1475                         // looks ugly in LyX.
1476                         eat_whitespace(p, os, parent_context, false);
1477                 }
1478         }
1479
1480         else if (is_known(name, preamble.polyglossia_languages)) {
1481                 // We must begin a new paragraph if not already done
1482                 if (! parent_context.atParagraphStart()) {
1483                         parent_context.check_end_layout(os);
1484                         parent_context.new_paragraph(os);
1485                 }
1486                 // save the language in the context so that it is
1487                 // handled by parse_text
1488                 parent_context.font.language = preamble.polyglossia2lyx(name);
1489                 parse_text(p, os, FLAG_END, outer, parent_context);
1490                 // Just in case the environment is empty
1491                 parent_context.extra_stuff.erase();
1492                 // We must begin a new paragraph to reset the language
1493                 parent_context.new_paragraph(os);
1494                 p.skip_spaces();
1495         }
1496
1497         else if (unstarred_name == "tabular" || name == "longtable") {
1498                 eat_whitespace(p, os, parent_context, false);
1499                 string width = "0pt";
1500                 if (name == "tabular*") {
1501                         width = lyx::translate_len(p.getArg('{', '}'));
1502                         eat_whitespace(p, os, parent_context, false);
1503                 }
1504                 parent_context.check_layout(os);
1505                 begin_inset(os, "Tabular ");
1506                 handle_tabular(p, os, name, width, parent_context);
1507                 end_inset(os);
1508                 p.skip_spaces();
1509         }
1510
1511         else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1512                 eat_whitespace(p, os, parent_context, false);
1513                 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1514                 eat_whitespace(p, os, parent_context, false);
1515                 parent_context.check_layout(os);
1516                 begin_inset(os, "Float " + unstarred_name + "\n");
1517                 // store the float type for subfloats
1518                 // subfloats only work with figures and tables
1519                 if (unstarred_name == "figure")
1520                         float_type = unstarred_name;
1521                 else if (unstarred_name == "table")
1522                         float_type = unstarred_name;
1523                 else
1524                         float_type = "";
1525                 if (!opt.empty())
1526                         os << "placement " << opt << '\n';
1527                 if (contains(opt, "H"))
1528                         preamble.registerAutomaticallyLoadedPackage("float");
1529                 else {
1530                         Floating const & fl = parent_context.textclass.floats()
1531                                               .getType(unstarred_name);
1532                         if (!fl.floattype().empty() && fl.usesFloatPkg())
1533                                 preamble.registerAutomaticallyLoadedPackage("float");
1534                 }
1535
1536                 os << "wide " << convert<string>(is_starred)
1537                    << "\nsideways false"
1538                    << "\nstatus open\n\n";
1539                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1540                 end_inset(os);
1541                 // We don't need really a new paragraph, but
1542                 // we must make sure that the next item gets a \begin_layout.
1543                 parent_context.new_paragraph(os);
1544                 p.skip_spaces();
1545                 // the float is parsed thus delete the type
1546                 float_type = "";
1547         }
1548
1549         else if (unstarred_name == "sidewaysfigure"
1550                 || unstarred_name == "sidewaystable"
1551                 || unstarred_name == "sidewaysalgorithm") {
1552                 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1553                 eat_whitespace(p, os, parent_context, false);
1554                 parent_context.check_layout(os);
1555                 if (unstarred_name == "sidewaysfigure")
1556                         begin_inset(os, "Float figure\n");
1557                 else if (unstarred_name == "sidewaystable")
1558                         begin_inset(os, "Float table\n");
1559                 else if (unstarred_name == "sidewaysalgorithm")
1560                         begin_inset(os, "Float algorithm\n");
1561                 if (!opt.empty())
1562                         os << "placement " << opt << '\n';
1563                 if (contains(opt, "H"))
1564                         preamble.registerAutomaticallyLoadedPackage("float");
1565                 os << "wide " << convert<string>(is_starred)
1566                    << "\nsideways true"
1567                    << "\nstatus open\n\n";
1568                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1569                 end_inset(os);
1570                 // We don't need really a new paragraph, but
1571                 // we must make sure that the next item gets a \begin_layout.
1572                 parent_context.new_paragraph(os);
1573                 p.skip_spaces();
1574                 preamble.registerAutomaticallyLoadedPackage("rotfloat");
1575         }
1576
1577         else if (name == "wrapfigure" || name == "wraptable") {
1578                 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
1579                 eat_whitespace(p, os, parent_context, false);
1580                 parent_context.check_layout(os);
1581                 // default values
1582                 string lines = "0";
1583                 string overhang = "0col%";
1584                 // parse
1585                 if (p.hasOpt())
1586                         lines = p.getArg('[', ']');
1587                 string const placement = p.getArg('{', '}');
1588                 if (p.hasOpt())
1589                         overhang = p.getArg('[', ']');
1590                 string const width = p.getArg('{', '}');
1591                 // write
1592                 if (name == "wrapfigure")
1593                         begin_inset(os, "Wrap figure\n");
1594                 else
1595                         begin_inset(os, "Wrap table\n");
1596                 os << "lines " << lines
1597                    << "\nplacement " << placement
1598                    << "\noverhang " << lyx::translate_len(overhang)
1599                    << "\nwidth " << lyx::translate_len(width)
1600                    << "\nstatus open\n\n";
1601                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1602                 end_inset(os);
1603                 // We don't need really a new paragraph, but
1604                 // we must make sure that the next item gets a \begin_layout.
1605                 parent_context.new_paragraph(os);
1606                 p.skip_spaces();
1607                 preamble.registerAutomaticallyLoadedPackage("wrapfig");
1608         }
1609
1610         else if (name == "minipage") {
1611                 eat_whitespace(p, os, parent_context, false);
1612                 // Test whether this is an outer box of a shaded box
1613                 p.pushPosition();
1614                 // swallow arguments
1615                 while (p.hasOpt()) {
1616                         p.getArg('[', ']');
1617                         p.skip_spaces(true);
1618                 }
1619                 p.getArg('{', '}');
1620                 p.skip_spaces(true);
1621                 Token t = p.get_token();
1622                 bool shaded = false;
1623                 if (t.asInput() == "\\begin") {
1624                         p.skip_spaces(true);
1625                         if (p.getArg('{', '}') == "shaded")
1626                                 shaded = true;
1627                 }
1628                 p.popPosition();
1629                 if (shaded)
1630                         parse_outer_box(p, os, FLAG_END, outer,
1631                                         parent_context, name, "shaded");
1632                 else
1633                         parse_box(p, os, 0, FLAG_END, outer, parent_context,
1634                                   "", "", name, "", "");
1635                 p.skip_spaces();
1636         }
1637
1638         else if (name == "comment") {
1639                 eat_whitespace(p, os, parent_context, false);
1640                 parent_context.check_layout(os);
1641                 begin_inset(os, "Note Comment\n");
1642                 os << "status open\n";
1643                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1644                 end_inset(os);
1645                 p.skip_spaces();
1646                 skip_braces(p); // eat {} that might by set by LyX behind comments
1647                 preamble.registerAutomaticallyLoadedPackage("verbatim");
1648         }
1649
1650         else if (unstarred_name == "verbatim") {
1651                 // FIXME: this should go in the generic code that
1652                 // handles environments defined in layout file that
1653                 // have "PassThru 1". However, the code over there is
1654                 // already too complicated for my taste.
1655                 string const ascii_name =
1656                         (name == "verbatim*") ? "Verbatim*" : "Verbatim";
1657                 parent_context.new_paragraph(os);
1658                 Context context(true, parent_context.textclass,
1659                                 &parent_context.textclass[from_ascii(ascii_name)]);
1660                 string s = p.verbatimEnvironment(name);
1661                 output_ert(os, s, context);
1662                 p.skip_spaces();
1663         }
1664
1665         else if (name == "IPA") {
1666                 eat_whitespace(p, os, parent_context, false);
1667                 parent_context.check_layout(os);
1668                 begin_inset(os, "IPA\n");
1669                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1670                 end_inset(os);
1671                 p.skip_spaces();
1672                 preamble.registerAutomaticallyLoadedPackage("tipa");
1673                 preamble.registerAutomaticallyLoadedPackage("tipx");
1674         }
1675
1676         else if (name == "CJK") {
1677                 // the scheme is \begin{CJK}{encoding}{mapping}text\end{CJK}
1678                 // It is impossible to decide if a CJK environment was in its own paragraph or within
1679                 // a line. We therefore always assume a paragraph since the latter is a rare case.
1680                 eat_whitespace(p, os, parent_context, false);
1681                 parent_context.check_end_layout(os);
1682                 // store the encoding to be able to reset it
1683                 string const encoding_old = p.getEncoding();
1684                 string const encoding = p.getArg('{', '}');
1685                 // FIXME: For some reason JIS does not work. Although the text
1686                 // in tests/CJK.tex is identical with the SJIS version if you
1687                 // convert both snippets using the recode command line utility,
1688                 // the resulting .lyx file contains some extra characters if
1689                 // you set buggy_encoding to false for JIS.
1690                 bool const buggy_encoding = encoding == "JIS";
1691                 if (!buggy_encoding)
1692                         p.setEncoding(encoding, Encoding::CJK);
1693                 else {
1694                         // FIXME: This will read garbage, since the data is not encoded in utf8.
1695                         p.setEncoding("UTF-8");
1696                 }
1697                 // LyX only supports the same mapping for all CJK
1698                 // environments, so we might need to output everything as ERT
1699                 string const mapping = trim(p.getArg('{', '}'));
1700                 char const * const * const where =
1701                         is_known(encoding, supported_CJK_encodings);
1702                 if (!buggy_encoding && !preamble.fontCJKSet())
1703                         preamble.fontCJK(mapping);
1704                 bool knownMapping = mapping == preamble.fontCJK();
1705                 if (buggy_encoding || !knownMapping || !where) {
1706                         parent_context.check_layout(os);
1707                         output_ert_inset(os, "\\begin{" + name + "}{" + encoding + "}{" + mapping + "}",
1708                                        parent_context);
1709                         // we must parse the content as verbatim because e.g. JIS can contain
1710                         // normally invalid characters
1711                         // FIXME: This works only for the most simple cases.
1712                         //        Since TeX control characters are not parsed,
1713                         //        things like comments are completely wrong.
1714                         string const s = p.plainEnvironment("CJK");
1715                         for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1716                                 if (*it == '\\')
1717                                         output_ert_inset(os, "\\", parent_context);
1718                                 else if (*it == '$')
1719                                         output_ert_inset(os, "$", parent_context);
1720                                 else if (*it == '\n' && it + 1 != et && s.begin() + 1 != it)
1721                                         os << "\n ";
1722                                 else
1723                                         os << *it;
1724                         }
1725                         output_ert_inset(os, "\\end{" + name + "}",
1726                                        parent_context);
1727                 } else {
1728                         string const lang =
1729                                 supported_CJK_languages[where - supported_CJK_encodings];
1730                         // store the language because we must reset it at the end
1731                         string const lang_old = parent_context.font.language;
1732                         parent_context.font.language = lang;
1733                         parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1734                         parent_context.font.language = lang_old;
1735                         parent_context.new_paragraph(os);
1736                 }
1737                 p.setEncoding(encoding_old);
1738                 p.skip_spaces();
1739         }
1740
1741         else if (name == "lyxgreyedout") {
1742                 eat_whitespace(p, os, parent_context, false);
1743                 parent_context.check_layout(os);
1744                 begin_inset(os, "Note Greyedout\n");
1745                 os << "status open\n";
1746                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1747                 end_inset(os);
1748                 p.skip_spaces();
1749                 if (!preamble.notefontcolor().empty())
1750                         preamble.registerAutomaticallyLoadedPackage("color");
1751         }
1752
1753         else if (name == "btSect") {
1754                 eat_whitespace(p, os, parent_context, false);
1755                 parent_context.check_layout(os);
1756                 begin_command_inset(os, "bibtex", "bibtex");
1757                 string bibstyle = "plain";
1758                 if (p.hasOpt()) {
1759                         bibstyle = p.getArg('[', ']');
1760                         p.skip_spaces(true);
1761                 }
1762                 string const bibfile = p.getArg('{', '}');
1763                 eat_whitespace(p, os, parent_context, false);
1764                 Token t = p.get_token();
1765                 if (t.asInput() == "\\btPrintCited") {
1766                         p.skip_spaces(true);
1767                         os << "btprint " << '"' << "btPrintCited" << '"' << "\n";
1768                 }
1769                 if (t.asInput() == "\\btPrintNotCited") {
1770                         p.skip_spaces(true);
1771                         os << "btprint " << '"' << "btPrintNotCited" << '"' << "\n";
1772                 }
1773                 if (t.asInput() == "\\btPrintAll") {
1774                         p.skip_spaces(true);
1775                         os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
1776                 }
1777                 os << "bibfiles " << '"' << bibfile << "\"\n"
1778                    << "options " << '"' << bibstyle << "\"\n";
1779                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1780                 end_inset(os);
1781                 p.skip_spaces();
1782         }
1783
1784         else if (name == "framed" || name == "shaded") {
1785                 eat_whitespace(p, os, parent_context, false);
1786                 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
1787                 p.skip_spaces();
1788                 preamble.registerAutomaticallyLoadedPackage("framed");
1789         }
1790
1791         else if (name == "listing") {
1792                 minted_float = "float";
1793                 eat_whitespace(p, os, parent_context, false);
1794                 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1795                 if (!opt.empty())
1796                         minted_float += "=" + opt;
1797                 // If something precedes \begin{minted}, we output it at the end
1798                 // as a caption, in order to keep it inside the listings inset.
1799                 eat_whitespace(p, os, parent_context, true);
1800                 p.pushPosition();
1801                 Token const & t = p.get_token();
1802                 p.skip_spaces(true);
1803                 string const envname = p.next_token().cat() == catBegin
1804                                                 ? p.getArg('{', '}') : string();
1805                 bool prologue = t.asInput() != "\\begin" || envname != "minted";
1806                 p.popPosition();
1807                 minted_float_has_caption = false;
1808                 string content = parse_text_snippet(p, FLAG_END, outer,
1809                                                     parent_context);
1810                 size_t i = content.find("\\begin_inset listings");
1811                 bool minted_env = i != string::npos;
1812                 string caption;
1813                 if (prologue) {
1814                         caption = content.substr(0, i);
1815                         content.erase(0, i);
1816                 }
1817                 parent_context.check_layout(os);
1818                 if (minted_env && minted_float_has_caption) {
1819                         eat_whitespace(p, os, parent_context, true);
1820                         os << content << "\n";
1821                         if (!caption.empty())
1822                                 os << caption << "\n";
1823                         os << "\n\\end_layout\n"; // close inner layout
1824                         end_inset(os);            // close caption inset
1825                         os << "\n\\end_layout\n"; // close outer layout
1826                 } else if (!caption.empty()) {
1827                         if (!minted_env) {
1828                                 begin_inset(os, "listings\n");
1829                                 os << "lstparams " << '"' << minted_float << '"' << '\n';
1830                                 os << "inline false\n";
1831                                 os << "status collapsed\n";
1832                         }
1833                         os << "\n\\begin_layout Plain Layout\n";
1834                         begin_inset(os, "Caption Standard\n");
1835                         Context newcontext(true, parent_context.textclass,
1836                                            0, 0, parent_context.font);
1837                         newcontext.check_layout(os);
1838                         os << caption << "\n";
1839                         newcontext.check_end_layout(os);
1840                         end_inset(os);
1841                         os << "\n\\end_layout\n";
1842                 } else if (content.empty()) {
1843                         begin_inset(os, "listings\n");
1844                         os << "lstparams " << '"' << minted_float << '"' << '\n';
1845                         os << "inline false\n";
1846                         os << "status collapsed\n";
1847                 } else {
1848                         os << content << "\n";
1849                 }
1850                 end_inset(os); // close listings inset
1851                 parent_context.check_end_layout(os);
1852                 parent_context.new_paragraph(os);
1853                 p.skip_spaces();
1854                 minted_float.clear();
1855                 minted_float_has_caption = false;
1856         }
1857
1858         else if (name == "lstlisting" || name == "minted") {
1859                 bool use_minted = name == "minted";
1860                 eat_whitespace(p, os, parent_context, false);
1861                 if (use_minted && minted_float.empty()) {
1862                         // look ahead for a bottom caption
1863                         p.pushPosition();
1864                         bool found_end_minted = false;
1865                         while (!found_end_minted && p.good()) {
1866                                 Token const & t = p.get_token();
1867                                 p.skip_spaces();
1868                                 string const envname =
1869                                         p.next_token().cat() == catBegin
1870                                                 ? p.getArg('{', '}') : string();
1871                                 found_end_minted = t.asInput() == "\\end"
1872                                                         && envname == "minted";
1873                         }
1874                         eat_whitespace(p, os, parent_context, true);
1875                         Token const & t = p.get_token();
1876                         p.skip_spaces(true);
1877                         if (t.asInput() == "\\lyxmintcaption") {
1878                                 string const pos = p.getArg('[', ']');
1879                                 if (pos == "b") {
1880                                         string const caption =
1881                                                 parse_text_snippet(p, FLAG_ITEM,
1882                                                         false, parent_context);
1883                                         minted_nonfloat_caption = "[b]" + caption;
1884                                 }
1885                         }
1886                         p.popPosition();
1887                 }
1888                 parse_listings(p, os, parent_context, false, use_minted);
1889                 p.skip_spaces();
1890         }
1891
1892         else if (!parent_context.new_layout_allowed)
1893                 parse_unknown_environment(p, name, os, FLAG_END, outer,
1894                                           parent_context);
1895
1896         // Alignment and spacing settings
1897         // FIXME (bug xxxx): These settings can span multiple paragraphs and
1898         //                                       therefore are totally broken!
1899         // Note that \centering, raggedright, and raggedleft cannot be handled, as
1900         // they are commands not environments. They are furthermore switches that
1901         // can be ended by another switches, but also by commands like \footnote or
1902         // \parbox. So the only safe way is to leave them untouched.
1903         else if (name == "center" || name == "centering" ||
1904                  name == "flushleft" || name == "flushright" ||
1905                  name == "singlespace" || name == "onehalfspace" ||
1906                  name == "doublespace" || name == "spacing") {
1907                 eat_whitespace(p, os, parent_context, false);
1908                 // We must begin a new paragraph if not already done
1909                 if (! parent_context.atParagraphStart()) {
1910                         parent_context.check_end_layout(os);
1911                         parent_context.new_paragraph(os);
1912                 }
1913                 if (name == "flushleft")
1914                         parent_context.add_extra_stuff("\\align left\n");
1915                 else if (name == "flushright")
1916                         parent_context.add_extra_stuff("\\align right\n");
1917                 else if (name == "center" || name == "centering")
1918                         parent_context.add_extra_stuff("\\align center\n");
1919                 else if (name == "singlespace")
1920                         parent_context.add_extra_stuff("\\paragraph_spacing single\n");
1921                 else if (name == "onehalfspace") {
1922                         parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
1923                         preamble.registerAutomaticallyLoadedPackage("setspace");
1924                 } else if (name == "doublespace") {
1925                         parent_context.add_extra_stuff("\\paragraph_spacing double\n");
1926                         preamble.registerAutomaticallyLoadedPackage("setspace");
1927                 } else if (name == "spacing") {
1928                         parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
1929                         preamble.registerAutomaticallyLoadedPackage("setspace");
1930                 }
1931                 parse_text(p, os, FLAG_END, outer, parent_context);
1932                 // Just in case the environment is empty
1933                 parent_context.extra_stuff.erase();
1934                 // We must begin a new paragraph to reset the alignment
1935                 parent_context.new_paragraph(os);
1936                 p.skip_spaces();
1937         }
1938
1939         // The single '=' is meant here.
1940         else if ((newlayout = findLayout(parent_context.textclass, name, false))) {
1941                 eat_whitespace(p, os, parent_context, false);
1942                 Context context(true, parent_context.textclass, newlayout,
1943                                 parent_context.layout, parent_context.font);
1944                 if (parent_context.deeper_paragraph) {
1945                         // We are beginning a nested environment after a
1946                         // deeper paragraph inside the outer list environment.
1947                         // Therefore we don't need to output a "begin deeper".
1948                         context.need_end_deeper = true;
1949                 }
1950                 parent_context.check_end_layout(os);
1951                 if (last_env == name) {
1952                         // we need to output a separator since LyX would export
1953                         // the two environments as one otherwise (bug 5716)
1954                         TeX2LyXDocClass const & textclass(parent_context.textclass);
1955                         Context newcontext(true, textclass,
1956                                         &(textclass.defaultLayout()));
1957                         newcontext.check_layout(os);
1958                         begin_inset(os, "Separator plain\n");
1959                         end_inset(os);
1960                         newcontext.check_end_layout(os);
1961                 }
1962                 switch (context.layout->latextype) {
1963                 case  LATEX_LIST_ENVIRONMENT:
1964                         context.add_par_extra_stuff("\\labelwidthstring "
1965                                                     + p.verbatim_item() + '\n');
1966                         p.skip_spaces();
1967                         break;
1968                 case  LATEX_BIB_ENVIRONMENT:
1969                         p.verbatim_item(); // swallow next arg
1970                         p.skip_spaces();
1971                         break;
1972                 default:
1973                         break;
1974                 }
1975                 context.check_deeper(os);
1976                 // handle known optional and required arguments
1977                 // Unfortunately LyX can't handle arguments of list arguments (bug 7468):
1978                 // It is impossible to place anything after the environment name,
1979                 // but before the first \\item.
1980                 if (context.layout->latextype == LATEX_ENVIRONMENT)
1981                         output_arguments(os, p, outer, false, false, context,
1982                                          context.layout->latexargs());
1983                 parse_text(p, os, FLAG_END, outer, context);
1984                 if (context.layout->latextype == LATEX_ENVIRONMENT)
1985                         output_arguments(os, p, outer, false, true, context,
1986                                          context.layout->postcommandargs());
1987                 context.check_end_layout(os);
1988                 if (parent_context.deeper_paragraph) {
1989                         // We must suppress the "end deeper" because we
1990                         // suppressed the "begin deeper" above.
1991                         context.need_end_deeper = false;
1992                 }
1993                 context.check_end_deeper(os);
1994                 parent_context.new_paragraph(os);
1995                 p.skip_spaces();
1996                 if (!preamble.titleLayoutFound())
1997                         preamble.titleLayoutFound(newlayout->intitle);
1998                 set<string> const & req = newlayout->requires();
1999                 set<string>::const_iterator it = req.begin();
2000                 set<string>::const_iterator en = req.end();
2001                 for (; it != en; ++it)
2002                         preamble.registerAutomaticallyLoadedPackage(*it);
2003         }
2004
2005         // The single '=' is meant here.
2006         else if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
2007                 eat_whitespace(p, os, parent_context, false);
2008                 parent_context.check_layout(os);
2009                 begin_inset(os, "Flex ");
2010                 os << to_utf8(newinsetlayout->name()) << '\n'
2011                    << "status collapsed\n";
2012                 if (newinsetlayout->isPassThru()) {
2013                         string const arg = p.verbatimEnvironment(name);
2014                         Context context(true, parent_context.textclass,
2015                                         &parent_context.textclass.plainLayout(),
2016                                         parent_context.layout);
2017                         output_ert(os, arg, parent_context);
2018                 } else
2019                         parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
2020                 end_inset(os);
2021         }
2022
2023         else if (name == "appendix") {
2024                 // This is no good latex style, but it works and is used in some documents...
2025                 eat_whitespace(p, os, parent_context, false);
2026                 parent_context.check_end_layout(os);
2027                 Context context(true, parent_context.textclass, parent_context.layout,
2028                                 parent_context.layout, parent_context.font);
2029                 context.check_layout(os);
2030                 os << "\\start_of_appendix\n";
2031                 parse_text(p, os, FLAG_END, outer, context);
2032                 context.check_end_layout(os);
2033                 p.skip_spaces();
2034         }
2035
2036         else if (known_environments.find(name) != known_environments.end()) {
2037                 vector<ArgumentType> arguments = known_environments[name];
2038                 // The last "argument" denotes wether we may translate the
2039                 // environment contents to LyX
2040                 // The default required if no argument is given makes us
2041                 // compatible with the reLyXre environment.
2042                 ArgumentType contents = arguments.empty() ?
2043                         required :
2044                         arguments.back();
2045                 if (!arguments.empty())
2046                         arguments.pop_back();
2047                 // See comment in parse_unknown_environment()
2048                 bool const specialfont =
2049                         (parent_context.font != parent_context.normalfont);
2050                 bool const new_layout_allowed =
2051                         parent_context.new_layout_allowed;
2052                 if (specialfont)
2053                         parent_context.new_layout_allowed = false;
2054                 parse_arguments("\\begin{" + name + "}", arguments, p, os,
2055                                 outer, parent_context);
2056                 if (contents == verbatim)
2057                         output_ert_inset(os, p.ertEnvironment(name),
2058                                    parent_context);
2059                 else
2060                         parse_text_snippet(p, os, FLAG_END, outer,
2061                                            parent_context);
2062                 output_ert_inset(os, "\\end{" + name + "}", parent_context);
2063                 if (specialfont)
2064                         parent_context.new_layout_allowed = new_layout_allowed;
2065         }
2066
2067         else
2068                 parse_unknown_environment(p, name, os, FLAG_END, outer,
2069                                           parent_context);
2070
2071         last_env = name;
2072         active_environments.pop_back();
2073 }
2074
2075
2076 /// parses a comment and outputs it to \p os.
2077 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
2078 {
2079         LASSERT(t.cat() == catComment, return);
2080         if (!t.cs().empty()) {
2081                 context.check_layout(os);
2082                 output_comment(p, os, t.cs(), context);
2083                 if (p.next_token().cat() == catNewline) {
2084                         // A newline after a comment line starts a new
2085                         // paragraph
2086                         if (context.new_layout_allowed) {
2087                                 if(!context.atParagraphStart())
2088                                         // Only start a new paragraph if not already
2089                                         // done (we might get called recursively)
2090                                         context.new_paragraph(os);
2091                         } else
2092                                 output_ert_inset(os, "\n", context);
2093                         eat_whitespace(p, os, context, true);
2094                 }
2095         } else {
2096                 // "%\n" combination
2097                 p.skip_spaces();
2098         }
2099 }
2100
2101
2102 /*!
2103  * Reads spaces and comments until the first non-space, non-comment token.
2104  * New paragraphs (double newlines or \\par) are handled like simple spaces
2105  * if \p eatParagraph is true.
2106  * Spaces are skipped, but comments are written to \p os.
2107  */
2108 void eat_whitespace(Parser & p, ostream & os, Context & context,
2109                     bool eatParagraph)
2110 {
2111         while (p.good()) {
2112                 Token const & t = p.get_token();
2113                 if (t.cat() == catComment)
2114                         parse_comment(p, os, t, context);
2115                 else if ((! eatParagraph && p.isParagraph()) ||
2116                          (t.cat() != catSpace && t.cat() != catNewline)) {
2117                         p.putback();
2118                         return;
2119                 }
2120         }
2121 }
2122
2123
2124 /*!
2125  * Set a font attribute, parse text and reset the font attribute.
2126  * \param attribute Attribute name (e.g. \\family, \\shape etc.)
2127  * \param currentvalue Current value of the attribute. Is set to the new
2128  * value during parsing.
2129  * \param newvalue New value of the attribute
2130  */
2131 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
2132                            Context & context, string const & attribute,
2133                            string & currentvalue, string const & newvalue)
2134 {
2135         context.check_layout(os);
2136         string const oldvalue = currentvalue;
2137         currentvalue = newvalue;
2138         os << '\n' << attribute << ' ' << newvalue << "\n";
2139         parse_text_snippet(p, os, flags, outer, context);
2140         context.check_layout(os);
2141         os << '\n' << attribute << ' ' << oldvalue << "\n";
2142         currentvalue = oldvalue;
2143 }
2144
2145
2146 /// get the arguments of a natbib or jurabib citation command
2147 void get_cite_arguments(Parser & p, bool natbibOrder,
2148         string & before, string & after, bool const qualified = false)
2149 {
2150         // We need to distinguish "" and "[]", so we can't use p.getOpt().
2151
2152         // text before the citation
2153         before.clear();
2154         // text after the citation
2155         after = qualified ? p.getFullOpt(false, '(', ')') : p.getFullOpt();
2156
2157         if (!after.empty()) {
2158                 before = qualified ? p.getFullOpt(false, '(', ')') : p.getFullOpt();
2159                 if (natbibOrder && !before.empty())
2160                         swap(before, after);
2161         }
2162 }
2163
2164
2165 /// Convert filenames with TeX macros and/or quotes to something LyX
2166 /// can understand
2167 string const normalize_filename(string const & name)
2168 {
2169         Parser p(name);
2170         ostringstream os;
2171         while (p.good()) {
2172                 Token const & t = p.get_token();
2173                 if (t.cat() != catEscape)
2174                         os << t.asInput();
2175                 else if (t.cs() == "lyxdot") {
2176                         // This is used by LyX for simple dots in relative
2177                         // names
2178                         os << '.';
2179                         p.skip_spaces();
2180                 } else if (t.cs() == "space") {
2181                         os << ' ';
2182                         p.skip_spaces();
2183                 } else if (t.cs() == "string") {
2184                         // Convert \string" to " and \string~ to ~
2185                         Token const & n = p.next_token();
2186                         if (n.asInput() != "\"" && n.asInput() != "~")
2187                                 os << t.asInput();
2188                 } else
2189                         os << t.asInput();
2190         }
2191         // Strip quotes. This is a bit complicated (see latex_path()).
2192         string full = os.str();
2193         if (!full.empty() && full[0] == '"') {
2194                 string base = removeExtension(full);
2195                 string ext = getExtension(full);
2196                 if (!base.empty() && base[base.length()-1] == '"')
2197                         // "a b"
2198                         // "a b".tex
2199                         return addExtension(trim(base, "\""), ext);
2200                 if (full[full.length()-1] == '"')
2201                         // "a b.c"
2202                         // "a b.c".tex
2203                         return trim(full, "\"");
2204         }
2205         return full;
2206 }
2207
2208
2209 /// Convert \p name from TeX convention (relative to master file) to LyX
2210 /// convention (relative to .lyx file) if it is relative
2211 void fix_child_filename(string & name)
2212 {
2213         string const absMasterTeX = getMasterFilePath(true);
2214         bool const isabs = FileName::isAbsolute(name);
2215         // convert from "relative to .tex master" to absolute original path
2216         if (!isabs)
2217                 name = makeAbsPath(name, absMasterTeX).absFileName();
2218         bool copyfile = copyFiles();
2219         string const absParentLyX = getParentFilePath(false);
2220         string abs = name;
2221         if (copyfile) {
2222                 // convert from absolute original path to "relative to master file"
2223                 string const rel = to_utf8(makeRelPath(from_utf8(name),
2224                                                        from_utf8(absMasterTeX)));
2225                 // re-interpret "relative to .tex file" as "relative to .lyx file"
2226                 // (is different if the master .lyx file resides in a
2227                 // different path than the master .tex file)
2228                 string const absMasterLyX = getMasterFilePath(false);
2229                 abs = makeAbsPath(rel, absMasterLyX).absFileName();
2230                 // Do not copy if the new path is impossible to create. Example:
2231                 // absMasterTeX = "/foo/bar/"
2232                 // absMasterLyX = "/bar/"
2233                 // name = "/baz.eps" => new absolute name would be "/../baz.eps"
2234                 if (contains(name, "/../"))
2235                         copyfile = false;
2236         }
2237         if (copyfile) {
2238                 if (isabs)
2239                         name = abs;
2240                 else {
2241                         // convert from absolute original path to
2242                         // "relative to .lyx file"
2243                         name = to_utf8(makeRelPath(from_utf8(abs),
2244                                                    from_utf8(absParentLyX)));
2245                 }
2246         }
2247         else if (!isabs) {
2248                 // convert from absolute original path to "relative to .lyx file"
2249                 name = to_utf8(makeRelPath(from_utf8(name),
2250                                            from_utf8(absParentLyX)));
2251         }
2252 }
2253
2254
2255 void copy_file(FileName const & src, string dstname)
2256 {
2257         if (!copyFiles())
2258                 return;
2259         string const absParent = getParentFilePath(false);
2260         FileName dst;
2261         if (FileName::isAbsolute(dstname))
2262                 dst = FileName(dstname);
2263         else
2264                 dst = makeAbsPath(dstname, absParent);
2265         FileName const srcpath = src.onlyPath();
2266         FileName const dstpath = dst.onlyPath();
2267         if (equivalent(srcpath, dstpath))
2268                 return;
2269         if (!dstpath.isDirectory()) {
2270                 if (!dstpath.createPath()) {
2271                         cerr << "Warning: Could not create directory for file `"
2272                              << dst.absFileName() << "´." << endl;
2273                         return;
2274                 }
2275         }
2276         if (dst.isReadableFile()) {
2277                 if (overwriteFiles())
2278                         cerr << "Warning: Overwriting existing file `"
2279                              << dst.absFileName() << "´." << endl;
2280                 else {
2281                         cerr << "Warning: Not overwriting existing file `"
2282                              << dst.absFileName() << "´." << endl;
2283                         return;
2284                 }
2285         }
2286         if (!src.copyTo(dst))
2287                 cerr << "Warning: Could not copy file `" << src.absFileName()
2288                      << "´ to `" << dst.absFileName() << "´." << endl;
2289 }
2290
2291
2292 /// Parse a literate Chunk section. The initial "<<" is already parsed.
2293 bool parse_chunk(Parser & p, ostream & os, Context & context)
2294 {
2295         // check whether a chunk is possible here.
2296         if (!context.textclass.hasInsetLayout(from_ascii("Flex:Chunk"))) {
2297                 return false;
2298         }
2299
2300         p.pushPosition();
2301
2302         // read the parameters
2303         Parser::Arg const params = p.verbatimStuff(">>=\n", false);
2304         if (!params.first) {
2305                 p.popPosition();
2306                 return false;
2307         }
2308
2309         Parser::Arg const code = p.verbatimStuff("\n@");
2310         if (!code.first) {
2311                 p.popPosition();
2312                 return false;
2313         }
2314         string const post_chunk = p.verbatimStuff("\n").second + '\n';
2315         if (post_chunk[0] != ' ' && post_chunk[0] != '\n') {
2316                 p.popPosition();
2317                 return false;
2318         }
2319         // The last newline read is important for paragraph handling
2320         p.putback();
2321         p.deparse();
2322
2323         //cerr << "params=[" << params.second << "], code=[" << code.second << "]" <<endl;
2324         // We must have a valid layout before outputting the Chunk inset.
2325         context.check_layout(os);
2326         Context chunkcontext(true, context.textclass);
2327         chunkcontext.layout = &context.textclass.plainLayout();
2328         begin_inset(os, "Flex Chunk");
2329         os << "\nstatus open\n";
2330         if (!params.second.empty()) {
2331                 chunkcontext.check_layout(os);
2332                 Context paramscontext(true, context.textclass);
2333                 paramscontext.layout = &context.textclass.plainLayout();
2334                 begin_inset(os, "Argument 1");
2335                 os << "\nstatus open\n";
2336                 output_ert(os, params.second, paramscontext);
2337                 end_inset(os);
2338         }
2339         output_ert(os, code.second, chunkcontext);
2340         end_inset(os);
2341
2342         p.dropPosition();
2343         return true;
2344 }
2345
2346
2347 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
2348 bool is_macro(Parser & p)
2349 {
2350         Token first = p.curr_token();
2351         if (first.cat() != catEscape || !p.good())
2352                 return false;
2353         if (first.cs() == "def")
2354                 return true;
2355         if (first.cs() != "global" && first.cs() != "long")
2356                 return false;
2357         Token second = p.get_token();
2358         int pos = 1;
2359         while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
2360                second.cat() == catNewline || second.cat() == catComment)) {
2361                 second = p.get_token();
2362                 pos++;
2363         }
2364         bool secondvalid = second.cat() == catEscape;
2365         Token third;
2366         bool thirdvalid = false;
2367         if (p.good() && first.cs() == "global" && secondvalid &&
2368             second.cs() == "long") {
2369                 third = p.get_token();
2370                 pos++;
2371                 while (p.good() && !p.isParagraph() &&
2372                        (third.cat() == catSpace ||
2373                         third.cat() == catNewline ||
2374                         third.cat() == catComment)) {
2375                         third = p.get_token();
2376                         pos++;
2377                 }
2378                 thirdvalid = third.cat() == catEscape;
2379         }
2380         for (int i = 0; i < pos; ++i)
2381                 p.putback();
2382         if (!secondvalid)
2383                 return false;
2384         if (!thirdvalid)
2385                 return (first.cs() == "global" || first.cs() == "long") &&
2386                        second.cs() == "def";
2387         return first.cs() == "global" && second.cs() == "long" &&
2388                third.cs() == "def";
2389 }
2390
2391
2392 /// Parse a macro definition (assumes that is_macro() returned true)
2393 void parse_macro(Parser & p, ostream & os, Context & context)
2394 {
2395         context.check_layout(os);
2396         Token first = p.curr_token();
2397         Token second;
2398         Token third;
2399         string command = first.asInput();
2400         if (first.cs() != "def") {
2401                 p.get_token();
2402                 eat_whitespace(p, os, context, false);
2403                 second = p.curr_token();
2404                 command += second.asInput();
2405                 if (second.cs() != "def") {
2406                         p.get_token();
2407                         eat_whitespace(p, os, context, false);
2408                         third = p.curr_token();
2409                         command += third.asInput();
2410                 }
2411         }
2412         eat_whitespace(p, os, context, false);
2413         string const name = p.get_token().cs();
2414         eat_whitespace(p, os, context, false);
2415
2416         // parameter text
2417         bool simple = true;
2418         string paramtext;
2419         int arity = 0;
2420         while (p.next_token().cat() != catBegin) {
2421                 if (p.next_token().cat() == catParameter) {
2422                         // # found
2423                         p.get_token();
2424                         paramtext += "#";
2425
2426                         // followed by number?
2427                         if (p.next_token().cat() == catOther) {
2428                                 string s = p.get_token().asInput();
2429                                 paramtext += s;
2430                                 // number = current arity + 1?
2431                                 if (s.size() == 1 && s[0] == arity + '0' + 1)
2432                                         ++arity;
2433                                 else
2434                                         simple = false;
2435                         } else
2436                                 paramtext += p.get_token().cs();
2437                 } else {
2438                         paramtext += p.get_token().cs();
2439                         simple = false;
2440                 }
2441         }
2442
2443         // only output simple (i.e. compatible) macro as FormulaMacros
2444         string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
2445         if (simple) {
2446                 context.check_layout(os);
2447                 begin_inset(os, "FormulaMacro");
2448                 os << "\n\\def" << ert;
2449                 end_inset(os);
2450         } else
2451                 output_ert_inset(os, command + ert, context);
2452 }
2453
2454
2455 void registerExternalTemplatePackages(string const & name)
2456 {
2457         external::TemplateManager const & etm = external::TemplateManager::get();
2458         external::Template const * const et = etm.getTemplateByName(name);
2459         if (!et)
2460                 return;
2461         external::Template::Formats::const_iterator cit = et->formats.end();
2462         if (pdflatex)
2463                 cit = et->formats.find("PDFLaTeX");
2464         if (cit == et->formats.end())
2465                 // If the template has not specified a PDFLaTeX output,
2466                 // we try the LaTeX format.
2467                 cit = et->formats.find("LaTeX");
2468         if (cit == et->formats.end())
2469                 return;
2470         vector<string>::const_iterator qit = cit->second.requirements.begin();
2471         vector<string>::const_iterator qend = cit->second.requirements.end();
2472         for (; qit != qend; ++qit)
2473                 preamble.registerAutomaticallyLoadedPackage(*qit);
2474 }
2475
2476 } // anonymous namespace
2477
2478
2479 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
2480                 Context & context)
2481 {
2482         Layout const * newlayout = 0;
2483         InsetLayout const * newinsetlayout = 0;
2484         char const * const * where = 0;
2485         // Store the latest bibliographystyle, addcontentslineContent and
2486         // nocite{*} option (needed for bibtex inset)
2487         string btprint;
2488         string contentslineContent;
2489         string bibliographystyle = "default";
2490         bool const use_natbib = isProvided("natbib");
2491         bool const use_jurabib = isProvided("jurabib");
2492         bool const use_biblatex = isProvided("biblatex")
2493                         && preamble.citeEngine() != "biblatex-natbib";
2494         bool const use_biblatex_natbib = isProvided("biblatex-natbib")
2495                         || (isProvided("biblatex") && preamble.citeEngine() == "biblatex-natbib");
2496         need_commentbib = use_biblatex || use_biblatex_natbib;
2497         string last_env;
2498
2499         // it is impossible to determine the correct encoding for non-CJK Japanese.
2500         // Therefore write a note at the beginning of the document
2501         if (is_nonCJKJapanese) {
2502                 context.check_layout(os);
2503                 begin_inset(os, "Note Note\n");
2504                 os << "status open\n\\begin_layout Plain Layout\n"
2505                    << "\\series bold\n"
2506                    << "Important information:\n"
2507                    << "\\end_layout\n\n"
2508                    << "\\begin_layout Plain Layout\n"
2509                    << "The original LaTeX source for this document is in Japanese (pLaTeX).\n"
2510                    << " It was therefore impossible for tex2lyx to determine the correct encoding.\n"
2511                    << " The iconv encoding " << p.getEncoding() << " was used.\n"
2512                    << " If this is incorrect, you must run the tex2lyx program on the command line\n"
2513                    << " and specify the encoding using the -e command-line switch.\n"
2514                    << " In addition, you might want to double check that the desired output encoding\n"
2515                    << " is correctly selected in Document > Settings > Language.\n"
2516                    << "\\end_layout\n";
2517                 end_inset(os);
2518                 is_nonCJKJapanese = false;
2519         }
2520
2521         while (p.good()) {
2522                 Token const & t = p.get_token();
2523 #ifdef FILEDEBUG
2524                 debugToken(cerr, t, flags);
2525 #endif
2526
2527                 if (flags & FLAG_ITEM) {
2528                         if (t.cat() == catSpace)
2529                                 continue;
2530
2531                         flags &= ~FLAG_ITEM;
2532                         if (t.cat() == catBegin) {
2533                                 // skip the brace and collect everything to the next matching
2534                                 // closing brace
2535                                 flags |= FLAG_BRACE_LAST;
2536                                 continue;
2537                         }
2538
2539                         // handle only this single token, leave the loop if done
2540                         flags |= FLAG_LEAVE;
2541                 }
2542
2543                 if (t.cat() != catEscape && t.character() == ']' &&
2544                     (flags & FLAG_BRACK_LAST))
2545                         return;
2546                 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
2547                         return;
2548
2549                 // If there is anything between \end{env} and \begin{env} we
2550                 // don't need to output a separator.
2551                 if (t.cat() != catSpace && t.cat() != catNewline &&
2552                     t.asInput() != "\\begin")
2553                         last_env = "";
2554
2555                 //
2556                 // cat codes
2557                 //
2558                 bool const starred = p.next_token().asInput() == "*";
2559                 string const starredname(starred ? (t.cs() + '*') : t.cs());
2560                 if (t.cat() == catMath) {
2561                         // we are inside some text mode thingy, so opening new math is allowed
2562                         context.check_layout(os);
2563                         begin_inset(os, "Formula ");
2564                         Token const & n = p.get_token();
2565                         bool const display(n.cat() == catMath && outer);
2566                         if (display) {
2567                                 // TeX's $$...$$ syntax for displayed math
2568                                 os << "\\[";
2569                                 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2570                                 os << "\\]";
2571                                 p.get_token(); // skip the second '$' token
2572                         } else {
2573                                 // simple $...$  stuff
2574                                 p.putback();
2575                                 os << '$';
2576                                 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2577                                 os << '$';
2578                         }
2579                         end_inset(os);
2580                         if (display) {
2581                                 // Prevent the conversion of a line break to a
2582                                 // space (bug 7668). This does not change the
2583                                 // output, but looks ugly in LyX.
2584                                 eat_whitespace(p, os, context, false);
2585                         }
2586                 }
2587
2588                 else if (t.cat() == catSuper || t.cat() == catSub)
2589                         cerr << "catcode " << t << " illegal in text mode\n";
2590
2591                 // Basic support for english quotes. This should be
2592                 // extended to other quotes, but is not so easy (a
2593                 // left english quote is the same as a right german
2594                 // quote...)
2595                 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
2596                         context.check_layout(os);
2597                         begin_inset(os, "Quotes ");
2598                         os << "eld";
2599                         end_inset(os);
2600                         p.get_token();
2601                         skip_braces(p);
2602                 }
2603                 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
2604                         context.check_layout(os);
2605                         begin_inset(os, "Quotes ");
2606                         os << "erd";
2607                         end_inset(os);
2608                         p.get_token();
2609                         skip_braces(p);
2610                 }
2611
2612                 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
2613                         context.check_layout(os);
2614                         begin_inset(os, "Quotes ");
2615                         os << "ald";
2616                         end_inset(os);
2617                         p.get_token();
2618                         skip_braces(p);
2619                 }
2620
2621                 else if (t.asInput() == "<"
2622                          && p.next_token().asInput() == "<") {
2623                         bool has_chunk = false;
2624                         if (noweb_mode) {
2625                                 p.pushPosition();
2626                                 p.get_token();
2627                                 has_chunk = parse_chunk(p, os, context);
2628                                 if (!has_chunk)
2629                                         p.popPosition();
2630                         }
2631
2632                         if (!has_chunk) {
2633                                 context.check_layout(os);
2634                                 begin_inset(os, "Quotes ");
2635                                 //FIXME: this is a right danish quote;
2636                                 // why not a left french quote?
2637                                 os << "ard";
2638                                 end_inset(os);
2639                                 p.get_token();
2640                                 skip_braces(p);
2641                         }
2642                 }
2643
2644                 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
2645                         check_space(p, os, context);
2646
2647                 // babel shorthands (also used by polyglossia)
2648                 // Since these can have different meanings for different languages
2649                 // we import them as ERT (but they must be put in ERT to get output
2650                 // verbatim).
2651                 else if (t.asInput() == "\"") {
2652                         string s = "\"";
2653                         // These are known pairs. We put them together in
2654                         // one ERT inset. In other cases (such as "a), only
2655                         // the quotation mark is ERTed.
2656                         if (p.next_token().asInput() == "\""
2657                             || p.next_token().asInput() == "|"
2658                             || p.next_token().asInput() == "-"
2659                             || p.next_token().asInput() == "~"
2660                             || p.next_token().asInput() == "="
2661                             || p.next_token().asInput() == "/"
2662                             || p.next_token().asInput() == "~"
2663                             || p.next_token().asInput() == "'"
2664                             || p.next_token().asInput() == "`"
2665                             || p.next_token().asInput() == "<"
2666                             || p.next_token().asInput() == ">") {
2667                                 s += p.next_token().asInput();
2668                                 p.get_token();
2669                         }
2670                         output_ert_inset(os, s, context);
2671                 }
2672
2673                 else if (t.character() == '[' && noweb_mode &&
2674                          p.next_token().character() == '[') {
2675                         // These can contain underscores
2676                         p.putback();
2677                         string const s = p.getFullOpt() + ']';
2678                         if (p.next_token().character() == ']')
2679                                 p.get_token();
2680                         else
2681                                 cerr << "Warning: Inserting missing ']' in '"
2682                                      << s << "'." << endl;
2683                         output_ert_inset(os, s, context);
2684                 }
2685
2686                 else if (t.cat() == catLetter) {
2687                         context.check_layout(os);
2688                         os << t.cs();
2689                 }
2690
2691                 else if (t.cat() == catOther ||
2692                                t.cat() == catAlign ||
2693                                t.cat() == catParameter) {
2694                         context.check_layout(os);
2695                         if (t.asInput() == "-" && p.next_token().asInput() == "-" &&
2696                             context.merging_hyphens_allowed &&
2697                             context.font.family != "ttfamily" &&
2698                             !context.layout->pass_thru) {
2699                                 if (p.next_next_token().asInput() == "-") {
2700                                         // --- is emdash
2701                                         os << to_utf8(docstring(1, 0x2014));
2702                                         p.get_token();
2703                                 } else
2704                                         // -- is endash
2705                                         os << to_utf8(docstring(1, 0x2013));
2706                                 p.get_token();
2707                         } else
2708                                 // This translates "&" to "\\&" which may be wrong...
2709                                 os << t.cs();
2710                 }
2711
2712                 else if (p.isParagraph()) {
2713                         // In minted floating listings we will collect
2714                         // everything into the caption, where multiple
2715                         // paragraphs are forbidden.
2716                         if (minted_float.empty()) {
2717                                 if (context.new_layout_allowed)
2718                                         context.new_paragraph(os);
2719                                 else
2720                                         output_ert_inset(os, "\\par ", context);
2721                         } else
2722                                 os << ' ';
2723                         eat_whitespace(p, os, context, true);
2724                 }
2725
2726                 else if (t.cat() == catActive) {
2727                         context.check_layout(os);
2728                         if (t.character() == '~') {
2729                                 if (context.layout->free_spacing)
2730                                         os << ' ';
2731                                 else {
2732                                         begin_inset(os, "space ~\n");
2733                                         end_inset(os);
2734                                 }
2735                         } else
2736                                 os << t.cs();
2737                 }
2738
2739                 else if (t.cat() == catBegin) {
2740                         Token const next = p.next_token();
2741                         Token const end = p.next_next_token();
2742                         if (next.cat() == catEnd) {
2743                                 // {}
2744                                 Token const prev = p.prev_token();
2745                                 p.get_token();
2746                                 if (p.next_token().character() == '`')
2747                                         ; // ignore it in {}``
2748                                 else
2749                                         output_ert_inset(os, "{}", context);
2750                         } else if (next.cat() == catEscape &&
2751                                    is_known(next.cs(), known_quotes) &&
2752                                    end.cat() == catEnd) {
2753                                 // Something like {\textquoteright} (e.g.
2754                                 // from writer2latex). LyX writes
2755                                 // \textquoteright{}, so we may skip the
2756                                 // braces here for better readability.
2757                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2758                                                    outer, context);
2759                         } else if (p.next_token().asInput() == "\\ascii") {
2760                                 // handle the \ascii characters
2761                                 // (the case without braces is handled later)
2762                                 // the code is "{\ascii\xxx}"
2763                                 p.get_token(); // eat \ascii
2764                                 string name2 = p.get_token().asInput();
2765                                 p.get_token(); // eat the final '}'
2766                                 string const name = "{\\ascii" + name2 + "}";
2767                                 bool termination;
2768                                 docstring rem;
2769                                 set<string> req;
2770                                 // get the character from unicodesymbols
2771                                 docstring s = encodings.fromLaTeXCommand(from_utf8(name),
2772                                         Encodings::TEXT_CMD, termination, rem, &req);
2773                                 if (!s.empty()) {
2774                                         context.check_layout(os);
2775                                         os << to_utf8(s);
2776                                         if (!rem.empty())
2777                                                 output_ert_inset(os,
2778                                                         to_utf8(rem), context);
2779                                         for (set<string>::const_iterator it = req.begin();
2780                                              it != req.end(); ++it)
2781                                                 preamble.registerAutomaticallyLoadedPackage(*it);
2782                                 } else
2783                                         // we did not find a non-ert version
2784                                         output_ert_inset(os, name, context);
2785                         } else {
2786                         context.check_layout(os);
2787                         // special handling of font attribute changes
2788                         Token const prev = p.prev_token();
2789                         TeXFont const oldFont = context.font;
2790                         if (next.character() == '[' ||
2791                             next.character() == ']' ||
2792                             next.character() == '*') {
2793                                 p.get_token();
2794                                 if (p.next_token().cat() == catEnd) {
2795                                         os << next.cs();
2796                                         p.get_token();
2797                                 } else {
2798                                         p.putback();
2799                                         output_ert_inset(os, "{", context);
2800                                         parse_text_snippet(p, os,
2801                                                         FLAG_BRACE_LAST,
2802                                                         outer, context);
2803                                         output_ert_inset(os, "}", context);
2804                                 }
2805                         } else if (! context.new_layout_allowed) {
2806                                 output_ert_inset(os, "{", context);
2807                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2808                                                    outer, context);
2809                                 output_ert_inset(os, "}", context);
2810                         } else if (is_known(next.cs(), known_sizes)) {
2811                                 // next will change the size, so we must
2812                                 // reset it here
2813                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2814                                                    outer, context);
2815                                 if (!context.atParagraphStart())
2816                                         os << "\n\\size "
2817                                            << context.font.size << "\n";
2818                         } else if (is_known(next.cs(), known_font_families)) {
2819                                 // next will change the font family, so we
2820                                 // must reset it here
2821                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2822                                                    outer, context);
2823                                 if (!context.atParagraphStart())
2824                                         os << "\n\\family "
2825                                            << context.font.family << "\n";
2826                         } else if (is_known(next.cs(), known_font_series)) {
2827                                 // next will change the font series, so we
2828                                 // must reset it here
2829                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2830                                                    outer, context);
2831                                 if (!context.atParagraphStart())
2832                                         os << "\n\\series "
2833                                            << context.font.series << "\n";
2834                         } else if (is_known(next.cs(), known_font_shapes)) {
2835                                 // next will change the font shape, so we
2836                                 // must reset it here
2837                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2838                                                    outer, context);
2839                                 if (!context.atParagraphStart())
2840                                         os << "\n\\shape "
2841                                            << context.font.shape << "\n";
2842                         } else if (is_known(next.cs(), known_old_font_families) ||
2843                                    is_known(next.cs(), known_old_font_series) ||
2844                                    is_known(next.cs(), known_old_font_shapes)) {
2845                                 // next will change the font family, series
2846                                 // and shape, so we must reset it here
2847                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2848                                                    outer, context);
2849                                 if (!context.atParagraphStart())
2850                                         os <<  "\n\\family "
2851                                            << context.font.family
2852                                            << "\n\\series "
2853                                            << context.font.series
2854                                            << "\n\\shape "
2855                                            << context.font.shape << "\n";
2856                         } else {
2857                                 output_ert_inset(os, "{", context);
2858                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2859                                                    outer, context);
2860                                 output_ert_inset(os, "}", context);
2861                                 }
2862                         }
2863                 }
2864
2865                 else if (t.cat() == catEnd) {
2866                         if (flags & FLAG_BRACE_LAST) {
2867                                 return;
2868                         }
2869                         cerr << "stray '}' in text\n";
2870                         output_ert_inset(os, "}", context);
2871                 }
2872
2873                 else if (t.cat() == catComment)
2874                         parse_comment(p, os, t, context);
2875
2876                 //
2877                 // control sequences
2878                 //
2879
2880                 else if (t.cs() == "(" || t.cs() == "[") {
2881                         bool const simple = t.cs() == "(";
2882                         context.check_layout(os);
2883                         begin_inset(os, "Formula");
2884                         os << " \\" << t.cs();
2885                         parse_math(p, os, simple ? FLAG_SIMPLE2 : FLAG_EQUATION, MATH_MODE);
2886                         os << '\\' << (simple ? ')' : ']');
2887                         end_inset(os);
2888                         if (!simple) {
2889                                 // Prevent the conversion of a line break to a
2890                                 // space (bug 7668). This does not change the
2891                                 // output, but looks ugly in LyX.
2892                                 eat_whitespace(p, os, context, false);
2893                         }
2894                 }
2895
2896                 else if (t.cs() == "begin")
2897                         parse_environment(p, os, outer, last_env,
2898                                           context);
2899
2900                 else if (t.cs() == "end") {
2901                         if (flags & FLAG_END) {
2902                                 // eat environment name
2903                                 string const name = p.getArg('{', '}');
2904                                 if (name != active_environment())
2905                                         cerr << "\\end{" + name + "} does not match \\begin{"
2906                                                 + active_environment() + "}\n";
2907                                 return;
2908                         }
2909                         p.error("found 'end' unexpectedly");
2910                 }
2911
2912                 else if (t.cs() == "item") {
2913                         string s;
2914                         bool const optarg = p.hasOpt();
2915                         if (optarg) {
2916                                 // FIXME: This swallows comments, but we cannot use
2917                                 //        eat_whitespace() since we must not output
2918                                 //        anything before the item.
2919                                 p.skip_spaces(true);
2920                                 s = p.verbatimOption();
2921                         } else
2922                                 p.skip_spaces(false);
2923                         context.set_item();
2924                         context.check_layout(os);
2925                         if (context.has_item) {
2926                                 // An item in an unknown list-like environment
2927                                 // FIXME: Do this in check_layout()!
2928                                 context.has_item = false;
2929                                 if (optarg)
2930                                         output_ert_inset(os, "\\item", context);
2931                                 else
2932                                         output_ert_inset(os, "\\item ", context);
2933                         }
2934                         if (optarg) {
2935                                 if (context.layout->labeltype != LABEL_MANUAL) {
2936                                         // handle option of itemize item
2937                                         begin_inset(os, "Argument item:1\n");
2938                                         os << "status open\n";
2939                                         os << "\n\\begin_layout Plain Layout\n";
2940                                         Parser p2(s + ']');
2941                                         os << parse_text_snippet(p2,
2942                                                 FLAG_BRACK_LAST, outer, context);
2943                                         // we must not use context.check_end_layout(os)
2944                                         // because that would close the outer itemize layout
2945                                         os << "\n\\end_layout\n";
2946                                         end_inset(os);
2947                                         eat_whitespace(p, os, context, false);
2948                                 } else if (!s.empty()) {
2949                                         // LyX adds braces around the argument,
2950                                         // so we need to remove them here.
2951                                         if (s.size() > 2 && s[0] == '{' &&
2952                                             s[s.size()-1] == '}')
2953                                                 s = s.substr(1, s.size()-2);
2954                                         // If the argument contains a space we
2955                                         // must put it into ERT: Otherwise LyX
2956                                         // would misinterpret the space as
2957                                         // item delimiter (bug 7663)
2958                                         if (contains(s, ' ')) {
2959                                                 output_ert_inset(os, s, context);
2960                                         } else {
2961                                                 Parser p2(s + ']');
2962                                                 os << parse_text_snippet(p2,
2963                                                         FLAG_BRACK_LAST, outer, context);
2964                                         }
2965                                         // The space is needed to separate the
2966                                         // item from the rest of the sentence.
2967                                         os << ' ';
2968                                         eat_whitespace(p, os, context, false);
2969                                 }
2970                         }
2971                 }
2972
2973                 else if (t.cs() == "bibitem") {
2974                         context.set_item();
2975                         context.check_layout(os);
2976                         eat_whitespace(p, os, context, false);
2977                         string label = convert_command_inset_arg(p.verbatimOption());
2978                         string key = convert_command_inset_arg(p.verbatim_item());
2979                         if (contains(label, '\\') || contains(key, '\\')) {
2980                                 // LyX can't handle LaTeX commands in labels or keys
2981                                 output_ert_inset(os, t.asInput() + '[' + label +
2982                                                "]{" + p.verbatim_item() + '}',
2983                                            context);
2984                         } else {
2985                                 begin_command_inset(os, "bibitem", "bibitem");
2986                                 os << "label \"" << label << "\"\n"
2987                                    << "key \"" << key << "\"\n"
2988                                    << "literal \"true\"\n";
2989                                 end_inset(os);
2990                         }
2991                 }
2992
2993                 else if (is_macro(p)) {
2994                         // catch the case of \def\inputGnumericTable
2995                         bool macro = true;
2996                         if (t.cs() == "def") {
2997                                 Token second = p.next_token();
2998                                 if (second.cs() == "inputGnumericTable") {
2999                                         p.pushPosition();
3000                                         p.get_token();
3001                                         skip_braces(p);
3002                                         Token third = p.get_token();
3003                                         p.popPosition();
3004                                         if (third.cs() == "input") {
3005                                                 p.get_token();
3006                                                 skip_braces(p);
3007                                                 p.get_token();
3008                                                 string name = normalize_filename(p.verbatim_item());
3009                                                 string const path = getMasterFilePath(true);
3010                                                 // We want to preserve relative / absolute filenames,
3011                                                 // therefore path is only used for testing
3012                                                 // The file extension is in every case ".tex".
3013                                                 // So we need to remove this extension and check for
3014                                                 // the original one.
3015                                                 name = removeExtension(name);
3016                                                 if (!makeAbsPath(name, path).exists()) {
3017                                                         char const * const Gnumeric_formats[] = {"gnumeric",
3018                                                                 "ods", "xls", 0};
3019                                                         string const Gnumeric_name =
3020                                                                 find_file(name, path, Gnumeric_formats);
3021                                                         if (!Gnumeric_name.empty())
3022                                                                 name = Gnumeric_name;
3023                                                 }
3024                                                 FileName const absname = makeAbsPath(name, path);
3025                                                 if (absname.exists()) {
3026                                                         fix_child_filename(name);
3027                                                         copy_file(absname, name);
3028                                                 } else
3029                                                         cerr << "Warning: Could not find file '"
3030                                                              << name << "'." << endl;
3031                                                 context.check_layout(os);
3032                                                 begin_inset(os, "External\n\ttemplate ");
3033                                                 os << "GnumericSpreadsheet\n\tfilename "
3034                                                    << name << "\n";
3035                                                 end_inset(os);
3036                                                 context.check_layout(os);
3037                                                 macro = false;
3038                                                 // register the packages that are automatically loaded
3039                                                 // by the Gnumeric template
3040                                                 registerExternalTemplatePackages("GnumericSpreadsheet");
3041                                         }
3042                                 }
3043                         }
3044                         if (macro)
3045                                 parse_macro(p, os, context);
3046                 }
3047
3048                 else if (t.cs() == "noindent") {
3049                         p.skip_spaces();
3050                         context.add_par_extra_stuff("\\noindent\n");
3051                 }
3052
3053                 else if (t.cs() == "appendix") {
3054                         context.add_par_extra_stuff("\\start_of_appendix\n");
3055                         // We need to start a new paragraph. Otherwise the
3056                         // appendix in 'bla\appendix\chapter{' would start
3057                         // too late.
3058                         context.new_paragraph(os);
3059                         // We need to make sure that the paragraph is
3060                         // generated even if it is empty. Otherwise the
3061                         // appendix in '\par\appendix\par\chapter{' would
3062                         // start too late.
3063                         context.check_layout(os);
3064                         // FIXME: This is a hack to prevent paragraph
3065                         // deletion if it is empty. Handle this better!
3066                         output_comment(p, os,
3067                                 "dummy comment inserted by tex2lyx to "
3068                                 "ensure that this paragraph is not empty",
3069                                 context);
3070                         // Both measures above may generate an additional
3071                         // empty paragraph, but that does not hurt, because
3072                         // whitespace does not matter here.
3073                         eat_whitespace(p, os, context, true);
3074                 }
3075
3076                 // Must catch empty dates before findLayout is called below
3077                 else if (t.cs() == "date") {
3078                         eat_whitespace(p, os, context, false);
3079                         p.pushPosition();
3080                         string const date = p.verbatim_item();
3081                         p.popPosition();
3082                         if (date.empty()) {
3083                                 preamble.suppressDate(true);
3084                                 p.verbatim_item();
3085                         } else {
3086                                 preamble.suppressDate(false);
3087                                 if (context.new_layout_allowed &&
3088                                     (newlayout = findLayout(context.textclass,
3089                                                             t.cs(), true))) {
3090                                         // write the layout
3091                                         output_command_layout(os, p, outer,
3092                                                         context, newlayout);
3093                                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3094                                         if (!preamble.titleLayoutFound())
3095                                                 preamble.titleLayoutFound(newlayout->intitle);
3096                                         set<string> const & req = newlayout->requires();
3097                                         set<string>::const_iterator it = req.begin();
3098                                         set<string>::const_iterator en = req.end();
3099                                         for (; it != en; ++it)
3100                                                 preamble.registerAutomaticallyLoadedPackage(*it);
3101                                 } else
3102                                         output_ert_inset(os,
3103                                                 "\\date{" + p.verbatim_item() + '}',
3104                                                 context);
3105                         }
3106                 }
3107
3108                 // Starred section headings
3109                 // Must attempt to parse "Section*" before "Section".
3110                 else if ((p.next_token().asInput() == "*") &&
3111                          context.new_layout_allowed &&
3112                          (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
3113                         // write the layout
3114                         p.get_token();
3115                         output_command_layout(os, p, outer, context, newlayout);
3116                         p.skip_spaces();
3117                         if (!preamble.titleLayoutFound())
3118                                 preamble.titleLayoutFound(newlayout->intitle);
3119                         set<string> const & req = newlayout->requires();
3120                         for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3121                                 preamble.registerAutomaticallyLoadedPackage(*it);
3122                 }
3123
3124                 // Section headings and the like
3125                 else if (context.new_layout_allowed &&
3126                          (newlayout = findLayout(context.textclass, t.cs(), true))) {
3127                         // write the layout
3128                         output_command_layout(os, p, outer, context, newlayout);
3129                         p.skip_spaces();
3130                         if (!preamble.titleLayoutFound())
3131                                 preamble.titleLayoutFound(newlayout->intitle);
3132                         set<string> const & req = newlayout->requires();
3133                         for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3134                                 preamble.registerAutomaticallyLoadedPackage(*it);
3135                 }
3136
3137                 else if (t.cs() == "subfloat") {
3138                         // the syntax is \subfloat[list entry][sub caption]{content}
3139                         // if it is a table of figure depends on the surrounding float
3140                         // FIXME: second optional argument is not parsed
3141                         p.skip_spaces();
3142                         // do nothing if there is no outer float
3143                         if (!float_type.empty()) {
3144                                 context.check_layout(os);
3145                                 p.skip_spaces();
3146                                 begin_inset(os, "Float " + float_type + "\n");
3147                                 os << "wide false"
3148                                    << "\nsideways false"
3149                                    << "\nstatus collapsed\n\n";
3150                                 // test for caption
3151                                 string caption;
3152                                 bool has_caption = false;
3153                                 if (p.next_token().cat() != catEscape &&
3154                                                 p.next_token().character() == '[') {
3155                                                         p.get_token(); // eat '['
3156                                                         caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
3157                                                         has_caption = true;
3158                                 }
3159                                 // the content
3160                                 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3161                                 // the caption comes always as the last
3162                                 if (has_caption) {
3163                                         // we must make sure that the caption gets a \begin_layout
3164                                         os << "\n\\begin_layout Plain Layout";
3165                                         p.skip_spaces();
3166                                         begin_inset(os, "Caption Standard\n");
3167                                         Context newcontext(true, context.textclass,
3168                                                            0, 0, context.font);
3169                                         newcontext.check_layout(os);
3170                                         os << caption << "\n";
3171                                         newcontext.check_end_layout(os);
3172                                         // We don't need really a new paragraph, but
3173                                         // we must make sure that the next item gets a \begin_layout.
3174                                         //newcontext.new_paragraph(os);
3175                                         end_inset(os);
3176                                         p.skip_spaces();
3177                                 }
3178                                 // We don't need really a new paragraph, but
3179                                 // we must make sure that the next item gets a \begin_layout.
3180                                 if (has_caption)
3181                                         context.new_paragraph(os);
3182                                 end_inset(os);
3183                                 p.skip_spaces();
3184                                 context.check_end_layout(os);
3185                                 // close the layout we opened
3186                                 if (has_caption)
3187                                         os << "\n\\end_layout\n";
3188                         } else {
3189                                 // if the float type is not supported or there is no surrounding float
3190                                 // output it as ERT
3191                                 if (p.hasOpt()) {
3192                                         string opt_arg = convert_command_inset_arg(p.getArg('[', ']'));
3193                                         output_ert_inset(os, t.asInput() + '[' + opt_arg +
3194                                                "]{" + p.verbatim_item() + '}', context);
3195                                 } else
3196                                         output_ert_inset(os, t.asInput() + "{" + p.verbatim_item() + '}', context);
3197                         }
3198                 }
3199
3200                 else if (t.cs() == "includegraphics") {
3201                         bool const clip = p.next_token().asInput() == "*";
3202                         if (clip)
3203                                 p.get_token();
3204                         string const arg = p.getArg('[', ']');
3205                         map<string, string> opts;
3206                         vector<string> keys;
3207                         split_map(arg, opts, keys);
3208                         if (clip)
3209                                 opts["clip"] = string();
3210                         string name = normalize_filename(p.verbatim_item());
3211
3212                         string const path = getMasterFilePath(true);
3213                         // We want to preserve relative / absolute filenames,
3214                         // therefore path is only used for testing
3215                         if (!makeAbsPath(name, path).exists()) {
3216                                 // The file extension is probably missing.
3217                                 // Now try to find it out.
3218                                 string const dvips_name =
3219                                         find_file(name, path,
3220                                                   known_dvips_graphics_formats);
3221                                 string const pdftex_name =
3222                                         find_file(name, path,
3223                                                   known_pdftex_graphics_formats);
3224                                 if (!dvips_name.empty()) {
3225                                         if (!pdftex_name.empty()) {
3226                                                 cerr << "This file contains the "
3227                                                         "latex snippet\n"
3228                                                         "\"\\includegraphics{"
3229                                                      << name << "}\".\n"
3230                                                         "However, files\n\""
3231                                                      << dvips_name << "\" and\n\""
3232                                                      << pdftex_name << "\"\n"
3233                                                         "both exist, so I had to make a "
3234                                                         "choice and took the first one.\n"
3235                                                         "Please move the unwanted one "
3236                                                         "someplace else and try again\n"
3237                                                         "if my choice was wrong."
3238                                                      << endl;
3239                                         }
3240                                         name = dvips_name;
3241                                 } else if (!pdftex_name.empty()) {
3242                                         name = pdftex_name;
3243                                         pdflatex = true;
3244                                 }
3245                         }
3246
3247                         FileName const absname = makeAbsPath(name, path);
3248                         if (absname.exists()) {
3249                                 fix_child_filename(name);
3250                                 copy_file(absname, name);
3251                         } else
3252                                 cerr << "Warning: Could not find graphics file '"
3253                                      << name << "'." << endl;
3254
3255                         context.check_layout(os);
3256                         begin_inset(os, "Graphics ");
3257                         os << "\n\tfilename " << name << '\n';
3258                         if (opts.find("width") != opts.end())
3259                                 os << "\twidth "
3260                                    << translate_len(opts["width"]) << '\n';
3261                         if (opts.find("height") != opts.end())
3262                                 os << "\theight "
3263                                    << translate_len(opts["height"]) << '\n';
3264                         if (opts.find("scale") != opts.end()) {
3265                                 istringstream iss(opts["scale"]);
3266                                 double val;
3267                                 iss >> val;
3268                                 val = val*100;
3269                                 os << "\tscale " << val << '\n';
3270                         }
3271                         if (opts.find("angle") != opts.end()) {
3272                                 os << "\trotateAngle "
3273                                    << opts["angle"] << '\n';
3274                                 vector<string>::const_iterator a =
3275                                         find(keys.begin(), keys.end(), "angle");
3276                                 vector<string>::const_iterator s =
3277                                         find(keys.begin(), keys.end(), "width");
3278                                 if (s == keys.end())
3279                                         s = find(keys.begin(), keys.end(), "height");
3280                                 if (s == keys.end())
3281                                         s = find(keys.begin(), keys.end(), "scale");
3282                                 if (s != keys.end() && distance(s, a) > 0)
3283                                         os << "\tscaleBeforeRotation\n";
3284                         }
3285                         if (opts.find("origin") != opts.end()) {
3286                                 ostringstream ss;
3287                                 string const opt = opts["origin"];
3288                                 if (opt.find('l') != string::npos) ss << "left";
3289                                 if (opt.find('r') != string::npos) ss << "right";
3290                                 if (opt.find('c') != string::npos) ss << "center";
3291                                 if (opt.find('t') != string::npos) ss << "Top";
3292                                 if (opt.find('b') != string::npos) ss << "Bottom";
3293                                 if (opt.find('B') != string::npos) ss << "Baseline";
3294                                 if (!ss.str().empty())
3295                                         os << "\trotateOrigin " << ss.str() << '\n';
3296                                 else
3297                                         cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
3298                         }
3299                         if (opts.find("keepaspectratio") != opts.end())
3300                                 os << "\tkeepAspectRatio\n";
3301                         if (opts.find("clip") != opts.end())
3302                                 os << "\tclip\n";
3303                         if (opts.find("draft") != opts.end())
3304                                 os << "\tdraft\n";
3305                         if (opts.find("bb") != opts.end())
3306                                 os << "\tBoundingBox "
3307                                    << opts["bb"] << '\n';
3308                         int numberOfbbOptions = 0;
3309                         if (opts.find("bbllx") != opts.end())
3310                                 numberOfbbOptions++;
3311                         if (opts.find("bblly") != opts.end())
3312                                 numberOfbbOptions++;
3313                         if (opts.find("bburx") != opts.end())
3314                                 numberOfbbOptions++;
3315                         if (opts.find("bbury") != opts.end())
3316                                 numberOfbbOptions++;
3317                         if (numberOfbbOptions == 4)
3318                                 os << "\tBoundingBox "
3319                                    << opts["bbllx"] << " " << opts["bblly"] << " "
3320                                    << opts["bburx"] << " " << opts["bbury"] << '\n';
3321                         else if (numberOfbbOptions > 0)
3322                                 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3323                         numberOfbbOptions = 0;
3324                         if (opts.find("natwidth") != opts.end())
3325                                 numberOfbbOptions++;
3326                         if (opts.find("natheight") != opts.end())
3327                                 numberOfbbOptions++;
3328                         if (numberOfbbOptions == 2)
3329                                 os << "\tBoundingBox 0bp 0bp "
3330                                    << opts["natwidth"] << " " << opts["natheight"] << '\n';
3331                         else if (numberOfbbOptions > 0)
3332                                 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3333                         ostringstream special;
3334                         if (opts.find("hiresbb") != opts.end())
3335                                 special << "hiresbb,";
3336                         if (opts.find("trim") != opts.end())
3337                                 special << "trim,";
3338                         if (opts.find("viewport") != opts.end())
3339                                 special << "viewport=" << opts["viewport"] << ',';
3340                         if (opts.find("totalheight") != opts.end())
3341                                 special << "totalheight=" << opts["totalheight"] << ',';
3342                         if (opts.find("type") != opts.end())
3343                                 special << "type=" << opts["type"] << ',';
3344                         if (opts.find("ext") != opts.end())
3345                                 special << "ext=" << opts["ext"] << ',';
3346                         if (opts.find("read") != opts.end())
3347                                 special << "read=" << opts["read"] << ',';
3348                         if (opts.find("command") != opts.end())
3349                                 special << "command=" << opts["command"] << ',';
3350                         string s_special = special.str();
3351                         if (!s_special.empty()) {
3352                                 // We had special arguments. Remove the trailing ','.
3353                                 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
3354                         }
3355                         // TODO: Handle the unknown settings better.
3356                         // Warn about invalid options.
3357                         // Check whether some option was given twice.
3358                         end_inset(os);
3359                         preamble.registerAutomaticallyLoadedPackage("graphicx");
3360                 }
3361
3362                 else if (t.cs() == "footnote" ||
3363                          (t.cs() == "thanks" && context.layout->intitle)) {
3364                         p.skip_spaces();
3365                         context.check_layout(os);
3366                         begin_inset(os, "Foot\n");
3367                         os << "status collapsed\n\n";
3368                         parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3369                         end_inset(os);
3370                 }
3371
3372                 else if (t.cs() == "marginpar") {
3373                         p.skip_spaces();
3374                         context.check_layout(os);
3375                         begin_inset(os, "Marginal\n");
3376                         os << "status collapsed\n\n";
3377                         parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3378                         end_inset(os);
3379                 }
3380
3381                 else if (t.cs() == "lstinline" || t.cs() == "mintinline") {
3382                         bool const use_minted = t.cs() == "mintinline";
3383                         p.skip_spaces();
3384                         parse_listings(p, os, context, true, use_minted);
3385                 }
3386
3387                 else if (t.cs() == "ensuremath") {
3388                         p.skip_spaces();
3389                         context.check_layout(os);
3390                         string const s = p.verbatim_item();
3391                         //FIXME: this never triggers in UTF8
3392                         if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
3393                                 os << s;
3394                         else
3395                                 output_ert_inset(os, "\\ensuremath{" + s + "}",
3396                                            context);
3397                 }
3398
3399                 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
3400                         if (preamble.titleLayoutFound()) {
3401                                 // swallow this
3402                                 skip_spaces_braces(p);
3403                         } else
3404                                 output_ert_inset(os, t.asInput(), context);
3405                 }
3406
3407                 else if (t.cs() == "tableofcontents"
3408                                 || t.cs() == "lstlistoflistings"
3409                                 || t.cs() == "listoflistings") {
3410                         string name = t.cs();
3411                         if (preamble.minted() && name == "listoflistings")
3412                                 name.insert(0, "lst");
3413                         context.check_layout(os);
3414                         begin_command_inset(os, "toc", name);
3415                         end_inset(os);
3416                         skip_spaces_braces(p);
3417                         if (name == "lstlistoflistings") {
3418                                 if (preamble.minted())
3419                                         preamble.registerAutomaticallyLoadedPackage("minted");
3420                                 else
3421                                         preamble.registerAutomaticallyLoadedPackage("listings");
3422                         }
3423                 }
3424
3425                 else if (t.cs() == "listoffigures" || t.cs() == "listoftables") {
3426                         context.check_layout(os);
3427                         if (t.cs() == "listoffigures")
3428                                 begin_inset(os, "FloatList figure\n");
3429                         else
3430                                 begin_inset(os, "FloatList table\n");
3431                         end_inset(os);
3432                         skip_spaces_braces(p);
3433                 }
3434
3435                 else if (t.cs() == "listof") {
3436                         p.skip_spaces(true);
3437                         string const name = p.get_token().cs();
3438                         if (context.textclass.floats().typeExist(name)) {
3439                                 context.check_layout(os);
3440                                 begin_inset(os, "FloatList ");
3441                                 os << name << "\n";
3442                                 end_inset(os);
3443                                 p.get_token(); // swallow second arg
3444                         } else
3445                                 output_ert_inset(os, "\\listof{" + name + "}", context);
3446                 }
3447
3448                 else if ((where = is_known(t.cs(), known_text_font_families)))
3449                         parse_text_attributes(p, os, FLAG_ITEM, outer,
3450                                 context, "\\family", context.font.family,
3451                                 known_coded_font_families[where - known_text_font_families]);
3452
3453                 else if ((where = is_known(t.cs(), known_text_font_series)))
3454                         parse_text_attributes(p, os, FLAG_ITEM, outer,
3455                                 context, "\\series", context.font.series,
3456                                 known_coded_font_series[where - known_text_font_series]);
3457
3458                 else if ((where = is_known(t.cs(), known_text_font_shapes)))
3459                         parse_text_attributes(p, os, FLAG_ITEM, outer,
3460                                 context, "\\shape", context.font.shape,
3461                                 known_coded_font_shapes[where - known_text_font_shapes]);
3462
3463                 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
3464                         context.check_layout(os);
3465                         TeXFont oldFont = context.font;
3466                         context.font.init();
3467                         context.font.size = oldFont.size;
3468                         os << "\n\\family " << context.font.family << "\n";
3469                         os << "\n\\series " << context.font.series << "\n";
3470                         os << "\n\\shape " << context.font.shape << "\n";
3471                         if (t.cs() == "textnormal") {
3472                                 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3473                                 output_font_change(os, context.font, oldFont);
3474                                 context.font = oldFont;
3475                         } else
3476                                 eat_whitespace(p, os, context, false);
3477                 }
3478
3479                 else if (t.cs() == "textcolor") {
3480                         // scheme is \textcolor{color name}{text}
3481                         string const color = p.verbatim_item();
3482                         // we support the predefined colors of the color  and the xcolor package
3483                         if (color == "black" || color == "blue" || color == "cyan"
3484                                 || color == "green" || color == "magenta" || color == "red"
3485                                 || color == "white" || color == "yellow") {
3486                                         context.check_layout(os);
3487                                         os << "\n\\color " << color << "\n";
3488                                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3489                                         context.check_layout(os);
3490                                         os << "\n\\color inherit\n";
3491                                         preamble.registerAutomaticallyLoadedPackage("color");
3492                         } else if (color == "brown" || color == "darkgray" || color == "gray"
3493                                 || color == "lightgray" || color == "lime" || color == "olive"
3494                                 || color == "orange" || color == "pink" || color == "purple"
3495                                 || color == "teal" || color == "violet") {
3496                                         context.check_layout(os);
3497                                         os << "\n\\color " << color << "\n";
3498                                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3499                                         context.check_layout(os);
3500                                         os << "\n\\color inherit\n";
3501                                         preamble.registerAutomaticallyLoadedPackage("xcolor");
3502                         } else
3503                                 // for custom defined colors
3504                                 output_ert_inset(os, t.asInput() + "{" + color + "}", context);
3505                 }
3506
3507                 else if (t.cs() == "underbar" || t.cs() == "uline") {
3508                         // \underbar is not 100% correct (LyX outputs \uline
3509                         // of ulem.sty). The difference is that \ulem allows
3510                         // line breaks, and \underbar does not.
3511                         // Do NOT handle \underline.
3512                         // \underbar cuts through y, g, q, p etc.,
3513                         // \underline does not.
3514                         context.check_layout(os);
3515                         os << "\n\\bar under\n";
3516                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3517                         context.check_layout(os);
3518                         os << "\n\\bar default\n";
3519                         preamble.registerAutomaticallyLoadedPackage("ulem");
3520                 }
3521
3522                 else if (t.cs() == "sout") {
3523                         context.check_layout(os);
3524                         os << "\n\\strikeout on\n";
3525                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3526                         context.check_layout(os);
3527                         os << "\n\\strikeout default\n";
3528                         preamble.registerAutomaticallyLoadedPackage("ulem");
3529                 }
3530
3531                 else if (t.cs() == "uuline" || t.cs() == "uwave"
3532                         || t.cs() == "emph" || t.cs() == "noun"
3533                         || t.cs() == "xout") {
3534                         context.check_layout(os);
3535                         os << "\n\\" << t.cs() << " on\n";
3536                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3537                         context.check_layout(os);
3538                         os << "\n\\" << t.cs() << " default\n";
3539                         if (t.cs() == "uuline" || t.cs() == "uwave" || t.cs() == "xout")
3540                                 preamble.registerAutomaticallyLoadedPackage("ulem");
3541                 }
3542
3543                 else if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
3544                         context.check_layout(os);
3545                         string name = p.getArg('{', '}');
3546                         string localtime = p.getArg('{', '}');
3547                         preamble.registerAuthor(name);
3548                         Author const & author = preamble.getAuthor(name);
3549                         // from_asctime_utc() will fail if LyX decides to output the
3550                         // time in the text language.
3551                         time_t ptime = from_asctime_utc(localtime);
3552                         if (ptime == static_cast<time_t>(-1)) {
3553                                 cerr << "Warning: Could not parse time `" << localtime
3554                                      << "´ for change tracking, using current time instead.\n";
3555                                 ptime = current_time();
3556                         }
3557                         if (t.cs() == "lyxadded")
3558                                 os << "\n\\change_inserted ";
3559                         else
3560                                 os << "\n\\change_deleted ";
3561                         os << author.bufferId() << ' ' << ptime << '\n';
3562                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3563                         bool dvipost    = LaTeXPackages::isAvailable("dvipost");
3564                         bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
3565                                           LaTeXPackages::isAvailable("xcolor");
3566                         // No need to test for luatex, since luatex comes in
3567                         // two flavours (dvi and pdf), like latex, and those
3568                         // are detected by pdflatex.
3569                         if (pdflatex || xetex) {
3570                                 if (xcolorulem) {
3571                                         preamble.registerAutomaticallyLoadedPackage("ulem");
3572                                         preamble.registerAutomaticallyLoadedPackage("xcolor");
3573                                         preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
3574                                 }
3575                         } else {
3576                                 if (dvipost) {
3577                                         preamble.registerAutomaticallyLoadedPackage("dvipost");
3578                                 } else if (xcolorulem) {
3579                                         preamble.registerAutomaticallyLoadedPackage("ulem");
3580                                         preamble.registerAutomaticallyLoadedPackage("xcolor");
3581                                 }
3582                         }
3583                 }
3584
3585                 else if (t.cs() == "textipa") {
3586                         context.check_layout(os);
3587                         begin_inset(os, "IPA\n");
3588                         bool merging_hyphens_allowed = context.merging_hyphens_allowed;
3589                         context.merging_hyphens_allowed = false;
3590                         parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3591                         context.merging_hyphens_allowed = merging_hyphens_allowed;
3592                         end_inset(os);
3593                         preamble.registerAutomaticallyLoadedPackage("tipa");
3594                         preamble.registerAutomaticallyLoadedPackage("tipx");
3595                 }
3596
3597                 else if (t.cs() == "texttoptiebar" || t.cs() == "textbottomtiebar") {
3598                         context.check_layout(os);
3599                         begin_inset(os, "IPADeco " + t.cs().substr(4) + "\n");
3600                         os << "status open\n";
3601                         parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3602                         end_inset(os);
3603                         p.skip_spaces();
3604                 }
3605
3606                 else if (t.cs() == "textvertline") {
3607                         // FIXME: This is not correct, \textvertline is higher than |
3608                         os << "|";
3609                         skip_braces(p);
3610                         continue;
3611                 }
3612
3613                 else if (t.cs() == "tone" ) {
3614                         context.check_layout(os);
3615                         // register the tone package
3616                         preamble.registerAutomaticallyLoadedPackage("tone");
3617                         string content = trimSpaceAndEol(p.verbatim_item());
3618                         string command = t.asInput() + "{" + content + "}";
3619                         // some tones can be detected by unicodesymbols, some need special code
3620                         if (is_known(content, known_tones)) {
3621                                 os << "\\IPAChar " << command << "\n";
3622                                 continue;
3623                         }
3624                         // try to see whether the string is in unicodesymbols
3625                         bool termination;
3626                         docstring rem;
3627                         set<string> req;
3628                         docstring s = encodings.fromLaTeXCommand(from_utf8(command),
3629                                 Encodings::TEXT_CMD | Encodings::MATH_CMD,
3630                                 termination, rem, &req);
3631                         if (!s.empty()) {
3632                                 os << to_utf8(s);
3633                                 if (!rem.empty())
3634                                         output_ert_inset(os, to_utf8(rem), context);
3635                                 for (set<string>::const_iterator it = req.begin();
3636                                      it != req.end(); ++it)
3637                                         preamble.registerAutomaticallyLoadedPackage(*it);
3638                         } else
3639                                 // we did not find a non-ert version
3640                                 output_ert_inset(os, command, context);
3641                 }
3642
3643                 else if (t.cs() == "phantom" || t.cs() == "hphantom" ||
3644                              t.cs() == "vphantom") {
3645                         context.check_layout(os);
3646                         if (t.cs() == "phantom")
3647                                 begin_inset(os, "Phantom Phantom\n");
3648                         if (t.cs() == "hphantom")
3649                                 begin_inset(os, "Phantom HPhantom\n");
3650                         if (t.cs() == "vphantom")
3651                                 begin_inset(os, "Phantom VPhantom\n");
3652                         os << "status open\n";
3653                         parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
3654                                             "Phantom");
3655                         end_inset(os);
3656                 }
3657
3658                 else if (t.cs() == "href") {
3659                         context.check_layout(os);
3660                         string target = convert_command_inset_arg(p.verbatim_item());
3661                         string name = convert_command_inset_arg(p.verbatim_item());
3662                         string type;
3663                         size_t i = target.find(':');
3664                         if (i != string::npos) {
3665                                 type = target.substr(0, i + 1);
3666                                 if (type == "mailto:" || type == "file:")
3667                                         target = target.substr(i + 1);
3668                                 // handle the case that name is equal to target, except of "http(s)://"
3669                                 else if (target.substr(i + 3) == name && (type == "http:" || type == "https:"))
3670                                         target = name;
3671                         }
3672                         begin_command_inset(os, "href", "href");
3673                         if (name != target)
3674                                 os << "name \"" << name << "\"\n";
3675                         os << "target \"" << target << "\"\n";
3676                         if (type == "mailto:" || type == "file:")
3677                                 os << "type \"" << type << "\"\n";
3678                         os << "literal \"true\"\n";
3679                         end_inset(os);
3680                         skip_spaces_braces(p);
3681                 }
3682
3683                 else if (t.cs() == "lyxline") {
3684                         // swallow size argument (it is not used anyway)
3685                         p.getArg('{', '}');
3686                         if (!context.atParagraphStart()) {
3687                                 // so our line is in the middle of a paragraph
3688                                 // we need to add a new line, lest this line
3689                                 // follow the other content on that line and
3690                                 // run off the side of the page
3691                                 // FIXME: This may create an empty paragraph,
3692                                 //        but without that it would not be
3693                                 //        possible to set noindent below.
3694                                 //        Fortunately LaTeX does not care
3695                                 //        about the empty paragraph.
3696                                 context.new_paragraph(os);
3697                         }
3698                         if (preamble.indentParagraphs()) {
3699                                 // we need to unindent, lest the line be too long
3700                                 context.add_par_extra_stuff("\\noindent\n");
3701                         }
3702                         context.check_layout(os);
3703                         begin_command_inset(os, "line", "rule");
3704                         os << "offset \"0.5ex\"\n"
3705                               "width \"100line%\"\n"
3706                               "height \"1pt\"\n";
3707                         end_inset(os);
3708                 }
3709
3710                 else if (t.cs() == "rule") {
3711                         string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
3712                         string const width = p.getArg('{', '}');
3713                         string const thickness = p.getArg('{', '}');
3714                         context.check_layout(os);
3715                         begin_command_inset(os, "line", "rule");
3716                         if (!offset.empty())
3717                                 os << "offset \"" << translate_len(offset) << "\"\n";
3718                         os << "width \"" << translate_len(width) << "\"\n"
3719                                   "height \"" << translate_len(thickness) << "\"\n";
3720                         end_inset(os);
3721                 }
3722
3723                 // handle refstyle first to catch \eqref which can also occur
3724                 // without refstyle. Only recognize these commands if
3725                 // refstyle.sty was found in the preamble (otherwise \eqref
3726                 // and user defined ref commands could be misdetected).
3727                 else if ((where = is_known(t.cs(), known_refstyle_commands)) &&
3728                          preamble.refstyle()) {
3729                         context.check_layout(os);
3730                         begin_command_inset(os, "ref", "formatted");
3731                         os << "reference \"";
3732                         os << known_refstyle_prefixes[where - known_refstyle_commands]
3733                            << ":";
3734                         os << convert_command_inset_arg(p.verbatim_item())
3735                            << "\"\n";
3736                         os << "plural \"false\"\n";
3737                         os << "caps \"false\"\n";
3738                         os << "noprefix \"false\"\n";
3739                         end_inset(os);
3740                         preamble.registerAutomaticallyLoadedPackage("refstyle");
3741                 }
3742
3743                 // if refstyle is used, we must not convert \prettyref to a
3744                 // formatted reference, since that would result in a refstyle command.
3745                 else if ((where = is_known(t.cs(), known_ref_commands)) &&
3746                          (t.cs() != "prettyref" || !preamble.refstyle())) {
3747                         string const opt = p.getOpt();
3748                         if (opt.empty()) {
3749                                 context.check_layout(os);
3750                                 begin_command_inset(os, "ref",
3751                                         known_coded_ref_commands[where - known_ref_commands]);
3752                                 os << "reference \""
3753                                    << convert_command_inset_arg(p.verbatim_item())
3754                                    << "\"\n";
3755                                 os << "plural \"false\"\n";
3756                                 os << "caps \"false\"\n";
3757                                 os << "noprefix \"false\"\n";
3758                                 end_inset(os);
3759                                 if (t.cs() == "vref" || t.cs() == "vpageref")
3760                                         preamble.registerAutomaticallyLoadedPackage("varioref");
3761                                 else if (t.cs() == "prettyref")
3762                                         preamble.registerAutomaticallyLoadedPackage("prettyref");
3763                         } else {
3764                                 // LyX does not yet support optional arguments of ref commands
3765                                 output_ert_inset(os, t.asInput() + '[' + opt + "]{" +
3766                                        p.verbatim_item() + '}', context);
3767                         }
3768                 }
3769
3770                 else if (use_natbib &&
3771                          is_known(t.cs(), known_natbib_commands) &&
3772                          ((t.cs() != "citefullauthor" &&
3773                            t.cs() != "citeyear" &&
3774                            t.cs() != "citeyearpar") ||
3775                           p.next_token().asInput() != "*")) {
3776                         context.check_layout(os);
3777                         string command = t.cs();
3778                         if (p.next_token().asInput() == "*") {
3779                                 command += '*';
3780                                 p.get_token();
3781                         }
3782                         if (command == "citefullauthor")
3783                                 // alternative name for "\\citeauthor*"
3784                                 command = "citeauthor*";
3785
3786                         // text before the citation
3787                         string before;
3788                         // text after the citation
3789                         string after;
3790                         get_cite_arguments(p, true, before, after);
3791
3792                         if (command == "cite") {
3793                                 // \cite without optional argument means
3794                                 // \citet, \cite with at least one optional
3795                                 // argument means \citep.
3796                                 if (before.empty() && after.empty())
3797                                         command = "citet";
3798                                 else
3799                                         command = "citep";
3800                         }
3801                         if (before.empty() && after == "[]")
3802                                 // avoid \citet[]{a}
3803                                 after.erase();
3804                         else if (before == "[]" && after == "[]") {
3805                                 // avoid \citet[][]{a}
3806                                 before.erase();
3807                                 after.erase();
3808                         }
3809                         // remove the brackets around after and before
3810                         if (!after.empty()) {
3811                                 after.erase(0, 1);
3812                                 after.erase(after.length() - 1, 1);
3813                                 after = convert_command_inset_arg(after);
3814                         }
3815                         if (!before.empty()) {
3816                                 before.erase(0, 1);
3817                                 before.erase(before.length() - 1, 1);
3818                                 before = convert_command_inset_arg(before);
3819                         }
3820                         begin_command_inset(os, "citation", command);
3821                         os << "after " << '"' << after << '"' << "\n";
3822                         os << "before " << '"' << before << '"' << "\n";
3823                         os << "key \""
3824                            << convert_command_inset_arg(p.verbatim_item())
3825                            << "\"\n"
3826                            << "literal \"true\"\n";
3827                         end_inset(os);
3828                         // Need to set the cite engine if natbib is loaded by
3829                         // the document class directly
3830                         if (preamble.citeEngine() == "basic")
3831                                 preamble.citeEngine("natbib");
3832                 }
3833
3834                 else if ((use_biblatex
3835                          && is_known(t.cs(), known_biblatex_commands)
3836                          && ((t.cs() == "cite"
3837                              || t.cs() == "citeauthor"
3838                              || t.cs() == "Citeauthor"
3839                              || t.cs() == "parencite"
3840                              || t.cs() == "citetitle")
3841                          || p.next_token().asInput() != "*"))
3842                         || (use_biblatex_natbib
3843                             && (is_known(t.cs(), known_biblatex_commands)
3844                               || is_known(t.cs(), known_natbib_commands))
3845                             && ((t.cs() == "cite" || t.cs() == "citet" || t.cs() == "Citet"
3846                                || t.cs() == "citep" || t.cs() == "Citep" || t.cs() == "citealt"
3847                                || t.cs() == "Citealt" || t.cs() == "citealp" || t.cs() == "Citealp"
3848                                || t.cs() == "citeauthor" || t.cs() == "Citeauthor"
3849                                || t.cs() == "parencite" || t.cs() == "citetitle")
3850                                || p.next_token().asInput() != "*"))){
3851                         context.check_layout(os);
3852                         string command = t.cs();
3853                         if (p.next_token().asInput() == "*") {
3854                                 command += '*';
3855                                 p.get_token();
3856                         }
3857
3858                         bool const qualified = suffixIs(command, "s");
3859                         if (qualified)
3860                                 command = rtrim(command, "s");
3861
3862                         // text before the citation
3863                         string before;
3864                         // text after the citation
3865                         string after;
3866                         get_cite_arguments(p, true, before, after, qualified);
3867
3868                         // These use natbib cmd names in LyX
3869                         // for inter-citeengine compativility
3870                         if (command == "citeyear")
3871                                 command = "citebyear";
3872                         else if (command == "cite*")
3873                                 command = "citeyear";
3874                         else if (command == "textcite")
3875                                 command = "citet";
3876                         else if (command == "Textcite")
3877                                 command = "Citet";
3878                         else if (command == "parencite")
3879                                 command = "citep";
3880                         else if (command == "Parencite")
3881                                 command = "Citep";
3882                         else if (command == "parencite*")
3883                                 command = "citeyearpar";
3884                         else if (command == "smartcite")
3885                                 command = "footcite";
3886                         else if (command == "Smartcite")
3887                                 command = "Footcite";
3888
3889                         string const emptyarg = qualified ? "()" : "[]";
3890                         if (before.empty() && after == emptyarg)
3891                                 // avoid \cite[]{a}
3892                                 after.erase();
3893                         else if (before == emptyarg && after == emptyarg) {
3894                                 // avoid \cite[][]{a}
3895                                 before.erase();
3896                                 after.erase();
3897                         }
3898                         // remove the brackets around after and before
3899                         if (!after.empty()) {
3900                                 after.erase(0, 1);
3901                                 after.erase(after.length() - 1, 1);
3902                                 after = convert_command_inset_arg(after);
3903                         }
3904                         if (!before.empty()) {
3905                                 before.erase(0, 1);
3906                                 before.erase(before.length() - 1, 1);
3907                                 before = convert_command_inset_arg(before);
3908                         }
3909                         string keys, pretextlist, posttextlist;
3910                         if (qualified) {
3911                                 map<string, string> pres;
3912                                 map<string, string> posts;
3913                                 vector<string> lkeys;
3914                                 // text before the citation
3915                                 string lbefore;
3916                                 // text after the citation
3917                                 string lafter;
3918                                 string lkey;
3919                                 while (true) {
3920                                         get_cite_arguments(p, true, lbefore, lafter);
3921                                         // remove the brackets around after and before
3922                                         if (!lafter.empty()) {
3923                                                 lafter.erase(0, 1);
3924                                                 lafter.erase(lafter.length() - 1, 1);
3925                                                 lafter = convert_command_inset_arg(lafter);
3926                                         }
3927                                         if (!lbefore.empty()) {
3928                                                 lbefore.erase(0, 1);
3929                                                 lbefore.erase(lbefore.length() - 1, 1);
3930                                                 lbefore = convert_command_inset_arg(lbefore);
3931                                         }
3932                                         if (lbefore.empty() && lafter == "[]")
3933                                                 // avoid \cite[]{a}
3934                                                 lafter.erase();
3935                                         else if (lbefore == "[]" && lafter == "[]") {
3936                                                 // avoid \cite[][]{a}
3937                                                 lbefore.erase();
3938                                                 lafter.erase();
3939                                         }
3940                                         lkey = p.getArg('{', '}');
3941                                         if (lkey.empty())
3942                                                 break;
3943                                         if (!lbefore.empty())
3944                                                 pres.insert(make_pair(lkey, lbefore));
3945                                         if (!lafter.empty())
3946                                                 posts.insert(make_pair(lkey, lafter));
3947                                         lkeys.push_back(lkey);
3948                                 }
3949                                 keys = convert_command_inset_arg(getStringFromVector(lkeys));
3950                                 for (auto const & ptl : pres) {
3951                                         if (!pretextlist.empty())
3952                                                 pretextlist += '\t';
3953                                         pretextlist += ptl.first + " " + ptl.second;
3954                                 }
3955                                 for (auto const & potl : posts) {
3956                                         if (!posttextlist.empty())
3957                                                 posttextlist += '\t';
3958                                         posttextlist += potl.first + " " + potl.second;
3959                                 }
3960                         } else
3961                                 keys = convert_command_inset_arg(p.verbatim_item());
3962                         begin_command_inset(os, "citation", command);
3963                         os << "after " << '"' << after << '"' << "\n";
3964                         os << "before " << '"' << before << '"' << "\n";
3965                         os << "key \""
3966                            << keys
3967                            << "\"\n";
3968                         if (!pretextlist.empty())
3969                                 os << "pretextlist " << '"'  << pretextlist << '"' << "\n";
3970                         if (!posttextlist.empty())
3971                                 os << "posttextlist " << '"'  << posttextlist << '"' << "\n";
3972                         os << "literal \"true\"\n";
3973                         end_inset(os);
3974                         // Need to set the cite engine if biblatex is loaded by
3975                         // the document class directly
3976                         if (preamble.citeEngine() == "basic")
3977                                 use_biblatex_natbib ?
3978                                           preamble.citeEngine("biblatex-natbib")
3979                                         : preamble.citeEngine("biblatex");
3980                 }
3981
3982                 else if (use_jurabib &&
3983                          is_known(t.cs(), known_jurabib_commands) &&
3984                          (t.cs() == "cite" || p.next_token().asInput() != "*")) {
3985                         context.check_layout(os);
3986                         string command = t.cs();
3987                         if (p.next_token().asInput() == "*") {
3988                                 command += '*';
3989                                 p.get_token();
3990                         }
3991                         char argumentOrder = '\0';
3992                         vector<string> const options =
3993                                 preamble.getPackageOptions("jurabib");
3994                         if (find(options.begin(), options.end(),
3995                                       "natbiborder") != options.end())
3996                                 argumentOrder = 'n';
3997                         else if (find(options.begin(), options.end(),
3998                                            "jurabiborder") != options.end())
3999                                 argumentOrder = 'j';
4000
4001                         // text before the citation
4002                         string before;
4003                         // text after the citation
4004                         string after;
4005                         get_cite_arguments(p, argumentOrder != 'j', before, after);
4006
4007                         string const citation = p.verbatim_item();
4008                         if (!before.empty() && argumentOrder == '\0') {
4009                                 cerr << "Warning: Assuming argument order "
4010                                         "of jurabib version 0.6 for\n'"
4011                                      << command << before << after << '{'
4012                                      << citation << "}'.\n"
4013                                         "Add 'jurabiborder' to the jurabib "
4014                                         "package options if you used an\n"
4015                                         "earlier jurabib version." << endl;
4016                         }
4017                         if (!after.empty()) {
4018                                 after.erase(0, 1);
4019                                 after.erase(after.length() - 1, 1);
4020                         }
4021                         if (!before.empty()) {
4022                                 before.erase(0, 1);
4023                                 before.erase(before.length() - 1, 1);
4024                         }
4025                         begin_command_inset(os, "citation", command);
4026                         os << "after " << '"' << after << "\"\n"
4027                            << "before " << '"' << before << "\"\n"
4028                            << "key " << '"' << citation << "\"\n"
4029                            << "literal \"true\"\n";
4030                         end_inset(os);
4031                         // Need to set the cite engine if jurabib is loaded by
4032                         // the document class directly
4033                         if (preamble.citeEngine() == "basic")
4034                                 preamble.citeEngine("jurabib");
4035                 }
4036
4037                 else if (t.cs() == "cite"
4038                         || t.cs() == "nocite") {
4039                         context.check_layout(os);
4040                         string after = convert_command_inset_arg(p.getArg('[', ']'));
4041                         string key = convert_command_inset_arg(p.verbatim_item());
4042                         // store the case that it is "\nocite{*}" to use it later for
4043                         // the BibTeX inset
4044                         if (key != "*") {
4045                                 begin_command_inset(os, "citation", t.cs());
4046                                 os << "after " << '"' << after << "\"\n"
4047                                    << "key " << '"' << key << "\"\n"
4048                                    << "literal \"true\"\n";
4049                                 end_inset(os);
4050                         } else if (t.cs() == "nocite")
4051                                 btprint = key;
4052                 }
4053
4054                 else if (t.cs() == "index" ||
4055                          (t.cs() == "sindex" && preamble.use_indices() == "true")) {
4056                         context.check_layout(os);
4057                         string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
4058                                 p.getArg('[', ']') : "";
4059                         string const kind = arg.empty() ? "idx" : arg;
4060                         begin_inset(os, "Index ");
4061                         os << kind << "\nstatus collapsed\n";
4062                         parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
4063                         end_inset(os);
4064                         if (kind != "idx")
4065                                 preamble.registerAutomaticallyLoadedPackage("splitidx");
4066                 }
4067
4068                 else if (t.cs() == "nomenclature") {
4069                         context.check_layout(os);
4070                         begin_command_inset(os, "nomenclature", "nomenclature");
4071                         string prefix = convert_command_inset_arg(p.getArg('[', ']'));
4072                         if (!prefix.empty())
4073                                 os << "prefix " << '"' << prefix << '"' << "\n";
4074                         os << "symbol " << '"'
4075                            << convert_command_inset_arg(p.verbatim_item());
4076                         os << "\"\ndescription \""
4077                            << convert_command_inset_arg(p.verbatim_item())
4078                            << "\"\n"
4079                            << "literal \"true\"\n";
4080                         end_inset(os);
4081                         preamble.registerAutomaticallyLoadedPackage("nomencl");
4082                 }
4083
4084                 else if (t.cs() == "label") {
4085                         context.check_layout(os);
4086                         begin_command_inset(os, "label", "label");
4087                         os << "name \""
4088                            << convert_command_inset_arg(p.verbatim_item())
4089                            << "\"\n";
4090                         end_inset(os);
4091                 }
4092
4093                 else if (t.cs() == "lyxmintcaption") {
4094                         string const pos = p.getArg('[', ']');
4095                         if (pos == "t") {
4096                                 string const caption =
4097                                         parse_text_snippet(p, FLAG_ITEM, false,
4098                                                            context);
4099                                 minted_nonfloat_caption = "[t]" + caption;
4100                         } else {
4101                                 // We already got the caption at the bottom,
4102                                 // so simply skip it.
4103                                 parse_text_snippet(p, FLAG_ITEM, false, context);
4104                         }
4105                 }
4106
4107                 else if (t.cs() == "printindex" || t.cs() == "printsubindex") {
4108                         context.check_layout(os);
4109                         string commandname = t.cs();
4110                         bool star = false;
4111                         if (p.next_token().asInput() == "*") {
4112                                 commandname += "*";
4113                                 star = true;
4114                                 p.get_token();
4115                         }
4116                         begin_command_inset(os, "index_print", commandname);
4117                         string const indexname = p.getArg('[', ']');
4118                         if (!star) {
4119                                 if (indexname.empty())
4120                                         os << "type \"idx\"\n";
4121                                 else
4122                                         os << "type \"" << indexname << "\"\n";
4123                                 os << "literal \"true\"\n";
4124                         }
4125                         end_inset(os);
4126                         skip_spaces_braces(p);
4127                         preamble.registerAutomaticallyLoadedPackage("makeidx");
4128                         if (preamble.use_indices() == "true")
4129                                 preamble.registerAutomaticallyLoadedPackage("splitidx");
4130                 }
4131
4132                 else if (t.cs() == "printnomenclature") {
4133                         string width = "";
4134                         string width_type = "";
4135                         context.check_layout(os);
4136                         begin_command_inset(os, "nomencl_print", "printnomenclature");
4137                         // case of a custom width
4138                         if (p.hasOpt()) {
4139                                 width = p.getArg('[', ']');
4140                                 width = translate_len(width);
4141                                 width_type = "custom";
4142                         }
4143                         // case of no custom width
4144                         // the case of no custom width but the width set
4145                         // via \settowidth{\nomlabelwidth}{***} cannot be supported
4146                         // because the user could have set anything, not only the width
4147                         // of the longest label (which would be width_type = "auto")
4148                         string label = convert_command_inset_arg(p.getArg('{', '}'));
4149                         if (label.empty() && width_type.empty())
4150                                 width_type = "none";
4151                         os << "set_width \"" << width_type << "\"\n";
4152                         if (width_type == "custom")
4153                                 os << "width \"" << width << '\"';
4154                         end_inset(os);
4155                         skip_spaces_braces(p);
4156                         preamble.registerAutomaticallyLoadedPackage("nomencl");
4157                 }
4158
4159                 else if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
4160                         context.check_layout(os);
4161                         begin_inset(os, "script ");
4162                         os << t.cs().substr(4) << '\n';
4163                         newinsetlayout = findInsetLayout(context.textclass, t.cs(), true);
4164                         parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
4165                         end_inset(os);
4166                         if (t.cs() == "textsubscript")
4167                                 preamble.registerAutomaticallyLoadedPackage("subscript");
4168                 }
4169
4170                 else if ((where = is_known(t.cs(), known_quotes))) {
4171                         context.check_layout(os);
4172                         begin_inset(os, "Quotes ");
4173                         os << known_coded_quotes[where - known_quotes];
4174                         end_inset(os);
4175                         // LyX adds {} after the quote, so we have to eat
4176                         // spaces here if there are any before a possible
4177                         // {} pair.
4178                         eat_whitespace(p, os, context, false);
4179                         skip_braces(p);
4180                 }
4181
4182                 else if ((where = is_known(t.cs(), known_sizes)) &&
4183                          context.new_layout_allowed) {
4184                         context.check_layout(os);
4185                         TeXFont const oldFont = context.font;
4186                         context.font.size = known_coded_sizes[where - known_sizes];
4187                         output_font_change(os, oldFont, context.font);
4188                         eat_whitespace(p, os, context, false);
4189                 }
4190
4191                 else if ((where = is_known(t.cs(), known_font_families)) &&
4192                          context.new_layout_allowed) {
4193                         context.check_layout(os);
4194                         TeXFont const oldFont = context.font;
4195                         context.font.family =
4196                                 known_coded_font_families[where - known_font_families];
4197                         output_font_change(os, oldFont, context.font);
4198                         eat_whitespace(p, os, context, false);
4199                 }
4200
4201                 else if ((where = is_known(t.cs(), known_font_series)) &&
4202                          context.new_layout_allowed) {
4203                         context.check_layout(os);
4204                         TeXFont const oldFont = context.font;
4205                         context.font.series =
4206                                 known_coded_font_series[where - known_font_series];
4207                         output_font_change(os, oldFont, context.font);
4208                         eat_whitespace(p, os, context, false);
4209                 }
4210
4211                 else if ((where = is_known(t.cs(), known_font_shapes)) &&
4212                          context.new_layout_allowed) {
4213                         context.check_layout(os);
4214                         TeXFont const oldFont = context.font;
4215                         context.font.shape =
4216                                 known_coded_font_shapes[where - known_font_shapes];
4217                         output_font_change(os, oldFont, context.font);
4218                         eat_whitespace(p, os, context, false);
4219                 }
4220                 else if ((where = is_known(t.cs(), known_old_font_families)) &&
4221                          context.new_layout_allowed) {
4222                         context.check_layout(os);
4223                         TeXFont const oldFont = context.font;
4224                         context.font.init();
4225                         context.font.size = oldFont.size;
4226                         context.font.family =
4227                                 known_coded_font_families[where - known_old_font_families];
4228                         output_font_change(os, oldFont, context.font);
4229                         eat_whitespace(p, os, context, false);
4230                 }
4231
4232                 else if ((where = is_known(t.cs(), known_old_font_series)) &&
4233                          context.new_layout_allowed) {
4234                         context.check_layout(os);
4235                         TeXFont const oldFont = context.font;
4236                         context.font.init();
4237                         context.font.size = oldFont.size;
4238                         context.font.series =
4239                                 known_coded_font_series[where - known_old_font_series];
4240                         output_font_change(os, oldFont, context.font);
4241                         eat_whitespace(p, os, context, false);
4242                 }
4243
4244                 else if ((where = is_known(t.cs(), known_old_font_shapes)) &&
4245                          context.new_layout_allowed) {
4246                         context.check_layout(os);
4247                         TeXFont const oldFont = context.font;
4248                         context.font.init();
4249                         context.font.size = oldFont.size;
4250                         context.font.shape =
4251                                 known_coded_font_shapes[where - known_old_font_shapes];
4252                         output_font_change(os, oldFont, context.font);
4253                         eat_whitespace(p, os, context, false);
4254                 }
4255
4256                 else if (t.cs() == "selectlanguage") {
4257                         context.check_layout(os);
4258                         // save the language for the case that a
4259                         // \foreignlanguage is used
4260                         context.font.language = babel2lyx(p.verbatim_item());
4261                         os << "\n\\lang " << context.font.language << "\n";
4262                 }
4263
4264                 else if (t.cs() == "foreignlanguage") {
4265                         string const lang = babel2lyx(p.verbatim_item());
4266                         parse_text_attributes(p, os, FLAG_ITEM, outer,
4267                                               context, "\\lang",
4268                                               context.font.language, lang);
4269                 }
4270
4271                 else if (prefixIs(t.cs(), "text") && preamble.usePolyglossia()
4272                          && is_known(t.cs().substr(4), preamble.polyglossia_languages)) {
4273                         // scheme is \textLANGUAGE{text} where LANGUAGE is in polyglossia_languages[]
4274                         string lang;
4275                         // We have to output the whole command if it has an option
4276                         // because LyX doesn't support this yet, see bug #8214,
4277                         // only if there is a single option specifying a variant, we can handle it.
4278                         if (p.hasOpt()) {
4279                                 string langopts = p.getOpt();
4280                                 // check if the option contains a variant, if yes, extract it
4281                                 string::size_type pos_var = langopts.find("variant");
4282                                 string::size_type i = langopts.find(',');
4283                                 string::size_type k = langopts.find('=', pos_var);
4284                                 if (pos_var != string::npos && i == string::npos) {
4285                                         string variant;
4286                                         variant = langopts.substr(k + 1, langopts.length() - k - 2);
4287                                         lang = preamble.polyglossia2lyx(variant);
4288                                         parse_text_attributes(p, os, FLAG_ITEM, outer,
4289                                                                   context, "\\lang",
4290                                                                   context.font.language, lang);
4291                                 } else
4292                                         output_ert_inset(os, t.asInput() + langopts, context);
4293                         } else {
4294                                 lang = preamble.polyglossia2lyx(t.cs().substr(4, string::npos));
4295                                 parse_text_attributes(p, os, FLAG_ITEM, outer,
4296                                                           context, "\\lang",
4297                                                           context.font.language, lang);
4298                         }
4299                 }
4300
4301                 else if (t.cs() == "inputencoding") {
4302                         // nothing to write here
4303                         string const enc = subst(p.verbatim_item(), "\n", " ");
4304                         p.setEncoding(enc, Encoding::inputenc);
4305                 }
4306
4307                 else if (is_known(t.cs(), known_special_chars) ||
4308                          (t.cs() == "protect" &&
4309                           p.next_token().cat() == catEscape &&
4310                           is_known(p.next_token().cs(), known_special_protect_chars))) {
4311                         // LyX sometimes puts a \protect in front, so we have to ignore it
4312                         where = is_known(
4313                                 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
4314                                 known_special_chars);
4315                         context.check_layout(os);
4316                         os << known_coded_special_chars[where - known_special_chars];
4317                         skip_spaces_braces(p);
4318                 }
4319
4320                 else if ((t.cs() == "nobreakdash" && p.next_token().asInput() == "-") ||
4321                          (t.cs() == "protect" && p.next_token().asInput() == "\\nobreakdash" &&
4322                           p.next_next_token().asInput() == "-") ||
4323                          (t.cs() == "@" && p.next_token().asInput() == ".")) {
4324                         // LyX sometimes puts a \protect in front, so we have to ignore it
4325                         if (t.cs() == "protect")
4326                                 p.get_token();
4327                         context.check_layout(os);
4328                         if (t.cs() == "nobreakdash")
4329                                 os << "\\SpecialChar nobreakdash\n";
4330                         else
4331                                 os << "\\SpecialChar endofsentence\n";
4332                         p.get_token();
4333                 }
4334
4335                 else if (t.cs() == "textquotedbl") {
4336                         context.check_layout(os);
4337                         os << "\"";
4338                         skip_braces(p);
4339                 }
4340
4341                 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
4342                             || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
4343                             || t.cs() == "%" || t.cs() == "-") {
4344                         context.check_layout(os);
4345                         if (t.cs() == "-")
4346                                 os << "\\SpecialChar softhyphen\n";
4347                         else
4348                                 os << t.cs();
4349                 }
4350
4351                 else if (t.cs() == "char") {
4352                         context.check_layout(os);
4353                         if (p.next_token().character() == '`') {
4354                                 p.get_token();
4355                                 if (p.next_token().cs() == "\"") {
4356                                         p.get_token();
4357                                         os << '"';
4358                                         skip_braces(p);
4359                                 } else {
4360                                         output_ert_inset(os, "\\char`", context);
4361                                 }
4362                         } else {
4363                                 output_ert_inset(os, "\\char", context);
4364                         }
4365                 }
4366
4367                 else if (t.cs() == "verb") {
4368                         context.check_layout(os);
4369                         // set catcodes to verbatim early, just in case.
4370                         p.setCatcodes(VERBATIM_CATCODES);
4371                         string delim = p.get_token().asInput();
4372                         Parser::Arg arg = p.verbatimStuff(delim);
4373                         if (arg.first)
4374                                 output_ert_inset(os, "\\verb" + delim
4375                                                  + arg.second + delim, context);
4376                         else
4377                                 cerr << "invalid \\verb command. Skipping" << endl;
4378                 }
4379
4380                 // Problem: \= creates a tabstop inside the tabbing environment
4381                 // and else an accent. In the latter case we really would want
4382                 // \={o} instead of \= o.
4383                 else if (t.cs() == "=" && (flags & FLAG_TABBING))
4384                         output_ert_inset(os, t.asInput(), context);
4385
4386                 else if (t.cs() == "\\") {
4387                         context.check_layout(os);
4388                         if (p.hasOpt())
4389                                 output_ert_inset(os, "\\\\" + p.getOpt(), context);
4390                         else if (p.next_token().asInput() == "*") {
4391                                 p.get_token();
4392                                 // getOpt() eats the following space if there
4393                                 // is no optional argument, but that is OK
4394                                 // here since it has no effect in the output.
4395                                 output_ert_inset(os, "\\\\*" + p.getOpt(), context);
4396                         }
4397                         else {
4398                                 begin_inset(os, "Newline newline");
4399                                 end_inset(os);
4400                         }
4401                 }
4402
4403                 else if (t.cs() == "newline" ||
4404                          (t.cs() == "linebreak" && !p.hasOpt())) {
4405                         context.check_layout(os);
4406                         begin_inset(os, "Newline ");
4407                         os << t.cs();
4408                         end_inset(os);
4409                         skip_spaces_braces(p);
4410                 }
4411
4412                 else if (t.cs() == "input" || t.cs() == "include"
4413                          || t.cs() == "verbatiminput") {
4414                         string name = t.cs();
4415                         if (t.cs() == "verbatiminput"
4416                             && p.next_token().asInput() == "*")
4417                                 name += p.get_token().asInput();
4418                         context.check_layout(os);
4419                         string filename(normalize_filename(p.getArg('{', '}')));
4420                         string const path = getMasterFilePath(true);
4421                         // We want to preserve relative / absolute filenames,
4422                         // therefore path is only used for testing
4423                         if ((t.cs() == "include" || t.cs() == "input") &&
4424                             !makeAbsPath(filename, path).exists()) {
4425                                 // The file extension is probably missing.
4426                                 // Now try to find it out.
4427                                 string const tex_name =
4428                                         find_file(filename, path,
4429                                                   known_tex_extensions);
4430                                 if (!tex_name.empty())
4431                                         filename = tex_name;
4432                         }
4433                         bool external = false;
4434                         string outname;
4435                         if (makeAbsPath(filename, path).exists()) {
4436                                 string const abstexname =
4437                                         makeAbsPath(filename, path).absFileName();
4438                                 string const absfigname =
4439                                         changeExtension(abstexname, ".fig");
4440                                 fix_child_filename(filename);
4441                                 string const lyxname = changeExtension(filename,
4442                                         roundtripMode() ? ".lyx.lyx" : ".lyx");
4443                                 string const abslyxname = makeAbsPath(
4444                                         lyxname, getParentFilePath(false)).absFileName();
4445                                 bool xfig = false;
4446                                 if (!skipChildren())
4447                                         external = FileName(absfigname).exists();
4448                                 if (t.cs() == "input" && !skipChildren()) {
4449                                         string const ext = getExtension(abstexname);
4450
4451                                         // Combined PS/LaTeX:
4452                                         // x.eps, x.pstex_t (old xfig)
4453                                         // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
4454                                         FileName const absepsname(
4455                                                 changeExtension(abstexname, ".eps"));
4456                                         FileName const abspstexname(
4457                                                 changeExtension(abstexname, ".pstex"));
4458                                         bool const xfigeps =
4459                                                 (absepsname.exists() ||
4460                                                  abspstexname.exists()) &&
4461                                                 ext == "pstex_t";
4462
4463                                         // Combined PDF/LaTeX:
4464                                         // x.pdf, x.pdftex_t (old xfig)
4465                                         // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
4466                                         FileName const abspdfname(
4467                                                 changeExtension(abstexname, ".pdf"));
4468                                         bool const xfigpdf =
4469                                                 abspdfname.exists() &&
4470                                                 (ext == "pdftex_t" || ext == "pdf_t");
4471                                         if (xfigpdf)
4472                                                 pdflatex = true;
4473
4474                                         // Combined PS/PDF/LaTeX:
4475                                         // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
4476                                         string const absbase2(
4477                                                 removeExtension(abstexname) + "_pspdftex");
4478                                         FileName const abseps2name(
4479                                                 addExtension(absbase2, ".eps"));
4480                                         FileName const abspdf2name(
4481                                                 addExtension(absbase2, ".pdf"));
4482                                         bool const xfigboth =
4483                                                 abspdf2name.exists() &&
4484                                                 abseps2name.exists() && ext == "pspdftex";
4485
4486                                         xfig = xfigpdf || xfigeps || xfigboth;
4487                                         external = external && xfig;
4488                                 }
4489                                 if (external) {
4490                                         outname = changeExtension(filename, ".fig");
4491                                         FileName abssrc(changeExtension(abstexname, ".fig"));
4492                                         copy_file(abssrc, outname);
4493                                 } else if (xfig) {
4494                                         // Don't try to convert, the result
4495                                         // would be full of ERT.
4496                                         outname = filename;
4497                                         FileName abssrc(abstexname);
4498                                         copy_file(abssrc, outname);
4499                                 } else if (t.cs() != "verbatiminput" &&
4500                                            !skipChildren() &&
4501                                     tex2lyx(abstexname, FileName(abslyxname),
4502                                             p.getEncoding())) {
4503                                         outname = lyxname;
4504                                         // no need to call copy_file
4505                                         // tex2lyx creates the file
4506                                 } else {
4507                                         outname = filename;
4508                                         FileName abssrc(abstexname);
4509                                         copy_file(abssrc, outname);
4510                                 }
4511                         } else {
4512                                 cerr << "Warning: Could not find included file '"
4513                                      << filename << "'." << endl;
4514                                 outname = filename;
4515                         }
4516                         if (external) {
4517                                 begin_inset(os, "External\n");
4518                                 os << "\ttemplate XFig\n"
4519                                    << "\tfilename " << outname << '\n';
4520                                 registerExternalTemplatePackages("XFig");
4521                         } else {
4522                                 begin_command_inset(os, "include", name);
4523                                 outname = subst(outname, "\"", "\\\"");
4524                                 os << "preview false\n"
4525                                       "filename \"" << outname << "\"\n";
4526                                 if (t.cs() == "verbatiminput")
4527                                         preamble.registerAutomaticallyLoadedPackage("verbatim");
4528                         }
4529                         end_inset(os);
4530                 }
4531
4532                 else if (t.cs() == "bibliographystyle") {
4533                         // store new bibliographystyle
4534                         bibliographystyle = p.verbatim_item();
4535                         // If any other command than \bibliography, \addcontentsline
4536                         // and \nocite{*} follows, we need to output the style
4537                         // (because it might be used by that command).
4538                         // Otherwise, it will automatically be output by LyX.
4539                         p.pushPosition();
4540                         bool output = true;
4541                         for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
4542                                 if (t2.cat() == catBegin)
4543                                         break;
4544                                 if (t2.cat() != catEscape)
4545                                         continue;
4546                                 if (t2.cs() == "nocite") {
4547                                         if (p.getArg('{', '}') == "*")
4548                                                 continue;
4549                                 } else if (t2.cs() == "bibliography")
4550                                         output = false;
4551                                 else if (t2.cs() == "phantomsection") {
4552                                         output = false;
4553                                         continue;
4554                                 }
4555                                 else if (t2.cs() == "addcontentsline") {
4556                                         // get the 3 arguments of \addcontentsline
4557                                         p.getArg('{', '}');
4558                                         p.getArg('{', '}');
4559                                         contentslineContent = p.getArg('{', '}');
4560                                         // if the last argument is not \refname we must output
4561                                         if (contentslineContent == "\\refname")
4562                                                 output = false;
4563                                 }
4564                                 break;
4565                         }
4566                         p.popPosition();
4567                         if (output) {
4568                                 output_ert_inset(os,
4569                                         "\\bibliographystyle{" + bibliographystyle + '}',
4570                                         context);
4571                         }
4572                 }
4573
4574                 else if (t.cs() == "phantomsection") {
4575                         // we only support this if it occurs between
4576                         // \bibliographystyle and \bibliography
4577                         if (bibliographystyle.empty())
4578                                 output_ert_inset(os, "\\phantomsection", context);
4579                 }
4580
4581                 else if (t.cs() == "addcontentsline") {
4582                         context.check_layout(os);
4583                         // get the 3 arguments of \addcontentsline
4584                         string const one = p.getArg('{', '}');
4585                         string const two = p.getArg('{', '}');
4586                         string const three = p.getArg('{', '}');
4587                         // only if it is a \refname, we support if for the bibtex inset
4588                         if (contentslineContent != "\\refname") {
4589                                 output_ert_inset(os,
4590                                         "\\addcontentsline{" + one + "}{" + two + "}{"+ three + '}',
4591                                         context);
4592                         }
4593                 }
4594
4595                 else if (t.cs() == "bibliography") {
4596                         context.check_layout(os);
4597                         string BibOpts;
4598                         begin_command_inset(os, "bibtex", "bibtex");
4599                         if (!btprint.empty()) {
4600                                 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
4601                                 // clear the string because the next BibTeX inset can be without the
4602                                 // \nocite{*} option
4603                                 btprint.clear();
4604                         }
4605                         os << "bibfiles " << '"' << normalize_filename(p.verbatim_item()) << '"' << "\n";
4606                         // Do we have addcontentsline?
4607                         if (contentslineContent == "\\refname") {
4608                                 BibOpts = "bibtotoc";
4609                                 // clear string because next BibTeX inset can be without addcontentsline
4610                                 contentslineContent.clear();
4611                         }
4612                         // Do we have a bibliographystyle set?
4613                         if (!bibliographystyle.empty()) {
4614                                 if (BibOpts.empty())
4615                                         BibOpts = normalize_filename(bibliographystyle);
4616                                 else
4617                                         BibOpts = BibOpts + ',' + normalize_filename(bibliographystyle);
4618                                 // clear it because each bibtex entry has its style
4619                                 // and we need an empty string to handle \phantomsection
4620                                 bibliographystyle.clear();
4621                         }
4622                         os << "options " << '"' << BibOpts << '"' << "\n";
4623                         end_inset(os);
4624                 }
4625
4626                 else if (t.cs() == "printbibliography") {
4627                         context.check_layout(os);
4628                         string BibOpts;
4629                         string bbloptions = p.hasOpt() ? p.getArg('[', ']') : string();
4630                         vector<string> opts = getVectorFromString(bbloptions);
4631                         vector<string>::iterator it =
4632                                 find(opts.begin(), opts.end(), "heading=bibintoc");
4633                         if (it != opts.end()) {
4634                                 opts.erase(it);
4635                                 BibOpts = "bibtotoc";
4636                         }
4637                         bbloptions = getStringFromVector(opts);
4638                         begin_command_inset(os, "bibtex", "bibtex");
4639                         if (!btprint.empty()) {
4640                                 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
4641                                 // clear the string because the next BibTeX inset can be without the
4642                                 // \nocite{*} option
4643                                 btprint.clear();
4644                         }
4645                         string bibfiles;
4646                         for (auto const & bf : preamble.biblatex_bibliographies) {
4647                                 if (!bibfiles.empty())
4648                                         bibfiles += ",";
4649                                 bibfiles += normalize_filename(bf);
4650                         }
4651                         if (!bibfiles.empty())
4652                                 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
4653                         // Do we have addcontentsline?
4654                         if (contentslineContent == "\\refname") {
4655                                 BibOpts = "bibtotoc";
4656                                 // clear string because next BibTeX inset can be without addcontentsline
4657                                 contentslineContent.clear();
4658                         }
4659                         os << "options " << '"' << BibOpts << '"' << "\n";
4660                         if (!bbloptions.empty())
4661                                 os << "biblatexopts " << '"' << bbloptions << '"' << "\n";
4662                         end_inset(os);
4663                         need_commentbib = false;
4664                 }
4665
4666                 else if (t.cs() == "bibbysection") {
4667                         context.check_layout(os);
4668                         string BibOpts;
4669                         string bbloptions = p.hasOpt() ? p.getArg('[', ']') : string();
4670                         vector<string> opts = getVectorFromString(bbloptions);
4671                         vector<string>::iterator it =
4672                                 find(opts.begin(), opts.end(), "heading=bibintoc");
4673                         if (it != opts.end()) {
4674                                 opts.erase(it);
4675                                 BibOpts = "bibtotoc";
4676                         }
4677                         bbloptions = getStringFromVector(opts);
4678                         begin_command_inset(os, "bibtex", "bibtex");
4679                         os << "btprint " << '"' << "bibbysection" << '"' << "\n";
4680                         string bibfiles;
4681                         for (auto const & bf : preamble.biblatex_bibliographies) {
4682                                 if (!bibfiles.empty())
4683                                         bibfiles += ",";
4684                                 bibfiles += normalize_filename(bf);
4685                         }
4686                         if (!bibfiles.empty())
4687                                 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
4688                         os << "options " << '"' << BibOpts << '"' << "\n";
4689                         if (!bbloptions.empty())
4690                                 os << "biblatexopts " << '"' << bbloptions << '"' << "\n";
4691                         end_inset(os);
4692                         need_commentbib = false;
4693                 }
4694
4695                 else if (t.cs() == "parbox") {
4696                         // Test whether this is an outer box of a shaded box
4697                         p.pushPosition();
4698                         // swallow arguments
4699                         while (p.hasOpt()) {
4700                                 p.getArg('[', ']');
4701                                 p.skip_spaces(true);
4702                         }
4703                         p.getArg('{', '}');
4704                         p.skip_spaces(true);
4705                         // eat the '{'
4706                         if (p.next_token().cat() == catBegin)
4707                                 p.get_token();
4708                         p.skip_spaces(true);
4709                         Token to = p.get_token();
4710                         bool shaded = false;
4711                         if (to.asInput() == "\\begin") {
4712                                 p.skip_spaces(true);
4713                                 if (p.getArg('{', '}') == "shaded")
4714                                         shaded = true;
4715                         }
4716                         p.popPosition();
4717                         if (shaded) {
4718                                 parse_outer_box(p, os, FLAG_ITEM, outer,
4719                                                 context, "parbox", "shaded");
4720                         } else
4721                                 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4722                                           "", "", t.cs(), "", "");
4723                 }
4724
4725                 else if (t.cs() == "fbox" || t.cs() == "mbox" ||
4726                              t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
4727                          t.cs() == "shadowbox" || t.cs() == "doublebox")
4728                         parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
4729
4730                 else if (t.cs() == "fcolorbox" || t.cs() == "colorbox") {
4731                         string backgroundcolor;
4732                         preamble.registerAutomaticallyLoadedPackage("xcolor");
4733                         if (t.cs() == "fcolorbox") {
4734                                 string const framecolor = p.getArg('{', '}');
4735                                 backgroundcolor = p.getArg('{', '}');
4736                                 parse_box(p, os, 0, 0, outer, context, "", "", "", framecolor, backgroundcolor);
4737                         } else {
4738                                 backgroundcolor = p.getArg('{', '}');
4739                                 parse_box(p, os, 0, 0, outer, context, "", "", "", "", backgroundcolor);
4740                         }
4741                 }
4742
4743                 // FIXME: due to the compiler limit of "if" nestings
4744                 // the code for the alignment was put here
4745                 // put them in their own if if this is fixed
4746                 else if (t.cs() == "fboxrule" || t.cs() == "fboxsep"
4747                              || t.cs() == "shadowsize"
4748                                  || t.cs() == "raggedleft" || t.cs() == "centering"
4749                          || t.cs() == "raggedright") {
4750                         if (t.cs() == "fboxrule")
4751                                 fboxrule = "";
4752                         if (t.cs() == "fboxsep")
4753                                 fboxsep = "";
4754                         if (t.cs() == "shadowsize")
4755                                 shadow_size = "";
4756                         if (t.cs() != "raggedleft" && t.cs() != "centering"
4757                          && t.cs() != "raggedright") {
4758                                 p.skip_spaces(true);
4759                                 while (p.good() && p.next_token().cat() != catSpace
4760                                        && p.next_token().cat() != catNewline
4761                                        && p.next_token().cat() != catEscape) {
4762                                         if (t.cs() == "fboxrule")
4763                                                 fboxrule = fboxrule + p.get_token().asInput();
4764                                         if (t.cs() == "fboxsep")
4765                                                 fboxsep = fboxsep + p.get_token().asInput();
4766                                         if (t.cs() == "shadowsize")
4767                                                 shadow_size = shadow_size + p.get_token().asInput();
4768                                 }
4769                         } else {
4770                                 output_ert_inset(os, t.asInput(), context);
4771                         }
4772                 }
4773
4774                 //\framebox() is part of the picture environment and different from \framebox{}
4775                 //\framebox{} will be parsed by parse_outer_box
4776                 else if (t.cs() == "framebox") {
4777                         if (p.next_token().character() == '(') {
4778                                 //the syntax is: \framebox(x,y)[position]{content}
4779                                 string arg = t.asInput();
4780                                 arg += p.getFullParentheseArg();
4781                                 arg += p.getFullOpt();
4782                                 eat_whitespace(p, os, context, false);
4783                                 output_ert_inset(os, arg + '{', context);
4784                                 parse_text(p, os, FLAG_ITEM, outer, context);
4785                                 output_ert_inset(os, "}", context);
4786                         } else {
4787                                 //the syntax is: \framebox[width][position]{content}
4788                                 string special = p.getFullOpt();
4789                                 special += p.getOpt();
4790                                 parse_outer_box(p, os, FLAG_ITEM, outer,
4791                                                     context, t.cs(), special);
4792                         }
4793                 }
4794
4795                 //\makebox() is part of the picture environment and different from \makebox{}
4796                 //\makebox{} will be parsed by parse_box
4797                 else if (t.cs() == "makebox") {
4798                         if (p.next_token().character() == '(') {
4799                                 //the syntax is: \makebox(x,y)[position]{content}
4800                                 string arg = t.asInput();
4801                                 arg += p.getFullParentheseArg();
4802                                 arg += p.getFullOpt();
4803                                 eat_whitespace(p, os, context, false);
4804                                 output_ert_inset(os, arg + '{', context);
4805                                 parse_text(p, os, FLAG_ITEM, outer, context);
4806                                 output_ert_inset(os, "}", context);
4807                         } else
4808                                 //the syntax is: \makebox[width][position]{content}
4809                                 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4810                                           "", "", t.cs(), "", "");
4811                 }
4812
4813                 else if (t.cs() == "smallskip" ||
4814                          t.cs() == "medskip" ||
4815                          t.cs() == "bigskip" ||
4816                          t.cs() == "vfill") {
4817                         context.check_layout(os);
4818                         begin_inset(os, "VSpace ");
4819                         os << t.cs();
4820                         end_inset(os);
4821                         skip_spaces_braces(p);
4822                 }
4823
4824                 else if ((where = is_known(t.cs(), known_spaces))) {
4825                         context.check_layout(os);
4826                         begin_inset(os, "space ");
4827                         os << '\\' << known_coded_spaces[where - known_spaces]
4828                            << '\n';
4829                         end_inset(os);
4830                         // LaTeX swallows whitespace after all spaces except
4831                         // "\\,". We have to do that here, too, because LyX
4832                         // adds "{}" which would make the spaces significant.
4833                         if (t.cs() !=  ",")
4834                                 eat_whitespace(p, os, context, false);
4835                         // LyX adds "{}" after all spaces except "\\ " and
4836                         // "\\,", so we have to remove "{}".
4837                         // "\\,{}" is equivalent to "\\," in LaTeX, so we
4838                         // remove the braces after "\\,", too.
4839                         if (t.cs() != " ")
4840                                 skip_braces(p);
4841                 }
4842
4843                 else if (t.cs() == "newpage" ||
4844                          (t.cs() == "pagebreak" && !p.hasOpt()) ||
4845                          t.cs() == "clearpage" ||
4846                          t.cs() == "cleardoublepage") {
4847                         context.check_layout(os);
4848                         begin_inset(os, "Newpage ");
4849                         os << t.cs();
4850                         end_inset(os);
4851                         skip_spaces_braces(p);
4852                 }
4853
4854                 else if (t.cs() == "DeclareRobustCommand" ||
4855                          t.cs() == "DeclareRobustCommandx" ||
4856                          t.cs() == "newcommand" ||
4857                          t.cs() == "newcommandx" ||
4858                          t.cs() == "providecommand" ||
4859                          t.cs() == "providecommandx" ||
4860                          t.cs() == "renewcommand" ||
4861                          t.cs() == "renewcommandx") {
4862                         // DeclareRobustCommand, DeclareRobustCommandx,
4863                         // providecommand and providecommandx could be handled
4864                         // by parse_command(), but we need to call
4865                         // add_known_command() here.
4866                         string name = t.asInput();
4867                         if (p.next_token().asInput() == "*") {
4868                                 // Starred form. Eat '*'
4869                                 p.get_token();
4870                                 name += '*';
4871                         }
4872                         string const command = p.verbatim_item();
4873                         string const opt1 = p.getFullOpt();
4874                         string const opt2 = p.getFullOpt();
4875                         add_known_command(command, opt1, !opt2.empty());
4876                         string const ert = name + '{' + command + '}' +
4877                                            opt1 + opt2 +
4878                                            '{' + p.verbatim_item() + '}';
4879
4880                         if (t.cs() == "DeclareRobustCommand" ||
4881                             t.cs() == "DeclareRobustCommandx" ||
4882                             t.cs() == "providecommand" ||
4883                             t.cs() == "providecommandx" ||
4884                             name[name.length()-1] == '*')
4885                                 output_ert_inset(os, ert, context);
4886                         else {
4887                                 context.check_layout(os);
4888                                 begin_inset(os, "FormulaMacro");
4889                                 os << "\n" << ert;
4890                                 end_inset(os);
4891                         }
4892                 }
4893
4894                 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
4895                         // let could be handled by parse_command(),
4896                         // but we need to call add_known_command() here.
4897                         string ert = t.asInput();
4898                         string name;
4899                         p.skip_spaces();
4900                         if (p.next_token().cat() == catBegin) {
4901                                 name = p.verbatim_item();
4902                                 ert += '{' + name + '}';
4903                         } else {
4904                                 name = p.verbatim_item();
4905                                 ert += name;
4906                         }
4907                         string command;
4908                         p.skip_spaces();
4909                         if (p.next_token().cat() == catBegin) {
4910                                 command = p.verbatim_item();
4911                                 ert += '{' + command + '}';
4912                         } else {
4913                                 command = p.verbatim_item();
4914                                 ert += command;
4915                         }
4916                         // If command is known, make name known too, to parse
4917                         // its arguments correctly. For this reason we also
4918                         // have commands in syntax.default that are hardcoded.
4919                         CommandMap::iterator it = known_commands.find(command);
4920                         if (it != known_commands.end())
4921                                 known_commands[t.asInput()] = it->second;
4922                         output_ert_inset(os, ert, context);
4923                 }
4924
4925                 else if (t.cs() == "hspace" || t.cs() == "vspace") {
4926                         if (starred)
4927                                 p.get_token();
4928                         string name = t.asInput();
4929                         string const length = p.verbatim_item();
4930                         string unit;
4931                         string valstring;
4932                         bool valid = splitLatexLength(length, valstring, unit);
4933                         bool known_hspace = false;
4934                         bool known_vspace = false;
4935                         bool known_unit = false;
4936                         double value;
4937                         if (valid) {
4938                                 istringstream iss(valstring);
4939                                 iss >> value;
4940                                 if (value == 1.0) {
4941                                         if (t.cs()[0] == 'h') {
4942                                                 if (unit == "\\fill") {
4943                                                         if (!starred) {
4944                                                                 unit = "";
4945                                                                 name = "\\hfill";
4946                                                         }
4947                                                         known_hspace = true;
4948                                                 }
4949                                         } else {
4950                                                 if (unit == "\\smallskipamount") {
4951                                                         unit = "smallskip";
4952                                                         known_vspace = true;
4953                                                 } else if (unit == "\\medskipamount") {
4954                                                         unit = "medskip";
4955                                                         known_vspace = true;
4956                                                 } else if (unit == "\\bigskipamount") {
4957                                                         unit = "bigskip";
4958                                                         known_vspace = true;
4959                                                 } else if (unit == "\\fill") {
4960                                                         unit = "vfill";
4961                                                         known_vspace = true;
4962                                                 }
4963                                         }
4964                                 }
4965                                 if (!known_hspace && !known_vspace) {
4966                                         switch (unitFromString(unit)) {
4967                                         case Length::SP:
4968                                         case Length::PT:
4969                                         case Length::BP:
4970                                         case Length::DD:
4971                                         case Length::MM:
4972                                         case Length::PC:
4973                                         case Length::CC:
4974                                         case Length::CM:
4975                                         case Length::IN:
4976                                         case Length::EX:
4977                                         case Length::EM:
4978                                         case Length::MU:
4979                                                 known_unit = true;
4980                                                 break;
4981                                         default: {
4982                                                 //unitFromString(unit) fails for relative units like Length::PCW
4983                                                 // therefore handle them separately
4984                                                 if (unit == "\\paperwidth" || unit == "\\columnwidth"
4985                                                         || unit == "\\textwidth" || unit == "\\linewidth"
4986                                                         || unit == "\\textheight" || unit == "\\paperheight"
4987                                                         || unit == "\\baselineskip")
4988                                                         known_unit = true;
4989                                                 break;
4990                                                          }
4991                                         }
4992                                 }
4993                         }
4994
4995                         // check for glue lengths
4996                         bool is_gluelength = false;
4997                         string gluelength = length;
4998                         string::size_type i = length.find(" minus");
4999                         if (i == string::npos) {
5000                                 i = length.find(" plus");
5001                                 if (i != string::npos)
5002                                         is_gluelength = true;
5003                         } else
5004                                 is_gluelength = true;
5005                         // if yes transform "9xx minus 8yy plus 7zz"
5006                         // to "9xx-8yy+7zz"
5007                         if (is_gluelength) {
5008                                 i = gluelength.find(" minus");
5009                                 if (i != string::npos)
5010                                         gluelength.replace(i, 7, "-");
5011                                 i = gluelength.find(" plus");
5012                                 if (i != string::npos)
5013                                         gluelength.replace(i, 6, "+");
5014                         }
5015
5016                         if (t.cs()[0] == 'h' && (known_unit || known_hspace || is_gluelength)) {
5017                                 // Literal horizontal length or known variable
5018                                 context.check_layout(os);
5019                                 begin_inset(os, "space ");
5020                                 os << name;
5021                                 if (starred)
5022                                         os << '*';
5023                                 os << '{';
5024                                 if (known_hspace)
5025                                         os << unit;
5026                                 os << "}";
5027                                 if (known_unit && !known_hspace)
5028                                         os << "\n\\length " << translate_len(length);
5029                                 if (is_gluelength)
5030                                         os << "\n\\length " << gluelength;
5031                                 end_inset(os);
5032                         } else if (known_unit || known_vspace || is_gluelength) {
5033                                 // Literal vertical length or known variable
5034                                 context.check_layout(os);
5035                                 begin_inset(os, "VSpace ");
5036                                 if (known_vspace)
5037                                         os << unit;
5038                                 if (known_unit && !known_vspace)
5039                                         os << translate_len(length);
5040                                 if (is_gluelength)
5041                                         os << gluelength;
5042                                 if (starred)
5043                                         os << '*';
5044                                 end_inset(os);
5045                         } else {
5046                                 // LyX can't handle other length variables in Inset VSpace/space
5047                                 if (starred)
5048                                         name += '*';
5049                                 if (valid) {
5050                                         if (value == 1.0)
5051                                                 output_ert_inset(os, name + '{' + unit + '}', context);
5052                                         else if (value == -1.0)
5053                                                 output_ert_inset(os, name + "{-" + unit + '}', context);
5054                                         else
5055                                                 output_ert_inset(os, name + '{' + valstring + unit + '}', context);
5056                                 } else
5057                                         output_ert_inset(os, name + '{' + length + '}', context);
5058                         }
5059                 }
5060
5061                 // The single '=' is meant here.
5062                 else if ((newinsetlayout = findInsetLayout(context.textclass, starredname, true))) {
5063                         if (starred)
5064                                 p.get_token();
5065                         p.skip_spaces();
5066                         context.check_layout(os);
5067                         docstring const name = newinsetlayout->name();
5068                         bool const caption = name.find(from_ascii("Caption:")) == 0;
5069                         if (caption) {
5070                                 // Already done for floating minted listings.
5071                                 if (minted_float.empty()) {
5072                                         begin_inset(os, "Caption ");
5073                                         os << to_utf8(name.substr(8)) << '\n';
5074                                 }
5075                         } else {
5076                                 begin_inset(os, "Flex ");
5077                                 os << to_utf8(name) << '\n'
5078                                    << "status collapsed\n";
5079                         }
5080                         if (!minted_float.empty()) {
5081                                 parse_text_snippet(p, os, FLAG_ITEM, false, context);
5082                         } else if (newinsetlayout->isPassThru()) {
5083                                 // set catcodes to verbatim early, just in case.
5084                                 p.setCatcodes(VERBATIM_CATCODES);
5085                                 string delim = p.get_token().asInput();
5086                                 if (delim != "{")
5087                                         cerr << "Warning: bad delimiter for command " << t.asInput() << endl;
5088                                 //FIXME: handle error condition
5089                                 string const arg = p.verbatimStuff("}").second;
5090                                 Context newcontext(true, context.textclass);
5091                                 if (newinsetlayout->forcePlainLayout())
5092                                         newcontext.layout = &context.textclass.plainLayout();
5093                                 output_ert(os, arg, newcontext);
5094                         } else
5095                                 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
5096                         if (caption)
5097                                 p.skip_spaces();
5098                         // Minted caption insets are not closed here because
5099                         // we collect everything into the caption.
5100                         if (minted_float.empty())
5101                                 end_inset(os);
5102                 }
5103
5104                 else if (t.cs() == "includepdf") {
5105                         p.skip_spaces();
5106                         string const arg = p.getArg('[', ']');
5107                         map<string, string> opts;
5108                         vector<string> keys;
5109                         split_map(arg, opts, keys);
5110                         string name = normalize_filename(p.verbatim_item());
5111                         string const path = getMasterFilePath(true);
5112                         // We want to preserve relative / absolute filenames,
5113                         // therefore path is only used for testing
5114                         if (!makeAbsPath(name, path).exists()) {
5115                                 // The file extension is probably missing.
5116                                 // Now try to find it out.
5117                                 char const * const pdfpages_format[] = {"pdf", 0};
5118                                 string const pdftex_name =
5119                                         find_file(name, path, pdfpages_format);
5120                                 if (!pdftex_name.empty()) {
5121                                         name = pdftex_name;
5122                                         pdflatex = true;
5123                                 }
5124                         }
5125                         FileName const absname = makeAbsPath(name, path);
5126                         if (absname.exists())
5127                         {
5128                                 fix_child_filename(name);
5129                                 copy_file(absname, name);
5130                         } else
5131                                 cerr << "Warning: Could not find file '"
5132                                      << name << "'." << endl;
5133                         // write output
5134                         context.check_layout(os);
5135                         begin_inset(os, "External\n\ttemplate ");
5136                         os << "PDFPages\n\tfilename "
5137                            << name << "\n";
5138                         // parse the options
5139                         if (opts.find("pages") != opts.end())
5140                                 os << "\textra LaTeX \"pages="
5141                                    << opts["pages"] << "\"\n";
5142                         if (opts.find("angle") != opts.end())
5143                                 os << "\trotateAngle "
5144                                    << opts["angle"] << '\n';
5145                         if (opts.find("origin") != opts.end()) {
5146                                 ostringstream ss;
5147                                 string const opt = opts["origin"];
5148                                 if (opt == "tl") ss << "topleft";
5149                                 if (opt == "bl") ss << "bottomleft";
5150                                 if (opt == "Bl") ss << "baselineleft";
5151                                 if (opt == "c") ss << "center";
5152                                 if (opt == "tc") ss << "topcenter";
5153                                 if (opt == "bc") ss << "bottomcenter";
5154                                 if (opt == "Bc") ss << "baselinecenter";
5155                                 if (opt == "tr") ss << "topright";
5156                                 if (opt == "br") ss << "bottomright";
5157                                 if (opt == "Br") ss << "baselineright";
5158                                 if (!ss.str().empty())
5159                                         os << "\trotateOrigin " << ss.str() << '\n';
5160                                 else
5161                                         cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
5162                         }
5163                         if (opts.find("width") != opts.end())
5164                                 os << "\twidth "
5165                                    << translate_len(opts["width"]) << '\n';
5166                         if (opts.find("height") != opts.end())
5167                                 os << "\theight "
5168                                    << translate_len(opts["height"]) << '\n';
5169                         if (opts.find("keepaspectratio") != opts.end())
5170                                 os << "\tkeepAspectRatio\n";
5171                         end_inset(os);
5172                         context.check_layout(os);
5173                         registerExternalTemplatePackages("PDFPages");
5174                 }
5175
5176                 else if (t.cs() == "loadgame") {
5177                         p.skip_spaces();
5178                         string name = normalize_filename(p.verbatim_item());
5179                         string const path = getMasterFilePath(true);
5180                         // We want to preserve relative / absolute filenames,
5181                         // therefore path is only used for testing
5182                         if (!makeAbsPath(name, path).exists()) {
5183                                 // The file extension is probably missing.
5184                                 // Now try to find it out.
5185                                 char const * const lyxskak_format[] = {"fen", 0};
5186                                 string const lyxskak_name =
5187                                         find_file(name, path, lyxskak_format);
5188                                 if (!lyxskak_name.empty())
5189                                         name = lyxskak_name;
5190                         }
5191                         FileName const absname = makeAbsPath(name, path);
5192                         if (absname.exists())
5193                         {
5194                                 fix_child_filename(name);
5195                                 copy_file(absname, name);
5196                         } else
5197                                 cerr << "Warning: Could not find file '"
5198                                      << name << "'." << endl;
5199                         context.check_layout(os);
5200                         begin_inset(os, "External\n\ttemplate ");
5201                         os << "ChessDiagram\n\tfilename "
5202                            << name << "\n";
5203                         end_inset(os);
5204                         context.check_layout(os);
5205                         // after a \loadgame follows a \showboard
5206                         if (p.get_token().asInput() == "showboard")
5207                                 p.get_token();
5208                         registerExternalTemplatePackages("ChessDiagram");
5209                 }
5210
5211                 else {
5212                         // try to see whether the string is in unicodesymbols
5213                         // Only use text mode commands, since we are in text mode here,
5214                         // and math commands may be invalid (bug 6797)
5215                         string name = t.asInput();
5216                         // handle the dingbats, cyrillic and greek
5217                         if (name == "\\ding" || name == "\\textcyr" ||
5218                             (name == "\\textgreek" && !preamble.usePolyglossia()))
5219                                 name = name + '{' + p.getArg('{', '}') + '}';
5220                         // handle the ifsym characters
5221                         else if (name == "\\textifsymbol") {
5222                                 string const optif = p.getFullOpt();
5223                                 string const argif = p.getArg('{', '}');
5224                                 name = name + optif + '{' + argif + '}';
5225                         }
5226                         // handle the \ascii characters
5227                         // the case of \ascii within braces, as LyX outputs it, is already
5228                         // handled for t.cat() == catBegin
5229                         else if (name == "\\ascii") {
5230                                 // the code is "\asci\xxx"
5231                                 name = "{" + name + p.get_token().asInput() + "}";
5232                                 skip_braces(p);
5233                         }
5234                         // handle some TIPA special characters
5235                         else if (preamble.isPackageUsed("tipa")) {
5236                                 if (name == "\\s") {
5237                                         // fromLaTeXCommand() does not yet
5238                                         // recognize tipa short cuts
5239                                         name = "\\textsyllabic";
5240                                 } else if (name == "\\=" &&
5241                                            p.next_token().asInput() == "*") {
5242                                         // fromLaTeXCommand() does not yet
5243                                         // recognize tipa short cuts
5244                                         p.get_token();
5245                                         name = "\\textsubbar";
5246                                 } else if (name == "\\textdoublevertline") {
5247                                         // FIXME: This is not correct,
5248                                         // \textvertline is higher than \textbardbl
5249                                         name = "\\textbardbl";
5250                                         skip_braces(p);
5251                                 } else if (name == "\\!" ) {
5252                                         if (p.next_token().asInput() == "b") {
5253                                                 p.get_token();  // eat 'b'
5254                                                 name = "\\texthtb";
5255                                                 skip_braces(p);
5256                                         } else if (p.next_token().asInput() == "d") {
5257                                                 p.get_token();
5258                                                 name = "\\texthtd";
5259                                                 skip_braces(p);
5260                                         } else if (p.next_token().asInput() == "g") {
5261                                                 p.get_token();
5262                                                 name = "\\texthtg";
5263                                                 skip_braces(p);
5264                                         } else if (p.next_token().asInput() == "G") {
5265                                                 p.get_token();
5266                                                 name = "\\texthtscg";
5267                                                 skip_braces(p);
5268                                         } else if (p.next_token().asInput() == "j") {
5269                                                 p.get_token();
5270                                                 name = "\\texthtbardotlessj";
5271                                                 skip_braces(p);
5272                                         } else if (p.next_token().asInput() == "o") {
5273                                                 p.get_token();
5274                                                 name = "\\textbullseye";
5275                                                 skip_braces(p);
5276                                         }
5277                                 } else if (name == "\\*" ) {
5278                                         if (p.next_token().asInput() == "k") {
5279                                                 p.get_token();
5280                                                 name = "\\textturnk";
5281                                                 skip_braces(p);
5282                                         } else if (p.next_token().asInput() == "r") {
5283                                                 p.get_token();  // eat 'b'
5284                                                 name = "\\textturnr";
5285                                                 skip_braces(p);
5286                                         } else if (p.next_token().asInput() == "t") {
5287                                                 p.get_token();
5288                                                 name = "\\textturnt";
5289                                                 skip_braces(p);
5290                                         } else if (p.next_token().asInput() == "w") {
5291                                                 p.get_token();
5292                                                 name = "\\textturnw";
5293                                                 skip_braces(p);
5294                                         }
5295                                 }
5296                         }
5297                         if ((name.size() == 2 &&
5298                              contains("\"'.=^`bcdHkrtuv~", name[1]) &&
5299                              p.next_token().asInput() != "*") ||
5300                             is_known(name.substr(1), known_tipa_marks)) {
5301                                 // name is a command that corresponds to a
5302                                 // combining character in unicodesymbols.
5303                                 // Append the argument, fromLaTeXCommand()
5304                                 // will either convert it to a single
5305                                 // character or a combining sequence.
5306                                 name += '{' + p.verbatim_item() + '}';
5307                         }
5308                         // now get the character from unicodesymbols
5309                         bool termination;
5310                         docstring rem;
5311                         set<string> req;
5312                         docstring s = normalize_c(encodings.fromLaTeXCommand(from_utf8(name),
5313                                         Encodings::TEXT_CMD, termination, rem, &req));
5314                         if (!s.empty()) {
5315                                 context.check_layout(os);
5316                                 os << to_utf8(s);
5317                                 if (!rem.empty())
5318                                         output_ert_inset(os, to_utf8(rem), context);
5319                                 if (termination)
5320                                         skip_spaces_braces(p);
5321                                 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
5322                                         preamble.registerAutomaticallyLoadedPackage(*it);
5323                         }
5324                         //cerr << "#: " << t << " mode: " << mode << endl;
5325                         // heuristic: read up to next non-nested space
5326                         /*
5327                         string s = t.asInput();
5328                         string z = p.verbatim_item();
5329                         while (p.good() && z != " " && !z.empty()) {
5330                                 //cerr << "read: " << z << endl;
5331                                 s += z;
5332                                 z = p.verbatim_item();
5333                         }
5334                         cerr << "found ERT: " << s << endl;
5335                         output_ert_inset(os, s + ' ', context);
5336                         */
5337                         else {
5338                                 if (t.asInput() == name &&
5339                                     p.next_token().asInput() == "*") {
5340                                         // Starred commands like \vspace*{}
5341                                         p.get_token();  // Eat '*'
5342                                         name += '*';
5343                                 }
5344                                 if (!parse_command(name, p, os, outer, context))
5345                                         output_ert_inset(os, name, context);
5346                         }
5347                 }
5348
5349                 if (flags & FLAG_LEAVE) {
5350                         flags &= ~FLAG_LEAVE;
5351                         break;
5352                 }
5353         }
5354 }
5355
5356
5357 string guessLanguage(Parser & p, string const & lang)
5358 {
5359         typedef std::map<std::string, size_t> LangMap;
5360         // map from language names to number of characters
5361         LangMap used;
5362         used[lang] = 0;
5363         for (char const * const * i = supported_CJK_languages; *i; i++)
5364                 used[string(*i)] = 0;
5365
5366         while (p.good()) {
5367                 Token const t = p.get_token();
5368                 // comments are not counted for any language
5369                 if (t.cat() == catComment)
5370                         continue;
5371                 // commands are not counted as well, but we need to detect
5372                 // \begin{CJK} and switch encoding if needed
5373                 if (t.cat() == catEscape) {
5374                         if (t.cs() == "inputencoding") {
5375                                 string const enc = subst(p.verbatim_item(), "\n", " ");
5376                                 p.setEncoding(enc, Encoding::inputenc);
5377                                 continue;
5378                         }
5379                         if (t.cs() != "begin")
5380                                 continue;
5381                 } else {
5382                         // Non-CJK content is counted for lang.
5383                         // We do not care about the real language here:
5384                         // If we have more non-CJK contents than CJK contents,
5385                         // we simply use the language that was specified as
5386                         // babel main language.
5387                         used[lang] += t.asInput().length();
5388                         continue;
5389                 }
5390                 // Now we are starting an environment
5391                 p.pushPosition();
5392                 string const name = p.getArg('{', '}');
5393                 if (name != "CJK") {
5394                         p.popPosition();
5395                         continue;
5396                 }
5397                 // It is a CJK environment
5398                 p.popPosition();
5399                 /* name = */ p.getArg('{', '}');
5400                 string const encoding = p.getArg('{', '}');
5401                 /* mapping = */ p.getArg('{', '}');
5402                 string const encoding_old = p.getEncoding();
5403                 char const * const * const where =
5404                         is_known(encoding, supported_CJK_encodings);
5405                 if (where)
5406                         p.setEncoding(encoding, Encoding::CJK);
5407                 else
5408                         p.setEncoding("UTF-8");
5409                 string const text = p.ertEnvironment("CJK");
5410                 p.setEncoding(encoding_old);
5411                 p.skip_spaces();
5412                 if (!where) {
5413                         // ignore contents in unknown CJK encoding
5414                         continue;
5415                 }
5416                 // the language of the text
5417                 string const cjk =
5418                         supported_CJK_languages[where - supported_CJK_encodings];
5419                 used[cjk] += text.length();
5420         }
5421         LangMap::const_iterator use = used.begin();
5422         for (LangMap::const_iterator it = used.begin(); it != used.end(); ++it) {
5423                 if (it->second > use->second)
5424                         use = it;
5425         }
5426         return use->first;
5427 }
5428
5429
5430 void check_comment_bib(ostream & os, Context & context)
5431 {
5432         if (!need_commentbib)
5433                 return;
5434         // We have a bibliography database, but no bibliography with biblatex
5435         // which is completely valid. Insert a bibtex inset in a note.
5436         context.check_layout(os);
5437         begin_inset(os, "Note Note\n");
5438         os << "status open\n";
5439         os << "\\begin_layout Plain Layout\n";
5440         begin_command_inset(os, "bibtex", "bibtex");
5441         string bibfiles;
5442         for (auto const & bf : preamble.biblatex_bibliographies) {
5443                 if (!bibfiles.empty())
5444                         bibfiles += ",";
5445                 bibfiles += normalize_filename(bf);
5446         }
5447         if (!bibfiles.empty())
5448                 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
5449         end_inset(os);// Bibtex
5450         os << "\\end_layout\n";
5451         end_inset(os);// Note
5452 }
5453
5454 // }])
5455
5456
5457 } // namespace lyx