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