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