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