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