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