]> git.lyx.org Git - features.git/blob - src/tex2lyx/text.cpp
tex2lyx: also support rotated xltabulars
[features.git] / src / tex2lyx / text.cpp
1 /**
2  * \file tex2lyx/text.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author André Pönitz
7  * \author Jean-Marc Lasgouttes
8  * \author Uwe Stöhr
9  *
10  * Full author contact details are available in file CREDITS.
11  */
12
13 // {[(
14
15 #include <config.h>
16
17 #include "tex2lyx.h"
18
19 #include "Context.h"
20 #include "Encoding.h"
21 #include "FloatList.h"
22 #include "LaTeXPackages.h"
23 #include "Layout.h"
24 #include "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 landscape environments that consists only
1959                 // of a longtable (this is how longtables in LyX are rotated by 90 degs).
1960                 // Other landscape environment is handled via the landscape module, thus
1961                 // we will fall through in that case.
1962                 if (name == "landscape") {
1963                         // We check if the next thing is a longtable
1964                         p.pushPosition();
1965                         bool found_end = false;
1966                         bool only_longtable = false;
1967                         bool end_longtable = false;
1968                         p.get_token();
1969                         p.get_token();
1970                         string envname = p.getArg('{', '}');
1971                         if (envname == "longtable" || envname == "xltabular") {
1972                                 // Now we check if the longtable is the only content
1973                                 // of the landscape environment
1974                                 string const ltenv = envname;
1975                                 while (!found_end && !end_longtable && 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_longtable = t.asInput() != "\\end"
1981                                                         && envname == ltenv;
1982                                         found_end = t.asInput() == "\\end"
1983                                                         && envname == "landscape";
1984                                 }
1985                                 if (end_longtable) {
1986                                         p.get_token();
1987                                         envname = p.getArg('{', '}');
1988                                         only_longtable = p.next_next_token().asInput() == "\\end"
1989                                                         && envname == "landscape";
1990                                 }
1991                                 if (only_longtable) {
1992                                         p.popPosition();
1993                                         p.skip_spaces();
1994                                         int const save_tablerotation = parent_context.tablerotation;
1995                                         parent_context.tablerotation = 90;
1996                                         parse_text(p, os, FLAG_END, outer, parent_context);
1997                                         parent_context.tablerotation = save_tablerotation;
1998                                         p.skip_spaces();
1999                                         break;
2000                                 }
2001                                 // fall through
2002                         }
2003                         // fall through
2004                         p.popPosition();
2005                 }
2006
2007                 if (name == "framed" || name == "shaded") {
2008                         eat_whitespace(p, os, parent_context, false);
2009                         parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
2010                         p.skip_spaces();
2011                         preamble.registerAutomaticallyLoadedPackage("framed");
2012                         break;
2013                 }
2014
2015                 if (name == "listing") {
2016                         minted_float = "float";
2017                         eat_whitespace(p, os, parent_context, false);
2018                         string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
2019                         if (!opt.empty())
2020                                 minted_float += "=" + opt;
2021                         // If something precedes \begin{minted}, we output it at the end
2022                         // as a caption, in order to keep it inside the listings inset.
2023                         eat_whitespace(p, os, parent_context, true);
2024                         p.pushPosition();
2025                         Token const & t = p.get_token();
2026                         p.skip_spaces(true);
2027                         string const envname = p.next_token().cat() == catBegin
2028                                                         ? p.getArg('{', '}') : string();
2029                         bool prologue = t.asInput() != "\\begin" || envname != "minted";
2030                         p.popPosition();
2031                         minted_float_has_caption = false;
2032                         string content = parse_text_snippet(p, FLAG_END, outer,
2033                                                             parent_context);
2034                         size_t i = content.find("\\begin_inset listings");
2035                         bool minted_env = i != string::npos;
2036                         string caption;
2037                         if (prologue) {
2038                                 caption = content.substr(0, i);
2039                                 content.erase(0, i);
2040                         }
2041                         parent_context.check_layout(os);
2042                         if (minted_env && minted_float_has_caption) {
2043                                 eat_whitespace(p, os, parent_context, true);
2044                                 os << content << "\n";
2045                                 if (!caption.empty())
2046                                         os << caption << "\n";
2047                                 os << "\n\\end_layout\n"; // close inner layout
2048                                 end_inset(os);            // close caption inset
2049                                 os << "\n\\end_layout\n"; // close outer layout
2050                         } else if (!caption.empty()) {
2051                                 if (!minted_env) {
2052                                         begin_inset(os, "listings\n");
2053                                         os << "lstparams " << '"' << minted_float << '"' << '\n';
2054                                         os << "inline false\n";
2055                                         os << "status collapsed\n";
2056                                 }
2057                                 os << "\n\\begin_layout Plain Layout\n";
2058                                 begin_inset(os, "Caption Standard\n");
2059                                 Context newcontext(true, parent_context.textclass,
2060                                                    0, 0, parent_context.font);
2061                                 newcontext.check_layout(os);
2062                                 os << caption << "\n";
2063                                 newcontext.check_end_layout(os);
2064                                 end_inset(os);
2065                                 os << "\n\\end_layout\n";
2066                         } else if (content.empty()) {
2067                                 begin_inset(os, "listings\n");
2068                                 os << "lstparams " << '"' << minted_float << '"' << '\n';
2069                                 os << "inline false\n";
2070                                 os << "status collapsed\n";
2071                         } else {
2072                                 os << content << "\n";
2073                         }
2074                         end_inset(os); // close listings inset
2075                         parent_context.check_end_layout(os);
2076                         parent_context.new_paragraph(os);
2077                         p.skip_spaces();
2078                         minted_float.clear();
2079                         minted_float_has_caption = false;
2080                         break;
2081                 }
2082
2083                 if (name == "lstlisting" || name == "minted") {
2084                         bool use_minted = name == "minted";
2085                         // with listings, we do not eat newlines here since
2086                         // \begin{lstlistings}
2087                         // [foo]
2088                         // and
2089                         // // \begin{lstlistings}%
2090                         //
2091                         // [foo]
2092                         // reads [foo] as content, whereas
2093                         // // \begin{lstlistings}%
2094                         // [foo]
2095                         // or
2096                         // \begin{lstlistings}[foo,
2097                         // bar]
2098                         // reads [foo...] as argument.
2099                         eat_whitespace(p, os, parent_context, false, use_minted);
2100                         if (use_minted && minted_float.empty()) {
2101                                 // look ahead for a bottom caption
2102                                 p.pushPosition();
2103                                 bool found_end_minted = false;
2104                                 while (!found_end_minted && p.good()) {
2105                                         Token const & t = p.get_token();
2106                                         p.skip_spaces();
2107                                         string const envname =
2108                                                 p.next_token().cat() == catBegin
2109                                                         ? p.getArg('{', '}') : string();
2110                                         found_end_minted = t.asInput() == "\\end"
2111                                                                 && envname == "minted";
2112                                 }
2113                                 eat_whitespace(p, os, parent_context, true);
2114                                 Token const & t = p.get_token();
2115                                 p.skip_spaces(true);
2116                                 if (t.asInput() == "\\lyxmintcaption") {
2117                                         string const pos = p.getArg('[', ']');
2118                                         if (pos == "b") {
2119                                                 string const caption =
2120                                                         parse_text_snippet(p, FLAG_ITEM,
2121                                                                 false, parent_context);
2122                                                 minted_nonfloat_caption = "[b]" + caption;
2123                                                 eat_whitespace(p, os, parent_context, true);
2124                                         }
2125                                 }
2126                                 p.popPosition();
2127                         }
2128                         parse_listings(p, os, parent_context, false, use_minted);
2129                         p.skip_spaces();
2130                         break;
2131                 }
2132
2133                 if (!parent_context.new_layout_allowed) {
2134                         parse_unknown_environment(p, name, os, FLAG_END, outer,
2135                                                   parent_context);
2136                         break;
2137                 }
2138
2139                 // Alignment and spacing settings
2140                 // FIXME (bug xxxx): These settings can span multiple paragraphs and
2141                 //                                       therefore are totally broken!
2142                 // Note that \centering, \raggedright, and \raggedleft cannot be handled, as
2143                 // they are commands not environments. They are furthermore switches that
2144                 // can be ended by another switches, but also by commands like \footnote or
2145                 // \parbox. So the only safe way is to leave them untouched.
2146                 // However, we support the pseudo-environments
2147                 // \begin{centering} ... \end{centering}
2148                 // \begin{raggedright} ... \end{raggedright}
2149                 // \begin{raggedleft} ... \end{raggedleft}
2150                 // since they are used by LyX in floats (for spacing reasons)
2151                 if (name == "center" || name == "centering"
2152                     || name == "flushleft" || name == "raggedright"
2153                     || name == "flushright" || name == "raggedleft"
2154                     || name == "singlespace" || name == "onehalfspace"
2155                     || name == "doublespace" || name == "spacing") {
2156                         eat_whitespace(p, os, parent_context, false);
2157                         // We must begin a new paragraph if not already done
2158                         if (! parent_context.atParagraphStart()) {
2159                                 parent_context.check_end_layout(os);
2160                                 parent_context.new_paragraph(os);
2161                         }
2162                         if (name == "flushleft" || name == "raggedright")
2163                                 parent_context.add_extra_stuff("\\align left\n");
2164                         else if (name == "flushright" || name == "raggedleft")
2165                                 parent_context.add_extra_stuff("\\align right\n");
2166                         else if (name == "center" || name == "centering")
2167                                 parent_context.add_extra_stuff("\\align center\n");
2168                         else if (name == "singlespace")
2169                                 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
2170                         else if (name == "onehalfspace") {
2171                                 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
2172                                 preamble.registerAutomaticallyLoadedPackage("setspace");
2173                         } else if (name == "doublespace") {
2174                                 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
2175                                 preamble.registerAutomaticallyLoadedPackage("setspace");
2176                         } else if (name == "spacing") {
2177                                 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
2178                                 preamble.registerAutomaticallyLoadedPackage("setspace");
2179                         }
2180                         parse_text(p, os, FLAG_END, outer, parent_context);
2181                         // Just in case the environment is empty
2182                         parent_context.extra_stuff.erase();
2183                         // We must begin a new paragraph to reset the alignment
2184                         parent_context.new_paragraph(os);
2185                         p.skip_spaces();
2186                         break;
2187                 }
2188
2189                 // The single '=' is meant here.
2190                 if ((newlayout = findLayout(parent_context.textclass, name, false))) {
2191                         eat_whitespace(p, os, parent_context, false);
2192                         Context context(true, parent_context.textclass, newlayout,
2193                                         parent_context.layout, parent_context.font);
2194                         if (parent_context.deeper_paragraph) {
2195                                 // We are beginning a nested environment after a
2196                                 // deeper paragraph inside the outer list environment.
2197                                 // Therefore we don't need to output a "begin deeper".
2198                                 context.need_end_deeper = true;
2199                         }
2200                         parent_context.check_end_layout(os);
2201                         if (last_env == name) {
2202                                 // we need to output a separator since LyX would export
2203                                 // the two environments as one otherwise (bug 5716)
2204                                 TeX2LyXDocClass const & textclass(parent_context.textclass);
2205                                 Context newcontext(true, textclass,
2206                                                 &(textclass.defaultLayout()));
2207                                 newcontext.check_layout(os);
2208                                 begin_inset(os, "Separator plain\n");
2209                                 end_inset(os);
2210                                 newcontext.check_end_layout(os);
2211                         }
2212                         switch (context.layout->latextype) {
2213                         case  LATEX_LIST_ENVIRONMENT:
2214                                 context.add_par_extra_stuff("\\labelwidthstring "
2215                                                             + p.verbatim_item() + '\n');
2216                                 p.skip_spaces();
2217                                 break;
2218                         case  LATEX_BIB_ENVIRONMENT:
2219                                 p.verbatim_item(); // swallow next arg
2220                                 p.skip_spaces();
2221                                 break;
2222                         default:
2223                                 break;
2224                         }
2225                         context.check_deeper(os);
2226                         if (newlayout->keepempty) {
2227                                 // We need to start a new paragraph
2228                                 // even if it is empty.
2229                                 context.new_paragraph(os);
2230                                 context.check_layout(os);
2231                         }
2232                         // handle known optional and required arguments
2233                         if (context.layout->latextype == LATEX_ENVIRONMENT)
2234                                 output_arguments(os, p, outer, false, string(), context,
2235                                                  context.layout->latexargs());
2236                         else if (context.layout->latextype == LATEX_ITEM_ENVIRONMENT) {
2237                                 ostringstream oss;
2238                                 output_arguments(oss, p, outer, false, string(), context,
2239                                                  context.layout->latexargs());
2240                                 context.list_extra_stuff = oss.str();
2241                         }
2242                         parse_text(p, os, FLAG_END, outer, context);
2243                         if (context.layout->latextype == LATEX_ENVIRONMENT)
2244                                 output_arguments(os, p, outer, false, "post", context,
2245                                                  context.layout->postcommandargs());
2246                         context.check_end_layout(os);
2247                         if (parent_context.deeper_paragraph) {
2248                                 // We must suppress the "end deeper" because we
2249                                 // suppressed the "begin deeper" above.
2250                                 context.need_end_deeper = false;
2251                         }
2252                         context.check_end_deeper(os);
2253                         parent_context.new_paragraph(os);
2254                         p.skip_spaces();
2255                         if (!preamble.titleLayoutFound())
2256                                 preamble.titleLayoutFound(newlayout->intitle);
2257                         set<string> const & req = newlayout->requires();
2258                         set<string>::const_iterator it = req.begin();
2259                         set<string>::const_iterator en = req.end();
2260                         for (; it != en; ++it)
2261                                 preamble.registerAutomaticallyLoadedPackage(*it);
2262                         break;
2263                 }
2264
2265                 // The single '=' is meant here.
2266                 if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
2267                         eat_whitespace(p, os, parent_context, false);
2268                         parent_context.check_layout(os);
2269                         begin_inset(os, "Flex ");
2270                         docstring flex_name = newinsetlayout->name();
2271                         // FIXME: what do we do if the prefix is not Flex: ?
2272                         if (prefixIs(flex_name, from_ascii("Flex:")))
2273                                 flex_name.erase(0, 5);
2274                         os << to_utf8(flex_name) << '\n'
2275                            << "status collapsed\n";
2276                         if (newinsetlayout->isPassThru()) {
2277                                 string const arg = p.verbatimEnvironment(name);
2278                                 Context context(true, parent_context.textclass,
2279                                                 &parent_context.textclass.plainLayout(),
2280                                                 parent_context.layout);
2281                                 output_ert(os, arg, parent_context);
2282                         } else
2283                                 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
2284                         end_inset(os);
2285                         break;
2286                 }
2287
2288                 if (name == "appendix") {
2289                         // This is no good latex style, but it works and is used in some documents...
2290                         eat_whitespace(p, os, parent_context, false);
2291                         parent_context.check_end_layout(os);
2292                         Context context(true, parent_context.textclass, parent_context.layout,
2293                                         parent_context.layout, parent_context.font);
2294                         context.check_layout(os);
2295                         os << "\\start_of_appendix\n";
2296                         parse_text(p, os, FLAG_END, outer, context);
2297                         context.check_end_layout(os);
2298                         p.skip_spaces();
2299                         break;
2300                 }
2301
2302                 if (known_environments.find(name) != known_environments.end()) {
2303                         vector<ArgumentType> arguments = known_environments[name];
2304                         // The last "argument" denotes wether we may translate the
2305                         // environment contents to LyX
2306                         // The default required if no argument is given makes us
2307                         // compatible with the reLyXre environment.
2308                         ArgumentType contents = arguments.empty() ?
2309                                 required :
2310                                 arguments.back();
2311                         if (!arguments.empty())
2312                                 arguments.pop_back();
2313                         // See comment in parse_unknown_environment()
2314                         bool const specialfont =
2315                                 (parent_context.font != parent_context.normalfont);
2316                         bool const new_layout_allowed =
2317                                 parent_context.new_layout_allowed;
2318                         if (specialfont)
2319                                 parent_context.new_layout_allowed = false;
2320                         parse_arguments("\\begin{" + name + "}", arguments, p, os,
2321                                         outer, parent_context);
2322                         if (contents == verbatim)
2323                                 output_ert_inset(os, p.ertEnvironment(name),
2324                                            parent_context);
2325                         else
2326                                 parse_text_snippet(p, os, FLAG_END, outer,
2327                                                    parent_context);
2328                         output_ert_inset(os, "\\end{" + name + "}", parent_context);
2329                         if (specialfont)
2330                                 parent_context.new_layout_allowed = new_layout_allowed;
2331                         break;
2332                 }
2333
2334                 parse_unknown_environment(p, name, os, FLAG_END, outer, parent_context);
2335                 break;
2336         }// end of loop
2337
2338         last_env = name;
2339         active_environments.pop_back();
2340 }
2341
2342
2343 /// parses a comment and outputs it to \p os.
2344 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context,
2345                    bool skipNewlines = false)
2346 {
2347         LASSERT(t.cat() == catComment, return);
2348         if (!t.cs().empty()) {
2349                 context.check_layout(os);
2350                 output_comment(p, os, t.cs(), context);
2351                 if (p.next_token().cat() == catNewline) {
2352                         // A newline after a comment line starts a new
2353                         // paragraph
2354                         if (context.new_layout_allowed) {
2355                                 if(!context.atParagraphStart())
2356                                         // Only start a new paragraph if not already
2357                                         // done (we might get called recursively)
2358                                         context.new_paragraph(os);
2359                         } else
2360                                 output_ert_inset(os, "\n", context);
2361                         eat_whitespace(p, os, context, true);
2362                 }
2363         } else if (!skipNewlines) {
2364                 // "%\n" combination
2365                 p.skip_spaces();
2366         }
2367 }
2368
2369
2370 /*!
2371  * Reads spaces and comments until the first non-space, non-comment token.
2372  * New paragraphs (double newlines or \\par) are handled like simple spaces
2373  * if \p eatParagraph is true.
2374  * If \p eatNewline is false, newlines won't be treated as whitespace.
2375  * Spaces are skipped, but comments are written to \p os.
2376  */
2377 void eat_whitespace(Parser & p, ostream & os, Context & context,
2378                     bool eatParagraph, bool eatNewline)
2379 {
2380         while (p.good()) {
2381                 Token const & t = p.get_token();
2382                 if (t.cat() == catComment)
2383                         parse_comment(p, os, t, context, !eatNewline);
2384                 else if ((!eatParagraph && p.isParagraph()) ||
2385                          (t.cat() != catSpace && (t.cat() != catNewline || !eatNewline))) {
2386                         p.putback();
2387                         return;
2388                 }
2389         }
2390 }
2391
2392
2393 /*!
2394  * Set a font attribute, parse text and reset the font attribute.
2395  * \param attribute Attribute name (e.g. \\family, \\shape etc.)
2396  * \param currentvalue Current value of the attribute. Is set to the new
2397  * value during parsing.
2398  * \param newvalue New value of the attribute
2399  */
2400 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
2401                            Context & context, string const & attribute,
2402                            string & currentvalue, string const & newvalue)
2403 {
2404         context.check_layout(os);
2405         string const oldvalue = currentvalue;
2406         currentvalue = newvalue;
2407         os << '\n' << attribute << ' ' << newvalue << "\n";
2408         parse_text_snippet(p, os, flags, outer, context);
2409         context.check_layout(os);
2410         os << '\n' << attribute << ' ' << oldvalue << "\n";
2411         currentvalue = oldvalue;
2412 }
2413
2414
2415 /// get the arguments of a natbib or jurabib citation command
2416 void get_cite_arguments(Parser & p, bool natbibOrder,
2417         string & before, string & after, bool const qualified = false)
2418 {
2419         // We need to distinguish "" and "[]", so we can't use p.getOpt().
2420
2421         // text before the citation
2422         before.clear();
2423         // text after the citation
2424         after = qualified ? p.getFullOpt(false, '(', ')') : p.getFullOpt();
2425
2426         if (!after.empty()) {
2427                 before = qualified ? p.getFullOpt(false, '(', ')') : p.getFullOpt();
2428                 if (natbibOrder && !before.empty())
2429                         swap(before, after);
2430         }
2431 }
2432
2433
2434 void copy_file(FileName const & src, string dstname)
2435 {
2436         if (!copyFiles())
2437                 return;
2438         string const absParent = getParentFilePath(false);
2439         FileName dst;
2440         if (FileName::isAbsolute(dstname))
2441                 dst = FileName(dstname);
2442         else
2443                 dst = makeAbsPath(dstname, absParent);
2444         FileName const srcpath = src.onlyPath();
2445         FileName const dstpath = dst.onlyPath();
2446         if (equivalent(srcpath, dstpath))
2447                 return;
2448         if (!dstpath.isDirectory()) {
2449                 if (!dstpath.createPath()) {
2450                         cerr << "Warning: Could not create directory for file `"
2451                              << dst.absFileName() << "´." << endl;
2452                         return;
2453                 }
2454         }
2455         if (dst.isReadableFile()) {
2456                 if (overwriteFiles())
2457                         cerr << "Warning: Overwriting existing file `"
2458                              << dst.absFileName() << "´." << endl;
2459                 else {
2460                         cerr << "Warning: Not overwriting existing file `"
2461                              << dst.absFileName() << "´." << endl;
2462                         return;
2463                 }
2464         }
2465         if (!src.copyTo(dst))
2466                 cerr << "Warning: Could not copy file `" << src.absFileName()
2467                      << "´ to `" << dst.absFileName() << "´." << endl;
2468 }
2469
2470
2471 /// Parse a literate Chunk section. The initial "<<" is already parsed.
2472 bool parse_chunk(Parser & p, ostream & os, Context & context)
2473 {
2474         // check whether a chunk is possible here.
2475         if (!context.textclass.hasInsetLayout(from_ascii("Flex:Chunk"))) {
2476                 return false;
2477         }
2478
2479         p.pushPosition();
2480
2481         // read the parameters
2482         Parser::Arg const params = p.verbatimStuff(">>=\n", false);
2483         if (!params.first) {
2484                 p.popPosition();
2485                 return false;
2486         }
2487
2488         Parser::Arg const code = p.verbatimStuff("\n@");
2489         if (!code.first) {
2490                 p.popPosition();
2491                 return false;
2492         }
2493         string const post_chunk = p.verbatimStuff("\n").second + '\n';
2494         if (post_chunk[0] != ' ' && post_chunk[0] != '\n') {
2495                 p.popPosition();
2496                 return false;
2497         }
2498         // The last newline read is important for paragraph handling
2499         p.putback();
2500         p.deparse();
2501
2502         //cerr << "params=[" << params.second << "], code=[" << code.second << "]" <<endl;
2503         // We must have a valid layout before outputting the Chunk inset.
2504         context.check_layout(os);
2505         Context chunkcontext(true, context.textclass);
2506         chunkcontext.layout = &context.textclass.plainLayout();
2507         begin_inset(os, "Flex Chunk");
2508         os << "\nstatus open\n";
2509         if (!params.second.empty()) {
2510                 chunkcontext.check_layout(os);
2511                 Context paramscontext(true, context.textclass);
2512                 paramscontext.layout = &context.textclass.plainLayout();
2513                 begin_inset(os, "Argument 1");
2514                 os << "\nstatus open\n";
2515                 output_ert(os, params.second, paramscontext);
2516                 end_inset(os);
2517         }
2518         output_ert(os, code.second, chunkcontext);
2519         end_inset(os);
2520
2521         p.dropPosition();
2522         return true;
2523 }
2524
2525
2526 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
2527 bool is_macro(Parser & p)
2528 {
2529         Token first = p.curr_token();
2530         if (first.cat() != catEscape || !p.good())
2531                 return false;
2532         if (first.cs() == "def")
2533                 return true;
2534         if (first.cs() != "global" && first.cs() != "long")
2535                 return false;
2536         Token second = p.get_token();
2537         int pos = 1;
2538         while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
2539                second.cat() == catNewline || second.cat() == catComment)) {
2540                 second = p.get_token();
2541                 pos++;
2542         }
2543         bool secondvalid = second.cat() == catEscape;
2544         Token third;
2545         bool thirdvalid = false;
2546         if (p.good() && first.cs() == "global" && secondvalid &&
2547             second.cs() == "long") {
2548                 third = p.get_token();
2549                 pos++;
2550                 while (p.good() && !p.isParagraph() &&
2551                        (third.cat() == catSpace ||
2552                         third.cat() == catNewline ||
2553                         third.cat() == catComment)) {
2554                         third = p.get_token();
2555                         pos++;
2556                 }
2557                 thirdvalid = third.cat() == catEscape;
2558         }
2559         for (int i = 0; i < pos; ++i)
2560                 p.putback();
2561         if (!secondvalid)
2562                 return false;
2563         if (!thirdvalid)
2564                 return (first.cs() == "global" || first.cs() == "long") &&
2565                        second.cs() == "def";
2566         return first.cs() == "global" && second.cs() == "long" &&
2567                third.cs() == "def";
2568 }
2569
2570
2571 /// Parse a macro definition (assumes that is_macro() returned true)
2572 void parse_macro(Parser & p, ostream & os, Context & context)
2573 {
2574         context.check_layout(os);
2575         Token first = p.curr_token();
2576         Token second;
2577         Token third;
2578         string command = first.asInput();
2579         if (first.cs() != "def") {
2580                 p.get_token();
2581                 eat_whitespace(p, os, context, false);
2582                 second = p.curr_token();
2583                 command += second.asInput();
2584                 if (second.cs() != "def") {
2585                         p.get_token();
2586                         eat_whitespace(p, os, context, false);
2587                         third = p.curr_token();
2588                         command += third.asInput();
2589                 }
2590         }
2591         eat_whitespace(p, os, context, false);
2592         string const name = p.get_token().cs();
2593         eat_whitespace(p, os, context, false);
2594
2595         // parameter text
2596         bool simple = true;
2597         string paramtext;
2598         int arity = 0;
2599         while (p.next_token().cat() != catBegin) {
2600                 if (p.next_token().cat() == catParameter) {
2601                         // # found
2602                         p.get_token();
2603                         paramtext += "#";
2604
2605                         // followed by number?
2606                         if (p.next_token().cat() == catOther) {
2607                                 string s = p.get_token().asInput();
2608                                 paramtext += s;
2609                                 // number = current arity + 1?
2610                                 if (s.size() == 1 && s[0] == arity + '0' + 1)
2611                                         ++arity;
2612                                 else
2613                                         simple = false;
2614                         } else
2615                                 paramtext += p.get_token().cs();
2616                 } else {
2617                         paramtext += p.get_token().cs();
2618                         simple = false;
2619                 }
2620         }
2621
2622         // only output simple (i.e. compatible) macro as FormulaMacros
2623         string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
2624         if (simple) {
2625                 context.check_layout(os);
2626                 begin_inset(os, "FormulaMacro");
2627                 os << "\n\\def" << ert;
2628                 end_inset(os);
2629         } else
2630                 output_ert_inset(os, command + ert, context);
2631 }
2632
2633
2634 void registerExternalTemplatePackages(string const & name)
2635 {
2636         external::TemplateManager const & etm = external::TemplateManager::get();
2637         external::Template const * const et = etm.getTemplateByName(name);
2638         if (!et)
2639                 return;
2640         external::Template::Formats::const_iterator cit = et->formats.end();
2641         if (pdflatex)
2642                 cit = et->formats.find("PDFLaTeX");
2643         if (cit == et->formats.end())
2644                 // If the template has not specified a PDFLaTeX output,
2645                 // we try the LaTeX format.
2646                 cit = et->formats.find("LaTeX");
2647         if (cit == et->formats.end())
2648                 return;
2649         vector<string>::const_iterator qit = cit->second.requirements.begin();
2650         vector<string>::const_iterator qend = cit->second.requirements.end();
2651         for (; qit != qend; ++qit)
2652                 preamble.registerAutomaticallyLoadedPackage(*qit);
2653 }
2654
2655 } // anonymous namespace
2656
2657
2658 /*!
2659  * Find a file with basename \p name in path \p path and an extension
2660  * in \p extensions.
2661  */
2662 string find_file(string const & name, string const & path,
2663                  char const * const * extensions)
2664 {
2665         for (char const * const * what = extensions; *what; ++what) {
2666                 string const trial = addExtension(name, *what);
2667                 if (makeAbsPath(trial, path).exists())
2668                         return trial;
2669         }
2670         return string();
2671 }
2672
2673
2674 /// Convert filenames with TeX macros and/or quotes to something LyX
2675 /// can understand
2676 string const normalize_filename(string const & name)
2677 {
2678         Parser p(name);
2679         ostringstream os;
2680         while (p.good()) {
2681                 Token const & t = p.get_token();
2682                 if (t.cat() != catEscape)
2683                         os << t.asInput();
2684                 else if (t.cs() == "lyxdot") {
2685                         // This is used by LyX for simple dots in relative
2686                         // names
2687                         os << '.';
2688                         p.skip_spaces();
2689                 } else if (t.cs() == "space") {
2690                         os << ' ';
2691                         p.skip_spaces();
2692                 } else if (t.cs() == "string") {
2693                         // Convert \string" to " and \string~ to ~
2694                         Token const & n = p.next_token();
2695                         if (n.asInput() != "\"" && n.asInput() != "~")
2696                                 os << t.asInput();
2697                 } else
2698                         os << t.asInput();
2699         }
2700         // Strip quotes. This is a bit complicated (see latex_path()).
2701         string full = os.str();
2702         if (!full.empty() && full[0] == '"') {
2703                 string base = removeExtension(full);
2704                 string ext = getExtension(full);
2705                 if (!base.empty() && base[base.length()-1] == '"')
2706                         // "a b"
2707                         // "a b".tex
2708                         return addExtension(trim(base, "\""), ext);
2709                 if (full[full.length()-1] == '"')
2710                         // "a b.c"
2711                         // "a b.c".tex
2712                         return trim(full, "\"");
2713         }
2714         return full;
2715 }
2716
2717
2718 /// Convert \p name from TeX convention (relative to master file) to LyX
2719 /// convention (relative to .lyx file) if it is relative
2720 void fix_child_filename(string & name)
2721 {
2722         string const absMasterTeX = getMasterFilePath(true);
2723         bool const isabs = FileName::isAbsolute(name);
2724         // convert from "relative to .tex master" to absolute original path
2725         if (!isabs)
2726                 name = makeAbsPath(name, absMasterTeX).absFileName();
2727         bool copyfile = copyFiles();
2728         string const absParentLyX = getParentFilePath(false);
2729         string abs = name;
2730         if (copyfile) {
2731                 // convert from absolute original path to "relative to master file"
2732                 string const rel = to_utf8(makeRelPath(from_utf8(name),
2733                                                        from_utf8(absMasterTeX)));
2734                 // re-interpret "relative to .tex file" as "relative to .lyx file"
2735                 // (is different if the master .lyx file resides in a
2736                 // different path than the master .tex file)
2737                 string const absMasterLyX = getMasterFilePath(false);
2738                 abs = makeAbsPath(rel, absMasterLyX).absFileName();
2739                 // Do not copy if the new path is impossible to create. Example:
2740                 // absMasterTeX = "/foo/bar/"
2741                 // absMasterLyX = "/bar/"
2742                 // name = "/baz.eps" => new absolute name would be "/../baz.eps"
2743                 if (contains(name, "/../"))
2744                         copyfile = false;
2745         }
2746         if (copyfile) {
2747                 if (isabs)
2748                         name = abs;
2749                 else {
2750                         // convert from absolute original path to
2751                         // "relative to .lyx file"
2752                         name = to_utf8(makeRelPath(from_utf8(abs),
2753                                                    from_utf8(absParentLyX)));
2754                 }
2755         }
2756         else if (!isabs) {
2757                 // convert from absolute original path to "relative to .lyx file"
2758                 name = to_utf8(makeRelPath(from_utf8(name),
2759                                            from_utf8(absParentLyX)));
2760         }
2761 }
2762
2763
2764 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
2765                 Context & context, string const rdelim)
2766 {
2767         Layout const * newlayout = 0;
2768         InsetLayout const * newinsetlayout = 0;
2769         char const * const * where = 0;
2770         // Store the latest bibliographystyle, addcontentslineContent and
2771         // nocite{*} option (needed for bibtex inset)
2772         string btprint;
2773         string contentslineContent;
2774         // Some classes provide a \bibliographystyle, so do not output
2775         // any if none is explicitly set.
2776         string bibliographystyle;
2777         bool const use_natbib = isProvided("natbib");
2778         bool const use_jurabib = isProvided("jurabib");
2779         bool const use_biblatex = isProvided("biblatex")
2780                         && preamble.citeEngine() != "biblatex-natbib";
2781         bool const use_biblatex_natbib = isProvided("biblatex-natbib")
2782                         || (isProvided("biblatex") && preamble.citeEngine() == "biblatex-natbib");
2783         need_commentbib = use_biblatex || use_biblatex_natbib;
2784         string last_env;
2785
2786         // it is impossible to determine the correct encoding for non-CJK Japanese.
2787         // Therefore write a note at the beginning of the document
2788         if (is_nonCJKJapanese) {
2789                 context.check_layout(os);
2790                 begin_inset(os, "Note Note\n");
2791                 os << "status open\n\\begin_layout Plain Layout\n"
2792                    << "\\series bold\n"
2793                    << "Important information:\n"
2794                    << "\\end_layout\n\n"
2795                    << "\\begin_layout Plain Layout\n"
2796                    << "The original LaTeX source for this document is in Japanese (pLaTeX).\n"
2797                    << " It was therefore impossible for tex2lyx to determine the correct encoding.\n"
2798                    << " The iconv encoding " << p.getEncoding() << " was used.\n"
2799                    << " If this is incorrect, you must run the tex2lyx program on the command line\n"
2800                    << " and specify the encoding using the -e command-line switch.\n"
2801                    << " In addition, you might want to double check that the desired output encoding\n"
2802                    << " is correctly selected in Document > Settings > Language.\n"
2803                    << "\\end_layout\n";
2804                 end_inset(os);
2805                 is_nonCJKJapanese = false;
2806         }
2807
2808         bool have_cycled = false;
2809         while (p.good()) {
2810                 // Leave here only after at least one cycle
2811                 if (have_cycled && flags & FLAG_LEAVE) {
2812                         flags &= ~FLAG_LEAVE;
2813                         break;
2814                 }
2815
2816                 Token const & t = p.get_token();
2817 #ifdef FILEDEBUG
2818                 debugToken(cerr, t, flags);
2819 #endif
2820
2821                 if (flags & FLAG_ITEM) {
2822                         if (t.cat() == catSpace)
2823                                 continue;
2824
2825                         flags &= ~FLAG_ITEM;
2826                         if (t.cat() == catBegin) {
2827                                 // skip the brace and collect everything to the next matching
2828                                 // closing brace
2829                                 flags |= FLAG_BRACE_LAST;
2830                                 continue;
2831                         }
2832
2833                         // handle only this single token, leave the loop if done
2834                         flags |= FLAG_LEAVE;
2835                 }
2836
2837                 if (t.cat() != catEscape && t.character() == ']' &&
2838                     (flags & FLAG_BRACK_LAST))
2839                         return;
2840                 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
2841                         return;
2842                 string tok = t.asInput();
2843                 // we only support delimiters with max 2 chars for now.
2844                 if (rdelim.size() > 1)
2845                         tok += p.next_token().asInput();
2846                 if (t.cat() != catEscape && !rdelim.empty()
2847                     && tok == rdelim && (flags & FLAG_RDELIM)) {
2848                         if (rdelim.size() > 1)
2849                                 p.get_token(); // eat rdelim
2850                         return;
2851                 }
2852
2853                 // If there is anything between \end{env} and \begin{env} we
2854                 // don't need to output a separator.
2855                 if (t.cat() != catSpace && t.cat() != catNewline &&
2856                     t.asInput() != "\\begin")
2857                         last_env = "";
2858
2859                 //
2860                 // cat codes
2861                 //
2862                 have_cycled = true;
2863                 bool const starred = p.next_token().asInput() == "*";
2864                 string const starredname(starred ? (t.cs() + '*') : t.cs());
2865                 if (t.cat() == catMath) {
2866                         // we are inside some text mode thingy, so opening new math is allowed
2867                         context.check_layout(os);
2868                         begin_inset(os, "Formula ");
2869                         Token const & n = p.get_token();
2870                         bool const display(n.cat() == catMath && outer);
2871                         if (display) {
2872                                 // TeX's $$...$$ syntax for displayed math
2873                                 os << "\\[";
2874                                 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2875                                 os << "\\]";
2876                                 p.get_token(); // skip the second '$' token
2877                         } else {
2878                                 // simple $...$  stuff
2879                                 p.putback();
2880                                 os << '$';
2881                                 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2882                                 os << '$';
2883                         }
2884                         end_inset(os);
2885                         if (display) {
2886                                 // Prevent the conversion of a line break to a
2887                                 // space (bug 7668). This does not change the
2888                                 // output, but looks ugly in LyX.
2889                                 eat_whitespace(p, os, context, false);
2890                         }
2891                         continue;
2892                 }
2893
2894                 if (t.cat() == catSuper || t.cat() == catSub) {
2895                         cerr << "catcode " << t << " illegal in text mode\n";
2896                         continue;
2897                 }
2898
2899                 // Basic support for quotes. We try to disambiguate
2900                 // quotes from the context (e.g., a left english quote is
2901                 // the same as a right german quote...).
2902                 // Try to make a smart guess about the side
2903                 Token const prev = p.prev_token();
2904                 bool const opening = (prev.cat() != catSpace && prev.character() != 0
2905                                 && prev.character() != '\n' && prev.character() != '~');
2906                 if (t.asInput() == "`" && p.next_token().asInput() == "`") {
2907                         context.check_layout(os);
2908                         begin_inset(os, "Quotes ");
2909                         os << guessQuoteStyle("eld", opening);
2910                         end_inset(os);
2911                         p.get_token();
2912                         skip_braces(p);
2913                         continue;
2914                 }
2915                 if (t.asInput() == "'" && p.next_token().asInput() == "'") {
2916                         context.check_layout(os);
2917                         begin_inset(os, "Quotes ");
2918                         os << guessQuoteStyle("erd", opening);
2919                         end_inset(os);
2920                         p.get_token();
2921                         skip_braces(p);
2922                         continue;
2923                 }
2924
2925                 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
2926                         context.check_layout(os);
2927                         begin_inset(os, "Quotes ");
2928                         os << guessQuoteStyle("ald", opening);
2929                         end_inset(os);
2930                         p.get_token();
2931                         skip_braces(p);
2932                         continue;
2933                 }
2934
2935                 if (t.asInput() == "<"
2936                          && p.next_token().asInput() == "<") {
2937                         bool has_chunk = false;
2938                         if (noweb_mode) {
2939                                 p.pushPosition();
2940                                 p.get_token();
2941                                 has_chunk = parse_chunk(p, os, context);
2942                                 if (!has_chunk)
2943                                         p.popPosition();
2944                         }
2945
2946                         if (!has_chunk) {
2947                                 context.check_layout(os);
2948                                 begin_inset(os, "Quotes ");
2949                                 os << guessQuoteStyle("ard", opening);
2950                                 end_inset(os);
2951                                 p.get_token();
2952                                 skip_braces(p);
2953                         }
2954                         continue;
2955                 }
2956
2957                 if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph())) {
2958                         check_space(p, os, context);
2959                         continue;
2960                 }
2961
2962                 // babel shorthands (also used by polyglossia)
2963                 // Since these can have different meanings for different languages
2964                 // we import them as ERT (but they must be put in ERT to get output
2965                 // verbatim).
2966                 if (t.asInput() == "\"") {
2967                         string s = "\"";
2968                         // These are known pairs. We put them together in
2969                         // one ERT inset. In other cases (such as "a), only
2970                         // the quotation mark is ERTed.
2971                         if (p.next_token().asInput() == "\""
2972                             || p.next_token().asInput() == "|"
2973                             || p.next_token().asInput() == "-"
2974                             || p.next_token().asInput() == "~"
2975                             || p.next_token().asInput() == "="
2976                             || p.next_token().asInput() == "/"
2977                             || p.next_token().asInput() == "~"
2978                             || p.next_token().asInput() == "'"
2979                             || p.next_token().asInput() == "`"
2980                             || p.next_token().asInput() == "<"
2981                             || p.next_token().asInput() == ">") {
2982                                 s += p.next_token().asInput();
2983                                 p.get_token();
2984                         }
2985                         output_ert_inset(os, s, context);
2986                         continue;
2987                 }
2988
2989                 if (t.character() == '[' && noweb_mode &&
2990                          p.next_token().character() == '[') {
2991                         // These can contain underscores
2992                         p.putback();
2993                         string const s = p.getFullOpt() + ']';
2994                         if (p.next_token().character() == ']')
2995                                 p.get_token();
2996                         else
2997                                 cerr << "Warning: Inserting missing ']' in '"
2998                                      << s << "'." << endl;
2999                         output_ert_inset(os, s, context);
3000                         continue;
3001                 }
3002
3003                 if (t.cat() == catLetter) {
3004                         context.check_layout(os);
3005                         os << t.cs();
3006                         continue;
3007                 }
3008
3009                 if (t.cat() == catOther ||
3010                                t.cat() == catAlign ||
3011                                t.cat() == catParameter) {
3012                         context.check_layout(os);
3013                         if (t.asInput() == "-" && p.next_token().asInput() == "-" &&
3014                             context.merging_hyphens_allowed &&
3015                             context.font.family != "ttfamily" &&
3016                             !context.layout->pass_thru) {
3017                                 if (p.next_next_token().asInput() == "-") {
3018                                         // --- is emdash
3019                                         os << to_utf8(docstring(1, 0x2014));
3020                                         p.get_token();
3021                                 } else
3022                                         // -- is endash
3023                                         os << to_utf8(docstring(1, 0x2013));
3024                                 p.get_token();
3025                         } else
3026                                 // This translates "&" to "\\&" which may be wrong...
3027                                 os << t.cs();
3028                         continue;
3029                 }
3030
3031                 if (p.isParagraph()) {
3032                         // In minted floating listings we will collect
3033                         // everything into the caption, where multiple
3034                         // paragraphs are forbidden.
3035                         if (minted_float.empty()) {
3036                                 if (context.new_layout_allowed)
3037                                         context.new_paragraph(os);
3038                                 else
3039                                         output_ert_inset(os, "\\par ", context);
3040                         } else
3041                                 os << ' ';
3042                         eat_whitespace(p, os, context, true);
3043                         continue;
3044                 }
3045
3046                 if (t.cat() == catActive) {
3047                         context.check_layout(os);
3048                         if (t.character() == '~') {
3049                                 if (context.layout->free_spacing)
3050                                         os << ' ';
3051                                 else {
3052                                         begin_inset(os, "space ~\n");
3053                                         end_inset(os);
3054                                 }
3055                         } else
3056                                 os << t.cs();
3057                         continue;
3058                 }
3059
3060                 if (t.cat() == catBegin) {
3061                         Token const next = p.next_token();
3062                         Token const end = p.next_next_token();
3063                         if (next.cat() == catEnd) {
3064                                 // {}
3065                                 Token const prev = p.prev_token();
3066                                 p.get_token();
3067                                 if (p.next_token().character() == '`')
3068                                         ; // ignore it in {}``
3069                                 else
3070                                         output_ert_inset(os, "{}", context);
3071                         } else if (next.cat() == catEscape &&
3072                                    is_known(next.cs(), known_quotes) &&
3073                                    end.cat() == catEnd) {
3074                                 // Something like {\textquoteright} (e.g.
3075                                 // from writer2latex). We may skip the
3076                                 // braces here for better readability.
3077                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3078                                                    outer, context);
3079                         } else if (p.next_token().asInput() == "\\ascii") {
3080                                 // handle the \ascii characters
3081                                 // (the case without braces is handled later)
3082                                 // the code is "{\ascii\xxx}"
3083                                 p.get_token(); // eat \ascii
3084                                 string name2 = p.get_token().asInput();
3085                                 p.get_token(); // eat the final '}'
3086                                 string const name = "{\\ascii" + name2 + "}";
3087                                 bool termination;
3088                                 docstring rem;
3089                                 set<string> req;
3090                                 // get the character from unicodesymbols
3091                                 docstring s = encodings.fromLaTeXCommand(from_utf8(name),
3092                                         Encodings::TEXT_CMD, termination, rem, &req);
3093                                 if (!s.empty()) {
3094                                         context.check_layout(os);
3095                                         os << to_utf8(s);
3096                                         if (!rem.empty())
3097                                                 output_ert_inset(os,
3098                                                         to_utf8(rem), context);
3099                                         for (set<string>::const_iterator it = req.begin();
3100                                              it != req.end(); ++it)
3101                                                 preamble.registerAutomaticallyLoadedPackage(*it);
3102                                 } else
3103                                         // we did not find a non-ert version
3104                                         output_ert_inset(os, name, context);
3105                         } else {
3106                         context.check_layout(os);
3107                         // special handling of font attribute changes
3108                         Token const prev = p.prev_token();
3109                         TeXFont const oldFont = context.font;
3110                         if (next.character() == '[' ||
3111                             next.character() == ']' ||
3112                             next.character() == '*') {
3113                                 p.get_token();
3114                                 if (p.next_token().cat() == catEnd) {
3115                                         os << next.cs();
3116                                         p.get_token();
3117                                 } else {
3118                                         p.putback();
3119                                         output_ert_inset(os, "{", context);
3120                                         parse_text_snippet(p, os,
3121                                                         FLAG_BRACE_LAST,
3122                                                         outer, context);
3123                                         output_ert_inset(os, "}", context);
3124                                 }
3125                         } else if (! context.new_layout_allowed) {
3126                                 output_ert_inset(os, "{", context);
3127                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3128                                                    outer, context);
3129                                 output_ert_inset(os, "}", context);
3130                         } else if (is_known(next.cs(), known_sizes)) {
3131                                 // next will change the size, so we must
3132                                 // reset it here
3133                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3134                                                    outer, context);
3135                                 if (!context.atParagraphStart())
3136                                         os << "\n\\size "
3137                                            << context.font.size << "\n";
3138                         } else if (is_known(next.cs(), known_font_families)) {
3139                                 // next will change the font family, so we
3140                                 // must reset it here
3141                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3142                                                    outer, context);
3143                                 if (!context.atParagraphStart())
3144                                         os << "\n\\family "
3145                                            << context.font.family << "\n";
3146                         } else if (is_known(next.cs(), known_font_series)) {
3147                                 // next will change the font series, so we
3148                                 // must reset it here
3149                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3150                                                    outer, context);
3151                                 if (!context.atParagraphStart())
3152                                         os << "\n\\series "
3153                                            << context.font.series << "\n";
3154                         } else if (is_known(next.cs(), known_font_shapes)) {
3155                                 // next will change the font shape, so we
3156                                 // must reset it here
3157                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3158                                                    outer, context);
3159                                 if (!context.atParagraphStart())
3160                                         os << "\n\\shape "
3161                                            << context.font.shape << "\n";
3162                         } else if (is_known(next.cs(), known_old_font_families) ||
3163                                    is_known(next.cs(), known_old_font_series) ||
3164                                    is_known(next.cs(), known_old_font_shapes)) {
3165                                 // next will change the font family, series
3166                                 // and shape, so we must reset it here
3167                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3168                                                    outer, context);
3169                                 if (!context.atParagraphStart())
3170                                         os <<  "\n\\family "
3171                                            << context.font.family
3172                                            << "\n\\series "
3173                                            << context.font.series
3174                                            << "\n\\shape "
3175                                            << context.font.shape << "\n";
3176                         } else {
3177                                 output_ert_inset(os, "{", context);
3178                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3179                                                    outer, context);
3180                                 output_ert_inset(os, "}", context);
3181                                 }
3182                         }
3183                         continue;
3184                 }
3185
3186                 if (t.cat() == catEnd) {
3187                         if (flags & FLAG_BRACE_LAST) {
3188                                 return;
3189                         }
3190                         cerr << "stray '}' in text\n";
3191                         output_ert_inset(os, "}", context);
3192                         continue;
3193                 }
3194
3195                 if (t.cat() == catComment) {
3196                         parse_comment(p, os, t, context);
3197                         continue;
3198                 }
3199
3200                 //
3201                 // control sequences
3202                 //
3203
3204                 if (t.cs() == "(" || t.cs() == "[") {
3205                         bool const simple = t.cs() == "(";
3206                         context.check_layout(os);
3207                         begin_inset(os, "Formula");
3208                         os << " \\" << t.cs();
3209                         parse_math(p, os, simple ? FLAG_SIMPLE2 : FLAG_EQUATION, MATH_MODE);
3210                         os << '\\' << (simple ? ')' : ']');
3211                         end_inset(os);
3212                         if (!simple) {
3213                                 // Prevent the conversion of a line break to a
3214                                 // space (bug 7668). This does not change the
3215                                 // output, but looks ugly in LyX.
3216                                 eat_whitespace(p, os, context, false);
3217                         }
3218                         continue;
3219                 }
3220
3221                 if (t.cs() == "begin") {
3222                         parse_environment(p, os, outer, last_env,
3223                                           context);
3224                         continue;
3225                 }
3226
3227                 if (t.cs() == "end") {
3228                         if (flags & FLAG_END) {
3229                                 // eat environment name
3230                                 string const name = p.getArg('{', '}');
3231                                 if (name != active_environment())
3232                                         cerr << "\\end{" + name + "} does not match \\begin{"
3233                                                 + active_environment() + "}\n";
3234                                 return;
3235                         }
3236                         p.error("found 'end' unexpectedly");
3237                         continue;
3238                 }
3239
3240                 // "item" by default, but could be something else
3241                 if (t.cs() == context.layout->itemcommand()) {
3242                         string s;
3243                         if (context.layout->labeltype == LABEL_MANUAL) {
3244                                 // FIXME: This swallows comments, but we cannot use
3245                                 //        eat_whitespace() since we must not output
3246                                 //        anything before the item.
3247                                 p.skip_spaces(true);
3248                                 s = p.verbatimOption();
3249                         } else
3250                                 p.skip_spaces(false);
3251                         context.set_item();
3252                         context.check_layout(os);
3253                         if (context.has_item) {
3254                                 // An item in an unknown list-like environment
3255                                 // FIXME: Do this in check_layout()!
3256                                 context.has_item = false;
3257                                 string item = "\\" + context.layout->itemcommand();
3258                                 if (!p.hasOpt())
3259                                         item += " ";
3260                                 output_ert_inset(os, item, context);
3261                         }
3262                         if (context.layout->labeltype != LABEL_MANUAL)
3263                                 output_arguments(os, p, outer, false, "item", context,
3264                                                  context.layout->itemargs());
3265                         if (!context.list_extra_stuff.empty()) {
3266                                 os << context.list_extra_stuff;
3267                                 context.list_extra_stuff.clear();
3268                         }
3269                         else if (!s.empty()) {
3270                                         // LyX adds braces around the argument,
3271                                         // so we need to remove them here.
3272                                         if (s.size() > 2 && s[0] == '{' &&
3273                                             s[s.size()-1] == '}')
3274                                                 s = s.substr(1, s.size()-2);
3275                                         // If the argument contains a space we
3276                                         // must put it into ERT: Otherwise LyX
3277                                         // would misinterpret the space as
3278                                         // item delimiter (bug 7663)
3279                                         if (contains(s, ' ')) {
3280                                                 output_ert_inset(os, s, context);
3281                                         } else {
3282                                                 Parser p2(s + ']');
3283                                                 os << parse_text_snippet(p2,
3284                                                         FLAG_BRACK_LAST, outer, context);
3285                                         }
3286                                         // The space is needed to separate the
3287                                         // item from the rest of the sentence.
3288                                         os << ' ';
3289                                         eat_whitespace(p, os, context, false);
3290                                 }
3291                         continue;
3292                 }
3293
3294                 if (t.cs() == "bibitem") {
3295                         context.set_item();
3296                         context.check_layout(os);
3297                         eat_whitespace(p, os, context, false);
3298                         string label = p.verbatimOption();
3299                         pair<bool, string> lbl = convert_latexed_command_inset_arg(label);
3300                         bool const literal = !lbl.first;
3301                         label = literal ? subst(label, "\n", " ") : lbl.second;
3302                         string lit = literal ? "\"true\"" : "\"false\"";
3303                         string key = convert_literate_command_inset_arg(p.verbatim_item());
3304                         begin_command_inset(os, "bibitem", "bibitem");
3305                         os << "label \"" << label << "\"\n"
3306                            << "key \"" << key << "\"\n"
3307                            << "literal " << lit << "\n";
3308                         end_inset(os);
3309                         continue;
3310                 }
3311
3312                 if (is_macro(p)) {
3313                         // catch the case of \def\inputGnumericTable
3314                         bool macro = true;
3315                         if (t.cs() == "def") {
3316                                 Token second = p.next_token();
3317                                 if (second.cs() == "inputGnumericTable") {
3318                                         p.pushPosition();
3319                                         p.get_token();
3320                                         skip_braces(p);
3321                                         Token third = p.get_token();
3322                                         p.popPosition();
3323                                         if (third.cs() == "input") {
3324                                                 p.get_token();
3325                                                 skip_braces(p);
3326                                                 p.get_token();
3327                                                 string name = normalize_filename(p.verbatim_item());
3328                                                 string const path = getMasterFilePath(true);
3329                                                 // We want to preserve relative / absolute filenames,
3330                                                 // therefore path is only used for testing
3331                                                 // The file extension is in every case ".tex".
3332                                                 // So we need to remove this extension and check for
3333                                                 // the original one.
3334                                                 name = removeExtension(name);
3335                                                 if (!makeAbsPath(name, path).exists()) {
3336                                                         char const * const Gnumeric_formats[] = {"gnumeric",
3337                                                                 "ods", "xls", 0};
3338                                                         string const Gnumeric_name =
3339                                                                 find_file(name, path, Gnumeric_formats);
3340                                                         if (!Gnumeric_name.empty())
3341                                                                 name = Gnumeric_name;
3342                                                 }
3343                                                 FileName const absname = makeAbsPath(name, path);
3344                                                 if (absname.exists()) {
3345                                                         fix_child_filename(name);
3346                                                         copy_file(absname, name);
3347                                                 } else
3348                                                         cerr << "Warning: Could not find file '"
3349                                                              << name << "'." << endl;
3350                                                 context.check_layout(os);
3351                                                 begin_inset(os, "External\n\ttemplate ");
3352                                                 os << "GnumericSpreadsheet\n\tfilename "
3353                                                    << name << "\n";
3354                                                 end_inset(os);
3355                                                 context.check_layout(os);
3356                                                 macro = false;
3357                                                 // register the packages that are automatically loaded
3358                                                 // by the Gnumeric template
3359                                                 registerExternalTemplatePackages("GnumericSpreadsheet");
3360                                         }
3361                                 }
3362                         }
3363                         if (macro)
3364                                 parse_macro(p, os, context);
3365                         continue;
3366                 }
3367
3368                 if (t.cs() == "noindent") {
3369                         p.skip_spaces();
3370                         context.add_par_extra_stuff("\\noindent\n");
3371                         continue;
3372                 }
3373
3374                 if (t.cs() == "appendix") {
3375                         context.add_par_extra_stuff("\\start_of_appendix\n");
3376                         // We need to start a new paragraph. Otherwise the
3377                         // appendix in 'bla\appendix\chapter{' would start
3378                         // too late.
3379                         context.new_paragraph(os);
3380                         // We need to make sure that the paragraph is
3381                         // generated even if it is empty. Otherwise the
3382                         // appendix in '\par\appendix\par\chapter{' would
3383                         // start too late.
3384                         context.check_layout(os);
3385                         // FIXME: This is a hack to prevent paragraph
3386                         // deletion if it is empty. Handle this better!
3387                         output_comment(p, os,
3388                                 "dummy comment inserted by tex2lyx to "
3389                                 "ensure that this paragraph is not empty",
3390                                 context);
3391                         // Both measures above may generate an additional
3392                         // empty paragraph, but that does not hurt, because
3393                         // whitespace does not matter here.
3394                         eat_whitespace(p, os, context, true);
3395                         continue;
3396                 }
3397
3398                 // Must catch empty dates before findLayout is called below
3399                 if (t.cs() == "date") {
3400                         eat_whitespace(p, os, context, false);
3401                         p.pushPosition();
3402                         string const date = p.verbatim_item();
3403                         p.popPosition();
3404                         if (date.empty()) {
3405                                 preamble.suppressDate(true);
3406                                 p.verbatim_item();
3407                         } else {
3408                                 preamble.suppressDate(false);
3409                                 if (context.new_layout_allowed &&
3410                                     (newlayout = findLayout(context.textclass,
3411                                                             t.cs(), true))) {
3412                                         // write the layout
3413                                         output_command_layout(os, p, outer,
3414                                                         context, newlayout);
3415                                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3416                                         if (!preamble.titleLayoutFound())
3417                                                 preamble.titleLayoutFound(newlayout->intitle);
3418                                         set<string> const & req = newlayout->requires();
3419                                         set<string>::const_iterator it = req.begin();
3420                                         set<string>::const_iterator en = req.end();
3421                                         for (; it != en; ++it)
3422                                                 preamble.registerAutomaticallyLoadedPackage(*it);
3423                                 } else
3424                                         output_ert_inset(os,
3425                                                 "\\date{" + p.verbatim_item() + '}',
3426                                                 context);
3427                         }
3428                         continue;
3429                 }
3430
3431                 // Before we look for the layout name with star and alone below, we check the layouts including
3432                 // the LateXParam, which might be one or several options or a star.
3433                 // The single '=' is meant here.
3434                 if (context.new_layout_allowed &&
3435                    (newlayout = findLayout(context.textclass, t.cs(), true, p.getCommandLatexParam()))) {
3436                         // store the latexparam here. This is eaten in output_command_layout
3437                         context.latexparam = newlayout->latexparam();
3438                         // write the layout
3439                         output_command_layout(os, p, outer, context, newlayout);
3440                         context.latexparam.clear();
3441                         p.skip_spaces();
3442                         if (!preamble.titleLayoutFound())
3443                                 preamble.titleLayoutFound(newlayout->intitle);
3444                         set<string> const & req = newlayout->requires();
3445                         for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3446                                 preamble.registerAutomaticallyLoadedPackage(*it);
3447                         continue;
3448                 }
3449
3450
3451                 // Starred section headings
3452                 // Must attempt to parse "Section*" before "Section".
3453                 if ((p.next_token().asInput() == "*") &&
3454                          context.new_layout_allowed &&
3455                          (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
3456                         // write the layout
3457                         p.get_token();
3458                         output_command_layout(os, p, outer, context, newlayout);
3459                         p.skip_spaces();
3460                         if (!preamble.titleLayoutFound())
3461                                 preamble.titleLayoutFound(newlayout->intitle);
3462                         set<string> const & req = newlayout->requires();
3463                         for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3464                                 preamble.registerAutomaticallyLoadedPackage(*it);
3465                         continue;
3466                 }
3467
3468                 // Section headings and the like
3469                 if (context.new_layout_allowed &&
3470                          (newlayout = findLayout(context.textclass, t.cs(), true))) {
3471                         // write the layout
3472                         output_command_layout(os, p, outer, context, newlayout);
3473                         p.skip_spaces();
3474                         if (!preamble.titleLayoutFound())
3475                                 preamble.titleLayoutFound(newlayout->intitle);
3476                         set<string> const & req = newlayout->requires();
3477                         for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3478                                 preamble.registerAutomaticallyLoadedPackage(*it);
3479                         continue;
3480                 }
3481
3482                 if (t.cs() == "subfloat") {
3483                         // the syntax is \subfloat[list entry][sub caption]{content}
3484                         // if it is a table of figure depends on the surrounding float
3485                         p.skip_spaces();
3486                         // do nothing if there is no outer float
3487                         if (!float_type.empty()) {
3488                                 context.check_layout(os);
3489                                 p.skip_spaces();
3490                                 begin_inset(os, "Float " + float_type + "\n");
3491                                 os << "wide false"
3492                                    << "\nsideways false"
3493                                    << "\nstatus collapsed\n\n";
3494                                 // test for caption
3495                                 string caption;
3496                                 bool has_caption = false;
3497                                 if (p.next_token().cat() != catEscape &&
3498                                                 p.next_token().character() == '[') {
3499                                                         p.get_token(); // eat '['
3500                                                         caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
3501                                                         has_caption = true;
3502                                 }
3503                                 // In case we have two optional args, the second is the caption.
3504                                 if (p.next_token().cat() != catEscape &&
3505                                                 p.next_token().character() == '[') {
3506                                                         p.get_token(); // eat '['
3507                                                         caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
3508                                 }
3509                                 // the content
3510                                 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3511                                 // the caption comes always as the last
3512                                 if (has_caption) {
3513                                         // we must make sure that the caption gets a \begin_layout
3514                                         os << "\n\\begin_layout Plain Layout";
3515                                         p.skip_spaces();
3516                                         begin_inset(os, "Caption Standard\n");
3517                                         Context newcontext(true, context.textclass,
3518                                                            0, 0, context.font);
3519                                         newcontext.check_layout(os);
3520                                         os << caption << "\n";
3521                                         newcontext.check_end_layout(os);
3522                                         end_inset(os);
3523                                         p.skip_spaces();
3524                                         // close the layout we opened
3525                                         os << "\n\\end_layout";
3526                                 }
3527                                 end_inset(os);
3528                                 p.skip_spaces();
3529                         } else {
3530                                 // if the float type is not supported or there is no surrounding float
3531                                 // output it as ERT
3532                                 string opt_arg1;
3533                                 string opt_arg2;
3534                                 if (p.hasOpt()) {
3535                                         opt_arg1 = convert_literate_command_inset_arg(p.getFullOpt());
3536                                         if (p.hasOpt())
3537                                                 opt_arg2 = convert_literate_command_inset_arg(p.getFullOpt());
3538                                 }
3539                                 output_ert_inset(os, t.asInput() + opt_arg1 + opt_arg2
3540                                                  + "{" + p.verbatim_item() + '}', context);
3541                         }
3542                         continue;
3543                 }
3544
3545                 if (t.cs() == "xymatrix") {
3546                         // we must open a new math because LyX's xy support is in math
3547                         context.check_layout(os);
3548                         begin_inset(os, "Formula ");
3549                         os << '$';
3550                         os << "\\" << t.cs() << '{';
3551                         parse_math(p, os, FLAG_ITEM, MATH_MODE);
3552                         os << '}' << '$';
3553                         end_inset(os);
3554                         preamble.registerAutomaticallyLoadedPackage("xy");
3555                         continue;
3556                 }
3557
3558                 if (t.cs() == "includegraphics") {
3559                         bool const clip = p.next_token().asInput() == "*";
3560                         if (clip)
3561                                 p.get_token();
3562                         string const arg = p.getArg('[', ']');
3563                         map<string, string> opts;
3564                         vector<string> keys;
3565                         split_map(arg, opts, keys);
3566                         if (clip)
3567                                 opts["clip"] = string();
3568                         string name = normalize_filename(p.verbatim_item());
3569
3570                         string const path = getMasterFilePath(true);
3571                         // We want to preserve relative / absolute filenames,
3572                         // therefore path is only used for testing
3573                         if (!makeAbsPath(name, path).exists()) {
3574                                 // The file extension is probably missing.
3575                                 // Now try to find it out.
3576                                 string const dvips_name =
3577                                         find_file(name, path,
3578                                                   known_dvips_graphics_formats);
3579                                 string const pdftex_name =
3580                                         find_file(name, path,
3581                                                   known_pdftex_graphics_formats);
3582                                 if (!dvips_name.empty()) {
3583                                         if (!pdftex_name.empty()) {
3584                                                 cerr << "This file contains the "
3585                                                         "latex snippet\n"
3586                                                         "\"\\includegraphics{"
3587                                                      << name << "}\".\n"
3588                                                         "However, files\n\""
3589                                                      << dvips_name << "\" and\n\""
3590                                                      << pdftex_name << "\"\n"
3591                                                         "both exist, so I had to make a "
3592                                                         "choice and took the first one.\n"
3593                                                         "Please move the unwanted one "
3594                                                         "someplace else and try again\n"
3595                                                         "if my choice was wrong."
3596                                                      << endl;
3597                                         }
3598                                         name = dvips_name;
3599                                 } else if (!pdftex_name.empty()) {
3600                                         name = pdftex_name;
3601                                         pdflatex = true;
3602                                 }
3603                         }
3604
3605                         FileName const absname = makeAbsPath(name, path);
3606                         if (absname.exists()) {
3607                                 fix_child_filename(name);
3608                                 copy_file(absname, name);
3609                         } else
3610                                 cerr << "Warning: Could not find graphics file '"
3611                                      << name << "'." << endl;
3612
3613                         context.check_layout(os);
3614                         begin_inset(os, "Graphics ");
3615                         os << "\n\tfilename " << name << '\n';
3616                         if (opts.find("width") != opts.end())
3617                                 os << "\twidth "
3618                                    << translate_len(opts["width"]) << '\n';
3619                         if (opts.find("height") != opts.end())
3620                                 os << "\theight "
3621                                    << translate_len(opts["height"]) << '\n';
3622                         if (opts.find("scale") != opts.end()) {
3623                                 istringstream iss(opts["scale"]);
3624                                 double val;
3625                                 iss >> val;
3626                                 val = val*100;
3627                                 os << "\tscale " << val << '\n';
3628                         }
3629                         if (opts.find("angle") != opts.end()) {
3630                                 os << "\trotateAngle "
3631                                    << opts["angle"] << '\n';
3632                                 vector<string>::const_iterator a =
3633                                         find(keys.begin(), keys.end(), "angle");
3634                                 vector<string>::const_iterator s =
3635                                         find(keys.begin(), keys.end(), "width");
3636                                 if (s == keys.end())
3637                                         s = find(keys.begin(), keys.end(), "height");
3638                                 if (s == keys.end())
3639                                         s = find(keys.begin(), keys.end(), "scale");
3640                                 if (s != keys.end() && distance(s, a) > 0)
3641                                         os << "\tscaleBeforeRotation\n";
3642                         }
3643                         if (opts.find("origin") != opts.end()) {
3644                                 ostringstream ss;
3645                                 string const opt = opts["origin"];
3646                                 if (opt.find('l') != string::npos) ss << "left";
3647                                 if (opt.find('r') != string::npos) ss << "right";
3648                                 if (opt.find('c') != string::npos) ss << "center";
3649                                 if (opt.find('t') != string::npos) ss << "Top";
3650                                 if (opt.find('b') != string::npos) ss << "Bottom";
3651                                 if (opt.find('B') != string::npos) ss << "Baseline";
3652                                 if (!ss.str().empty())
3653                                         os << "\trotateOrigin " << ss.str() << '\n';
3654                                 else
3655                                         cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
3656                         }
3657                         if (opts.find("keepaspectratio") != opts.end())
3658                                 os << "\tkeepAspectRatio\n";
3659                         if (opts.find("clip") != opts.end())
3660                                 os << "\tclip\n";
3661                         if (opts.find("draft") != opts.end())
3662                                 os << "\tdraft\n";
3663                         if (opts.find("bb") != opts.end())
3664                                 os << "\tBoundingBox "
3665                                    << opts["bb"] << '\n';
3666                         int numberOfbbOptions = 0;
3667                         if (opts.find("bbllx") != opts.end())
3668                                 numberOfbbOptions++;
3669                         if (opts.find("bblly") != opts.end())
3670                                 numberOfbbOptions++;
3671                         if (opts.find("bburx") != opts.end())
3672                                 numberOfbbOptions++;
3673                         if (opts.find("bbury") != opts.end())
3674                                 numberOfbbOptions++;
3675                         if (numberOfbbOptions == 4)
3676                                 os << "\tBoundingBox "
3677                                    << opts["bbllx"] << " " << opts["bblly"] << " "
3678                                    << opts["bburx"] << " " << opts["bbury"] << '\n';
3679                         else if (numberOfbbOptions > 0)
3680                                 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3681                         numberOfbbOptions = 0;
3682                         if (opts.find("natwidth") != opts.end())
3683                                 numberOfbbOptions++;
3684                         if (opts.find("natheight") != opts.end())
3685                                 numberOfbbOptions++;
3686                         if (numberOfbbOptions == 2)
3687                                 os << "\tBoundingBox 0bp 0bp "
3688                                    << opts["natwidth"] << " " << opts["natheight"] << '\n';
3689                         else if (numberOfbbOptions > 0)
3690                                 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3691                         ostringstream special;
3692                         if (opts.find("hiresbb") != opts.end())
3693                                 special << "hiresbb,";
3694                         if (opts.find("trim") != opts.end())
3695                                 special << "trim,";
3696                         if (opts.find("viewport") != opts.end())
3697                                 special << "viewport=" << opts["viewport"] << ',';
3698                         if (opts.find("totalheight") != opts.end())
3699                                 special << "totalheight=" << opts["totalheight"] << ',';
3700                         if (opts.find("type") != opts.end())
3701                                 special << "type=" << opts["type"] << ',';
3702                         if (opts.find("ext") != opts.end())
3703                                 special << "ext=" << opts["ext"] << ',';
3704                         if (opts.find("read") != opts.end())
3705                                 special << "read=" << opts["read"] << ',';
3706                         if (opts.find("command") != opts.end())
3707                                 special << "command=" << opts["command"] << ',';
3708                         string s_special = special.str();
3709                         if (!s_special.empty()) {
3710                                 // We had special arguments. Remove the trailing ','.
3711                                 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
3712                         }
3713                         // TODO: Handle the unknown settings better.
3714                         // Warn about invalid options.
3715                         // Check whether some option was given twice.
3716                         end_inset(os);
3717                         preamble.registerAutomaticallyLoadedPackage("graphicx");
3718                         continue;
3719                 }
3720
3721                 if (t.cs() == "footnote" ||
3722                          (t.cs() == "thanks" && context.layout->intitle)) {
3723                         p.skip_spaces();
3724                         context.check_layout(os);
3725                         begin_inset(os, "Foot\n");
3726                         os << "status collapsed\n\n";
3727                         parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3728                         end_inset(os);
3729                         continue;
3730                 }
3731
3732                 if (t.cs() == "marginpar") {
3733                         p.skip_spaces();
3734                         context.check_layout(os);
3735                         begin_inset(os, "Marginal\n");
3736                         os << "status collapsed\n\n";
3737                         parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3738                         end_inset(os);
3739                         continue;
3740                 }
3741
3742                 if (t.cs() == "lstinline" || t.cs() == "mintinline") {
3743                         bool const use_minted = t.cs() == "mintinline";
3744                         p.skip_spaces();
3745                         parse_listings(p, os, context, true, use_minted);
3746                         continue;
3747                 }
3748
3749                 if (t.cs() == "ensuremath") {
3750                         p.skip_spaces();
3751                         context.check_layout(os);
3752                         string const s = p.verbatim_item();
3753                         //FIXME: this never triggers in UTF8
3754                         if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
3755                                 os << s;
3756                         else
3757                                 output_ert_inset(os, "\\ensuremath{" + s + "}",
3758                                            context);
3759                         continue;
3760                 }
3761
3762                 else if (t.cs() == "makeindex"
3763                          || ((t.cs() == "maketitle" || t.cs() == context.textclass.titlename())
3764                              && context.textclass.titletype() == TITLE_COMMAND_AFTER)) {
3765                         if (preamble.titleLayoutFound()) {
3766                                 // swallow this
3767                                 skip_spaces_braces(p);
3768                         } else
3769                                 output_ert_inset(os, t.asInput(), context);
3770                         continue;
3771                 }
3772
3773                 if (t.cs() == "tableofcontents"
3774                                 || t.cs() == "lstlistoflistings"
3775                                 || t.cs() == "listoflistings") {
3776                         string name = t.cs();
3777                         if (preamble.minted() && name == "listoflistings")
3778                                 name.insert(0, "lst");
3779                         context.check_layout(os);
3780                         begin_command_inset(os, "toc", name);
3781                         end_inset(os);
3782                         skip_spaces_braces(p);
3783                         if (name == "lstlistoflistings") {
3784                                 if (preamble.minted())
3785                                         preamble.registerAutomaticallyLoadedPackage("minted");
3786                                 else
3787                                         preamble.registerAutomaticallyLoadedPackage("listings");
3788                         }
3789                         continue;
3790                 }
3791
3792                 if (t.cs() == "listoffigures" || t.cs() == "listoftables") {
3793                         context.check_layout(os);
3794                         if (t.cs() == "listoffigures")
3795                                 begin_inset(os, "FloatList figure\n");
3796                         else
3797                                 begin_inset(os, "FloatList table\n");
3798                         end_inset(os);
3799                         skip_spaces_braces(p);
3800                         continue;
3801                 }
3802
3803                 if (t.cs() == "listof") {
3804                         p.skip_spaces(true);
3805                         string const name = p.get_token().cs();
3806                         if (context.textclass.floats().typeExist(name)) {
3807                                 context.check_layout(os);
3808                                 begin_inset(os, "FloatList ");
3809                                 os << name << "\n";
3810                                 end_inset(os);
3811                                 p.get_token(); // swallow second arg
3812                         } else
3813                                 output_ert_inset(os, "\\listof{" + name + "}", context);
3814                         continue;
3815                 }
3816
3817                 if ((where = is_known(t.cs(), known_text_font_families))) {
3818                         parse_text_attributes(p, os, FLAG_ITEM, outer,
3819                                 context, "\\family", context.font.family,
3820                                 known_coded_font_families[where - known_text_font_families]);
3821                         continue;
3822                 }
3823
3824                 // beamer has a \textbf<overlay>{} inset
3825                 if (!p.hasOpt("<") && (where = is_known(t.cs(), known_text_font_series))) {
3826                         parse_text_attributes(p, os, FLAG_ITEM, outer,
3827                                 context, "\\series", context.font.series,
3828                                 known_coded_font_series[where - known_text_font_series]);
3829                         continue;
3830                 }
3831
3832                 // beamer has a \textit<overlay>{} inset
3833                 if (!p.hasOpt("<") && (where = is_known(t.cs(), known_text_font_shapes))) {
3834                         parse_text_attributes(p, os, FLAG_ITEM, outer,
3835                                 context, "\\shape", context.font.shape,
3836                                 known_coded_font_shapes[where - known_text_font_shapes]);
3837                         continue;
3838                 }
3839
3840                 if (t.cs() == "textnormal" || t.cs() == "normalfont") {
3841                         context.check_layout(os);
3842                         TeXFont oldFont = context.font;
3843                         context.font.init();
3844                         context.font.size = oldFont.size;
3845                         os << "\n\\family " << context.font.family << "\n";
3846                         os << "\n\\series " << context.font.series << "\n";
3847                         os << "\n\\shape " << context.font.shape << "\n";
3848                         if (t.cs() == "textnormal") {
3849                                 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3850                                 output_font_change(os, context.font, oldFont);
3851                                 context.font = oldFont;
3852                         } else
3853                                 eat_whitespace(p, os, context, false);
3854                         continue;
3855                 }
3856
3857                 if (t.cs() == "textcolor") {
3858                         // scheme is \textcolor{color name}{text}
3859                         string const color = p.verbatim_item();
3860                         // we support the predefined colors of the color  and the xcolor package
3861                         if (color == "black" || color == "blue" || color == "cyan"
3862                                 || color == "green" || color == "magenta" || color == "red"
3863                                 || color == "white" || color == "yellow") {
3864                                         context.check_layout(os);
3865                                         os << "\n\\color " << color << "\n";
3866                                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3867                                         context.check_layout(os);
3868                                         os << "\n\\color inherit\n";
3869                                         preamble.registerAutomaticallyLoadedPackage("color");
3870                         } else if (color == "brown" || color == "darkgray" || color == "gray"
3871                                 || color == "lightgray" || color == "lime" || color == "olive"
3872                                 || color == "orange" || color == "pink" || color == "purple"
3873                                 || color == "teal" || color == "violet") {
3874                                         context.check_layout(os);
3875                                         os << "\n\\color " << color << "\n";
3876                                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3877                                         context.check_layout(os);
3878                                         os << "\n\\color inherit\n";
3879                                         preamble.registerAutomaticallyLoadedPackage("xcolor");
3880                         } else
3881                                 // for custom defined colors
3882                                 output_ert_inset(os, t.asInput() + "{" + color + "}", context);
3883                         continue;
3884                 }
3885
3886                 if (t.cs() == "underbar" || t.cs() == "uline") {
3887                         // \underbar is not 100% correct (LyX outputs \uline
3888                         // of ulem.sty). The difference is that \ulem allows
3889                         // line breaks, and \underbar does not.
3890                         // Do NOT handle \underline.
3891                         // \underbar cuts through y, g, q, p etc.,
3892                         // \underline does not.
3893                         context.check_layout(os);
3894                         os << "\n\\bar under\n";
3895                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3896                         context.check_layout(os);
3897                         os << "\n\\bar default\n";
3898                         preamble.registerAutomaticallyLoadedPackage("ulem");
3899                         continue;
3900                 }
3901
3902                 if (t.cs() == "sout") {
3903                         context.check_layout(os);
3904                         os << "\n\\strikeout on\n";
3905                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3906                         context.check_layout(os);
3907                         os << "\n\\strikeout default\n";
3908                         preamble.registerAutomaticallyLoadedPackage("ulem");
3909                         continue;
3910                 }
3911
3912                 // beamer has an \emph<overlay>{} inset
3913                 if ((t.cs() == "uuline" || t.cs() == "uwave"
3914                         || t.cs() == "emph" || t.cs() == "noun"
3915                         || t.cs() == "xout") && !p.hasOpt("<")) {
3916                         context.check_layout(os);
3917                         os << "\n\\" << t.cs() << " on\n";
3918                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3919                         context.check_layout(os);
3920                         os << "\n\\" << t.cs() << " default\n";
3921                         if (t.cs() == "uuline" || t.cs() == "uwave" || t.cs() == "xout")
3922                                 preamble.registerAutomaticallyLoadedPackage("ulem");
3923                         continue;
3924                 }
3925
3926                 if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
3927                         context.check_layout(os);
3928                         string name = p.getArg('{', '}');
3929                         string localtime = p.getArg('{', '}');
3930                         preamble.registerAuthor(name);
3931                         Author const & author = preamble.getAuthor(name);
3932                         // from_asctime_utc() will fail if LyX decides to output the
3933                         // time in the text language.
3934                         time_t ptime = from_asctime_utc(localtime);
3935                         if (ptime == static_cast<time_t>(-1)) {
3936                                 cerr << "Warning: Could not parse time `" << localtime
3937                                      << "´ for change tracking, using current time instead.\n";
3938                                 ptime = current_time();
3939                         }
3940                         if (t.cs() == "lyxadded")
3941                                 os << "\n\\change_inserted ";
3942                         else
3943                                 os << "\n\\change_deleted ";
3944                         os << author.bufferId() << ' ' << ptime << '\n';
3945                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3946                         bool dvipost    = LaTeXPackages::isAvailable("dvipost");
3947                         bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
3948                                           LaTeXPackages::isAvailable("xcolor");
3949                         // No need to test for luatex, since luatex comes in
3950                         // two flavours (dvi and pdf), like latex, and those
3951                         // are detected by pdflatex.
3952                         if (pdflatex || xetex) {
3953                                 if (xcolorulem) {
3954                                         preamble.registerAutomaticallyLoadedPackage("ulem");
3955                                         preamble.registerAutomaticallyLoadedPackage("xcolor");
3956                                         preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
3957                                 }
3958                         } else {
3959                                 if (dvipost) {
3960                                         preamble.registerAutomaticallyLoadedPackage("dvipost");
3961                                 } else if (xcolorulem) {
3962                                         preamble.registerAutomaticallyLoadedPackage("ulem");
3963                                         preamble.registerAutomaticallyLoadedPackage("xcolor");
3964                                 }
3965                         }
3966                         continue;
3967                 }
3968
3969                 if (t.cs() == "textipa") {
3970                         context.check_layout(os);
3971                         begin_inset(os, "IPA\n");
3972                         bool merging_hyphens_allowed = context.merging_hyphens_allowed;
3973                         context.merging_hyphens_allowed = false;
3974                         parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3975                         context.merging_hyphens_allowed = merging_hyphens_allowed;
3976                         end_inset(os);
3977                         preamble.registerAutomaticallyLoadedPackage("tipa");
3978                         preamble.registerAutomaticallyLoadedPackage("tipx");
3979                         continue;
3980                 }
3981
3982                 if ((preamble.isPackageUsed("tipa") && t.cs() == "t" && p.next_token().asInput() == "*")
3983                     || t.cs() == "texttoptiebar" || t.cs() == "textbottomtiebar") {
3984                         context.check_layout(os);
3985                         if (t.cs() == "t")
3986                                 // swallow star
3987                                 p.get_token();
3988                         string const type = (t.cs() == "t") ? "bottomtiebar" : t.cs().substr(4);
3989                         begin_inset(os, "IPADeco " + type + "\n");
3990                         os << "status open\n";
3991                         parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3992                         end_inset(os);
3993                         p.skip_spaces();
3994                         continue;
3995                 }
3996
3997                 if (t.cs() == "textvertline") {
3998                         // FIXME: This is not correct, \textvertline is higher than |
3999                         os << "|";
4000                         skip_braces(p);
4001                         continue;
4002                 }
4003
4004                 if (t.cs() == "tone" ) {
4005                         context.check_layout(os);
4006                         // register the tone package
4007                         preamble.registerAutomaticallyLoadedPackage("tone");
4008                         string content = trimSpaceAndEol(p.verbatim_item());
4009                         string command = t.asInput() + "{" + content + "}";
4010                         // some tones can be detected by unicodesymbols, some need special code
4011                         if (is_known(content, known_tones)) {
4012                                 os << "\\IPAChar " << command << "\n";
4013                                 continue;
4014                         }
4015                         // try to see whether the string is in unicodesymbols
4016                         bool termination;
4017                         docstring rem;
4018                         set<string> req;
4019                         docstring s = encodings.fromLaTeXCommand(from_utf8(command),
4020                                 Encodings::TEXT_CMD | Encodings::MATH_CMD,
4021                                 termination, rem, &req);
4022                         if (!s.empty()) {
4023                                 os << to_utf8(s);
4024                                 if (!rem.empty())
4025                                         output_ert_inset(os, to_utf8(rem), context);
4026                                 for (set<string>::const_iterator it = req.begin();
4027                                      it != req.end(); ++it)
4028                                         preamble.registerAutomaticallyLoadedPackage(*it);
4029                         } else
4030                                 // we did not find a non-ert version
4031                                 output_ert_inset(os, command, context);
4032                         continue;
4033                 }
4034
4035                 if (t.cs() == "phantom" || t.cs() == "hphantom" ||
4036                              t.cs() == "vphantom") {
4037                         context.check_layout(os);
4038                         if (t.cs() == "phantom")
4039                                 begin_inset(os, "Phantom Phantom\n");
4040                         if (t.cs() == "hphantom")
4041                                 begin_inset(os, "Phantom HPhantom\n");
4042                         if (t.cs() == "vphantom")
4043                                 begin_inset(os, "Phantom VPhantom\n");
4044                         os << "status open\n";
4045                         parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
4046                                             "Phantom");
4047                         end_inset(os);
4048                         continue;
4049                 }
4050
4051                 if (t.cs() == "href") {
4052                         context.check_layout(os);
4053                         string target = convert_literate_command_inset_arg(p.verbatim_item());
4054                         string name = p.verbatim_item();
4055                         pair<bool, string> nm = convert_latexed_command_inset_arg(name);
4056                         bool const literal = !nm.first;
4057                         name = literal ? subst(name, "\n", " ") : nm.second;
4058                         string lit = literal ? "\"true\"" : "\"false\"";
4059                         string type;
4060                         size_t i = target.find(':');
4061                         if (i != string::npos) {
4062                                 type = target.substr(0, i + 1);
4063                                 if (type == "mailto:" || type == "file:")
4064                                         target = target.substr(i + 1);
4065                                 // handle the case that name is equal to target, except of "http(s)://"
4066                                 else if (target.substr(i + 3) == name && (type == "http:" || type == "https:"))
4067                                         target = name;
4068                         }
4069                         begin_command_inset(os, "href", "href");
4070                         if (name != target)
4071                                 os << "name \"" << name << "\"\n";
4072                         os << "target \"" << target << "\"\n";
4073                         if (type == "mailto:" || type == "file:")
4074                                 os << "type \"" << type << "\"\n";
4075                         os << "literal " << lit << "\n";
4076                         end_inset(os);
4077                         skip_spaces_braces(p);
4078                         continue;
4079                 }
4080
4081                 if (t.cs() == "lyxline") {
4082                         // swallow size argument (it is not used anyway)
4083                         p.getArg('{', '}');
4084                         if (!context.atParagraphStart()) {
4085                                 // so our line is in the middle of a paragraph
4086                                 // we need to add a new line, lest this line
4087                                 // follow the other content on that line and
4088                                 // run off the side of the page
4089                                 // FIXME: This may create an empty paragraph,
4090                                 //        but without that it would not be
4091                                 //        possible to set noindent below.
4092                                 //        Fortunately LaTeX does not care
4093                                 //        about the empty paragraph.
4094                                 context.new_paragraph(os);
4095                         }
4096                         if (preamble.indentParagraphs()) {
4097                                 // we need to unindent, lest the line be too long
4098                                 context.add_par_extra_stuff("\\noindent\n");
4099                         }
4100                         context.check_layout(os);
4101                         begin_command_inset(os, "line", "rule");
4102                         os << "offset \"0.5ex\"\n"
4103                               "width \"100line%\"\n"
4104                               "height \"1pt\"\n";
4105                         end_inset(os);
4106                         continue;
4107                 }
4108
4109                 if (t.cs() == "rule") {
4110                         string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
4111                         string const width = p.getArg('{', '}');
4112                         string const thickness = p.getArg('{', '}');
4113                         context.check_layout(os);
4114                         begin_command_inset(os, "line", "rule");
4115                         if (!offset.empty())
4116                                 os << "offset \"" << translate_len(offset) << "\"\n";
4117                         os << "width \"" << translate_len(width) << "\"\n"
4118                                   "height \"" << translate_len(thickness) << "\"\n";
4119                         end_inset(os);
4120                         continue;
4121                 }
4122
4123                 // handle refstyle first to catch \eqref which can also occur
4124                 // without refstyle. Only recognize these commands if
4125                 // refstyle.sty was found in the preamble (otherwise \eqref
4126                 // and user defined ref commands could be misdetected).
4127                 if ((where = is_known(t.cs(), known_refstyle_commands))
4128                      && preamble.refstyle()) {
4129                         context.check_layout(os);
4130                         begin_command_inset(os, "ref", "formatted");
4131                         os << "reference \"";
4132                         os << known_refstyle_prefixes[where - known_refstyle_commands]
4133                            << ":";
4134                         os << convert_literate_command_inset_arg(p.verbatim_item())
4135                            << "\"\n";
4136                         os << "plural \"false\"\n";
4137                         os << "caps \"false\"\n";
4138                         os << "noprefix \"false\"\n";
4139                         end_inset(os);
4140                         preamble.registerAutomaticallyLoadedPackage("refstyle");
4141                         continue;
4142                 }
4143
4144                 // if refstyle is used, we must not convert \prettyref to a
4145                 // formatted reference, since that would result in a refstyle command.
4146                 if ((where = is_known(t.cs(), known_ref_commands)) &&
4147                          (t.cs() != "prettyref" || !preamble.refstyle())) {
4148                         string const opt = p.getOpt();
4149                         if (opt.empty()) {
4150                                 context.check_layout(os);
4151                                 begin_command_inset(os, "ref",
4152                                         known_coded_ref_commands[where - known_ref_commands]);
4153                                 os << "reference \""
4154                                    << convert_literate_command_inset_arg(p.verbatim_item())
4155                                    << "\"\n";
4156                                 os << "plural \"false\"\n";
4157                                 os << "caps \"false\"\n";
4158                                 os << "noprefix \"false\"\n";
4159                                 end_inset(os);
4160                                 if (t.cs() == "vref" || t.cs() == "vpageref")
4161                                         preamble.registerAutomaticallyLoadedPackage("varioref");
4162                                 else if (t.cs() == "prettyref")
4163                                         preamble.registerAutomaticallyLoadedPackage("prettyref");
4164                         } else {
4165                                 // LyX does not yet support optional arguments of ref commands
4166                                 output_ert_inset(os, t.asInput() + '[' + opt + "]{" +
4167                                        p.verbatim_item() + '}', context);
4168                         }
4169                         continue;
4170                 }
4171
4172                 if (use_natbib &&
4173                          is_known(t.cs(), known_natbib_commands) &&
4174                          ((t.cs() != "citefullauthor" &&
4175                            t.cs() != "citeyear" &&
4176                            t.cs() != "citeyearpar") ||
4177                           p.next_token().asInput() != "*")) {
4178                         context.check_layout(os);
4179                         string command = t.cs();
4180                         if (p.next_token().asInput() == "*") {
4181                                 command += '*';
4182                                 p.get_token();
4183                         }
4184                         if (command == "citefullauthor")
4185                                 // alternative name for "\\citeauthor*"
4186                                 command = "citeauthor*";
4187
4188                         // text before the citation
4189                         string before;
4190                         // text after the citation
4191                         string after;
4192                         get_cite_arguments(p, true, before, after);
4193
4194                         if (command == "cite") {
4195                                 // \cite without optional argument means
4196                                 // \citet, \cite with at least one optional
4197                                 // argument means \citep.
4198                                 if (before.empty() && after.empty())
4199                                         command = "citet";
4200                                 else
4201                                         command = "citep";
4202                         }
4203                         if (before.empty() && after == "[]")
4204                                 // avoid \citet[]{a}
4205                                 after.erase();
4206                         else if (before == "[]" && after == "[]") {
4207                                 // avoid \citet[][]{a}
4208                                 before.erase();
4209                                 after.erase();
4210                         }
4211                         bool literal = false;
4212                         pair<bool, string> aft;
4213                         pair<bool, string> bef;
4214                         // remove the brackets around after and before
4215                         if (!after.empty()) {
4216                                 after.erase(0, 1);
4217                                 after.erase(after.length() - 1, 1);
4218                                 aft = convert_latexed_command_inset_arg(after);
4219                                 literal = !aft.first;
4220                                 after = literal ? subst(after, "\n", " ") : aft.second;
4221                         }
4222                         if (!before.empty()) {
4223                                 before.erase(0, 1);
4224                                 before.erase(before.length() - 1, 1);
4225                                 bef = convert_latexed_command_inset_arg(before);
4226                                 literal |= !bef.first;
4227                                 before = literal ? subst(before, "\n", " ") : bef.second;
4228                                 if (literal && !after.empty())
4229                                         after = subst(after, "\n", " ");
4230                         }
4231                         string lit = literal ? "\"true\"" : "\"false\"";
4232                         begin_command_inset(os, "citation", command);
4233                         os << "after " << '"' << after << '"' << "\n";
4234                         os << "before " << '"' << before << '"' << "\n";
4235                         os << "key \""
4236                            << convert_literate_command_inset_arg(p.verbatim_item())
4237                            << "\"\n"
4238                            << "literal " << lit << "\n";
4239                         end_inset(os);
4240                         // Need to set the cite engine if natbib is loaded by
4241                         // the document class directly
4242                         if (preamble.citeEngine() == "basic")
4243                                 preamble.citeEngine("natbib");
4244                         continue;
4245                 }
4246
4247                 if ((use_biblatex
4248                          && is_known(t.cs(), known_biblatex_commands)
4249                          && ((t.cs() == "cite"
4250                              || t.cs() == "citeauthor"
4251                              || t.cs() == "Citeauthor"
4252                              || t.cs() == "parencite"
4253                              || t.cs() == "citetitle")
4254                          || p.next_token().asInput() != "*"))
4255                         || (use_biblatex_natbib
4256                             && (is_known(t.cs(), known_biblatex_commands)
4257                               || is_known(t.cs(), known_natbib_commands))
4258                             && ((t.cs() == "cite" || t.cs() == "citet" || t.cs() == "Citet"
4259                                || t.cs() == "citep" || t.cs() == "Citep" || t.cs() == "citealt"
4260                                || t.cs() == "Citealt" || t.cs() == "citealp" || t.cs() == "Citealp"
4261                                || t.cs() == "citeauthor" || t.cs() == "Citeauthor"
4262                                || t.cs() == "parencite" || t.cs() == "citetitle")
4263                                || p.next_token().asInput() != "*"))){
4264                         context.check_layout(os);
4265                         string command = t.cs();
4266                         if (p.next_token().asInput() == "*") {
4267                                 command += '*';
4268                                 p.get_token();
4269                         }
4270
4271                         bool const qualified = suffixIs(command, "s");
4272                         if (qualified)
4273                                 command = rtrim(command, "s");
4274
4275                         // text before the citation
4276                         string before;
4277                         // text after the citation
4278                         string after;
4279                         get_cite_arguments(p, true, before, after, qualified);
4280
4281                         // These use natbib cmd names in LyX
4282                         // for inter-citeengine compativility
4283                         if (command == "citeyear")
4284                                 command = "citebyear";
4285                         else if (command == "cite*")
4286                                 command = "citeyear";
4287                         else if (command == "textcite")
4288                                 command = "citet";
4289                         else if (command == "Textcite")
4290                                 command = "Citet";
4291                         else if (command == "parencite")
4292                                 command = "citep";
4293                         else if (command == "Parencite")
4294                                 command = "Citep";
4295                         else if (command == "parencite*")
4296                                 command = "citeyearpar";
4297                         else if (command == "smartcite")
4298                                 command = "footcite";
4299                         else if (command == "Smartcite")
4300                                 command = "Footcite";
4301
4302                         string const emptyarg = qualified ? "()" : "[]";
4303                         if (before.empty() && after == emptyarg)
4304                                 // avoid \cite[]{a}
4305                                 after.erase();
4306                         else if (before == emptyarg && after == emptyarg) {
4307                                 // avoid \cite[][]{a}
4308                                 before.erase();
4309                                 after.erase();
4310                         }
4311                         bool literal = false;
4312                         pair<bool, string> aft;
4313                         pair<bool, string> bef;
4314                         // remove the brackets around after and before
4315                         if (!after.empty()) {
4316                                 after.erase(0, 1);
4317                                 after.erase(after.length() - 1, 1);
4318                                 aft = convert_latexed_command_inset_arg(after);
4319                                 literal = !aft.first;
4320                                 after = literal ? subst(after, "\n", " ") : aft.second;
4321                         }
4322                         if (!before.empty()) {
4323                                 before.erase(0, 1);
4324                                 before.erase(before.length() - 1, 1);
4325                                 bef = convert_latexed_command_inset_arg(before);
4326                                 literal |= !bef.first;
4327                                 before = literal ? subst(before, "\n", " ") : bef.second;
4328                         }
4329                         string keys, pretextlist, posttextlist;
4330                         if (qualified) {
4331                                 map<string, string> pres, posts, preslit, postslit;
4332                                 vector<string> lkeys;
4333                                 // text before the citation
4334                                 string lbefore, lbeforelit;
4335                                 // text after the citation
4336                                 string lafter, lafterlit;
4337                                 string lkey;    
4338                                 pair<bool, string> laft, lbef;
4339                                 while (true) {
4340                                         get_cite_arguments(p, true, lbefore, lafter);
4341                                         // remove the brackets around after and before
4342                                         if (!lafter.empty()) {
4343                                                 lafter.erase(0, 1);
4344                                                 lafter.erase(lafter.length() - 1, 1);
4345                                                 laft = convert_latexed_command_inset_arg(lafter);
4346                                                 literal |= !laft.first;
4347                                                 lafter = laft.second;
4348                                                 lafterlit = subst(lbefore, "\n", " ");
4349                                         }
4350                                         if (!lbefore.empty()) {
4351                                                 lbefore.erase(0, 1);
4352                                                 lbefore.erase(lbefore.length() - 1, 1);
4353                                                 lbef = convert_latexed_command_inset_arg(lbefore);
4354                                                 literal |= !lbef.first;
4355                                                 lbefore = lbef.second;
4356                                                 lbeforelit = subst(lbefore, "\n", " ");
4357                                         }
4358                                         if (lbefore.empty() && lafter == "[]") {
4359                                                 // avoid \cite[]{a}
4360                                                 lafter.erase();
4361                                                 lafterlit.erase();
4362                                         }
4363                                         else if (lbefore == "[]" && lafter == "[]") {
4364                                                 // avoid \cite[][]{a}
4365                                                 lbefore.erase();
4366                                                 lafter.erase();
4367                                                 lbeforelit.erase();
4368                                                 lafterlit.erase();
4369                                         }
4370                                         lkey = p.getArg('{', '}');
4371                                         if (lkey.empty())
4372                                                 break;
4373                                         if (!lbefore.empty()) {
4374                                                 pres.insert(make_pair(lkey, lbefore));
4375                                                 preslit.insert(make_pair(lkey, lbeforelit));
4376                                         }
4377                                         if (!lafter.empty()) {
4378                                                 posts.insert(make_pair(lkey, lafter));
4379                                                 postslit.insert(make_pair(lkey, lafterlit));
4380                                         }
4381                                         lkeys.push_back(lkey);
4382                                 }
4383                                 keys = convert_literate_command_inset_arg(getStringFromVector(lkeys));
4384                                 if (literal) {
4385                                         pres = preslit;
4386                                         posts = postslit;
4387                                 }
4388                                 for (auto const & ptl : pres) {
4389                                         if (!pretextlist.empty())
4390                                                 pretextlist += '\t';
4391                                         pretextlist += ptl.first + " " + ptl.second;
4392                                 }
4393                                 for (auto const & potl : posts) {
4394                                         if (!posttextlist.empty())
4395                                                 posttextlist += '\t';
4396                                         posttextlist += potl.first + " " + potl.second;
4397                                 }
4398                         } else
4399                                 keys = convert_literate_command_inset_arg(p.verbatim_item());
4400                         if (literal) {
4401                                 if (!after.empty())
4402                                         after = subst(after, "\n", " ");
4403                                 if (!before.empty())
4404                                         before = subst(after, "\n", " ");
4405                         }
4406                         string lit = literal ? "\"true\"" : "\"false\"";
4407                         begin_command_inset(os, "citation", command);
4408                         os << "after " << '"' << after << '"' << "\n";
4409                         os << "before " << '"' << before << '"' << "\n";
4410                         os << "key \""
4411                            << keys
4412                            << "\"\n";
4413                         if (!pretextlist.empty())
4414                                 os << "pretextlist " << '"'  << pretextlist << '"' << "\n";
4415                         if (!posttextlist.empty())
4416                                 os << "posttextlist " << '"'  << posttextlist << '"' << "\n";
4417                         os << "literal " << lit << "\n";
4418                         end_inset(os);
4419                         // Need to set the cite engine if biblatex is loaded by
4420                         // the document class directly
4421                         if (preamble.citeEngine() == "basic")
4422                                 use_biblatex_natbib ?
4423                                           preamble.citeEngine("biblatex-natbib")
4424                                         : preamble.citeEngine("biblatex");
4425                         continue;
4426                 }
4427
4428                 if (use_jurabib &&
4429                          is_known(t.cs(), known_jurabib_commands) &&
4430                          (t.cs() == "cite" || p.next_token().asInput() != "*")) {
4431                         context.check_layout(os);
4432                         string command = t.cs();
4433                         if (p.next_token().asInput() == "*") {
4434                                 command += '*';
4435                                 p.get_token();
4436                         }
4437                         char argumentOrder = '\0';
4438                         vector<string> const options =
4439                                 preamble.getPackageOptions("jurabib");
4440                         if (find(options.begin(), options.end(),
4441                                       "natbiborder") != options.end())
4442                                 argumentOrder = 'n';
4443                         else if (find(options.begin(), options.end(),
4444                                            "jurabiborder") != options.end())
4445                                 argumentOrder = 'j';
4446
4447                         // text before the citation
4448                         string before;
4449                         // text after the citation
4450                         string after;
4451                         get_cite_arguments(p, argumentOrder != 'j', before, after);
4452
4453                         string const citation = p.verbatim_item();
4454                         if (!before.empty() && argumentOrder == '\0') {
4455                                 cerr << "Warning: Assuming argument order "
4456                                         "of jurabib version 0.6 for\n'"
4457                                      << command << before << after << '{'
4458                                      << citation << "}'.\n"
4459                                         "Add 'jurabiborder' to the jurabib "
4460                                         "package options if you used an\n"
4461                                         "earlier jurabib version." << endl;
4462                         }
4463                         bool literal = false;
4464                         pair<bool, string> aft;
4465                         pair<bool, string> bef;
4466                         // remove the brackets around after and before
4467                         if (!after.empty()) {
4468                                 after.erase(0, 1);
4469                                 after.erase(after.length() - 1, 1);
4470                                 aft = convert_latexed_command_inset_arg(after);
4471                                 literal = !aft.first;
4472                                 after = literal ? subst(after, "\n", " ") : aft.second;
4473                         }
4474                         if (!before.empty()) {
4475                                 before.erase(0, 1);
4476                                 before.erase(before.length() - 1, 1);
4477                                 bef = convert_latexed_command_inset_arg(before);
4478                                 literal |= !bef.first;
4479                                 before = literal ? subst(before, "\n", " ") : bef.second;
4480                                 if (literal && !after.empty())
4481                                         after = subst(after, "\n", " ");
4482                         }
4483                         string lit = literal ? "\"true\"" : "\"false\"";
4484                         begin_command_inset(os, "citation", command);
4485                         os << "after " << '"' << after << "\"\n"
4486                            << "before " << '"' << before << "\"\n"
4487                            << "key " << '"' << citation << "\"\n"
4488                            << "literal " << lit << "\n";
4489                         end_inset(os);
4490                         // Need to set the cite engine if jurabib is loaded by
4491                         // the document class directly
4492                         if (preamble.citeEngine() == "basic")
4493                                 preamble.citeEngine("jurabib");
4494                         continue;
4495                 }
4496
4497                 if (t.cs() == "cite"
4498                         || t.cs() == "nocite") {
4499                         context.check_layout(os);
4500                         string after = p.getArg('[', ']');
4501                         pair<bool, string> aft = convert_latexed_command_inset_arg(after);
4502                         bool const literal = !aft.first;
4503                         after = literal ? subst(after, "\n", " ") : aft.second;
4504                         string lit = literal ? "\"true\"" : "\"false\"";
4505                         string key = convert_literate_command_inset_arg(p.verbatim_item());
4506                         // store the case that it is "\nocite{*}" to use it later for
4507                         // the BibTeX inset
4508                         if (key != "*") {
4509                                 begin_command_inset(os, "citation", t.cs());
4510                                 os << "after " << '"' << after << "\"\n"
4511                                    << "key " << '"' << key << "\"\n"
4512                                    << "literal " << lit << "\n";
4513                                 end_inset(os);
4514                         } else if (t.cs() == "nocite")
4515                                 btprint = key;
4516                         continue;
4517                 }
4518
4519                 if (t.cs() == "index" ||
4520                     (t.cs() == "sindex" && preamble.use_indices() == "true")) {
4521                         context.check_layout(os);
4522                         string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
4523                                 p.getArg('[', ']') : "";
4524                         string const kind = arg.empty() ? "idx" : arg;
4525                         begin_inset(os, "Index ");
4526                         os << kind << "\nstatus collapsed\n";
4527                         parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
4528                         end_inset(os);
4529                         if (kind != "idx")
4530                                 preamble.registerAutomaticallyLoadedPackage("splitidx");
4531                         continue;
4532                 }
4533
4534                 if (t.cs() == "nomenclature") {
4535                         context.check_layout(os);
4536                         begin_command_inset(os, "nomenclature", "nomenclature");
4537                         string prefix = convert_literate_command_inset_arg(p.getArg('[', ']'));
4538                         if (!prefix.empty())
4539                                 os << "prefix " << '"' << prefix << '"' << "\n";
4540                         string symbol = p.verbatim_item();
4541                         pair<bool, string> sym = convert_latexed_command_inset_arg(symbol);
4542                         bool literal = !sym.first;
4543                         string description = p.verbatim_item();
4544                         pair<bool, string> desc = convert_latexed_command_inset_arg(description);
4545                         literal |= !desc.first;
4546                         if (literal) {
4547                                 symbol = subst(symbol, "\n", " ");
4548                                 description = subst(description, "\n", " ");
4549                         } else {
4550                                 symbol = sym.second;
4551                                 description = desc.second;
4552                         }
4553                         string lit = literal ? "\"true\"" : "\"false\"";
4554                         os << "symbol " << '"' << symbol;
4555                         os << "\"\ndescription \""
4556                            << description << "\"\n"
4557                            << "literal " << lit << "\n";
4558                         end_inset(os);
4559                         preamble.registerAutomaticallyLoadedPackage("nomencl");
4560                         continue;
4561                 }
4562
4563                 if (t.cs() == "label") {
4564                         context.check_layout(os);
4565                         begin_command_inset(os, "label", "label");
4566                         os << "name \""
4567                            << convert_literate_command_inset_arg(p.verbatim_item())
4568                            << "\"\n";
4569                         end_inset(os);
4570                         continue;
4571                 }
4572
4573                 if (t.cs() == "lyxmintcaption") {
4574                         string const pos = p.getArg('[', ']');
4575                         if (pos == "t") {
4576                                 string const caption =
4577                                         parse_text_snippet(p, FLAG_ITEM, false,
4578                                                            context);
4579                                 minted_nonfloat_caption = "[t]" + caption;
4580                         } else {
4581                                 // We already got the caption at the bottom,
4582                                 // so simply skip it.
4583                                 parse_text_snippet(p, FLAG_ITEM, false, context);
4584                         }
4585                         eat_whitespace(p, os, context, true);
4586                         continue;
4587                 }
4588
4589                 if (t.cs() == "printindex" || t.cs() == "printsubindex") {
4590                         context.check_layout(os);
4591                         string commandname = t.cs();
4592                         bool star = false;
4593                         if (p.next_token().asInput() == "*") {
4594                                 commandname += "*";
4595                                 star = true;
4596                                 p.get_token();
4597                         }
4598                         begin_command_inset(os, "index_print", commandname);
4599                         string const indexname = p.getArg('[', ']');
4600                         if (!star) {
4601                                 if (indexname.empty())
4602                                         os << "type \"idx\"\n";
4603                                 else
4604                                         os << "type \"" << indexname << "\"\n";
4605                                 os << "literal \"true\"\n";
4606                         }
4607                         end_inset(os);
4608                         skip_spaces_braces(p);
4609                         preamble.registerAutomaticallyLoadedPackage("makeidx");
4610                         if (preamble.use_indices() == "true")
4611                                 preamble.registerAutomaticallyLoadedPackage("splitidx");
4612                         continue;
4613                 }
4614
4615                 if (t.cs() == "printnomenclature") {
4616                         string width = "";
4617                         string width_type = "";
4618                         context.check_layout(os);
4619                         begin_command_inset(os, "nomencl_print", "printnomenclature");
4620                         // case of a custom width
4621                         if (p.hasOpt()) {
4622                                 width = p.getArg('[', ']');
4623                                 width = translate_len(width);
4624                                 width_type = "custom";
4625                         }
4626                         // case of no custom width
4627                         // the case of no custom width but the width set
4628                         // via \settowidth{\nomlabelwidth}{***} cannot be supported
4629                         // because the user could have set anything, not only the width
4630                         // of the longest label (which would be width_type = "auto")
4631                         string label = convert_literate_command_inset_arg(p.getArg('{', '}'));
4632                         if (label.empty() && width_type.empty())
4633                                 width_type = "none";
4634                         os << "set_width \"" << width_type << "\"\n";
4635                         if (width_type == "custom")
4636                                 os << "width \"" << width << '\"';
4637                         end_inset(os);
4638                         skip_spaces_braces(p);
4639                         preamble.registerAutomaticallyLoadedPackage("nomencl");
4640                         continue;
4641                 }
4642
4643                 if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
4644                         context.check_layout(os);
4645                         begin_inset(os, "script ");
4646                         os << t.cs().substr(4) << '\n';
4647                         newinsetlayout = findInsetLayout(context.textclass, t.cs(), true);
4648                         parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
4649                         end_inset(os);
4650                         if (t.cs() == "textsubscript")
4651                                 preamble.registerAutomaticallyLoadedPackage("subscript");
4652                         continue;
4653                 }
4654
4655                 if ((where = is_known(t.cs(), known_quotes))) {
4656                         context.check_layout(os);
4657                         begin_inset(os, "Quotes ");
4658                         string quotetype = known_coded_quotes[where - known_quotes];
4659                         // try to make a smart guess about the side
4660                         Token const prev = p.prev_token();
4661                         bool const opening = (prev.cat() != catSpace && prev.character() != 0
4662                                         && prev.character() != '\n' && prev.character() != '~');
4663                         quotetype = guessQuoteStyle(quotetype, opening);
4664                         os << quotetype;
4665                         end_inset(os);
4666                         // LyX adds {} after the quote, so we have to eat
4667                         // spaces here if there are any before a possible
4668                         // {} pair.
4669                         eat_whitespace(p, os, context, false);
4670                         skip_braces(p);
4671                         continue;
4672                 }
4673
4674                 if ((where = is_known(t.cs(), known_sizes)) &&
4675                         context.new_layout_allowed) {
4676                         context.check_layout(os);
4677                         TeXFont const oldFont = context.font;
4678                         context.font.size = known_coded_sizes[where - known_sizes];
4679                         output_font_change(os, oldFont, context.font);
4680                         eat_whitespace(p, os, context, false);
4681                         continue;
4682                 }
4683
4684                 if ((where = is_known(t.cs(), known_font_families)) &&
4685                          context.new_layout_allowed) {
4686                         context.check_layout(os);
4687                         TeXFont const oldFont = context.font;
4688                         context.font.family =
4689                                 known_coded_font_families[where - known_font_families];
4690                         output_font_change(os, oldFont, context.font);
4691                         eat_whitespace(p, os, context, false);
4692                         continue;
4693                 }
4694
4695                 if ((where = is_known(t.cs(), known_font_series)) &&
4696                          context.new_layout_allowed) {
4697                         context.check_layout(os);
4698                         TeXFont const oldFont = context.font;
4699                         context.font.series =
4700                                 known_coded_font_series[where - known_font_series];
4701                         output_font_change(os, oldFont, context.font);
4702                         eat_whitespace(p, os, context, false);
4703                         continue;
4704                 }
4705
4706                 if ((where = is_known(t.cs(), known_font_shapes)) &&
4707                          context.new_layout_allowed) {
4708                         context.check_layout(os);
4709                         TeXFont const oldFont = context.font;
4710                         context.font.shape =
4711                                 known_coded_font_shapes[where - known_font_shapes];
4712                         output_font_change(os, oldFont, context.font);
4713                         eat_whitespace(p, os, context, false);
4714                         continue;
4715                 }
4716                 if ((where = is_known(t.cs(), known_old_font_families)) &&
4717                          context.new_layout_allowed) {
4718                         context.check_layout(os);
4719                         TeXFont const oldFont = context.font;
4720                         context.font.init();
4721                         context.font.size = oldFont.size;
4722                         context.font.family =
4723                                 known_coded_font_families[where - known_old_font_families];
4724                         output_font_change(os, oldFont, context.font);
4725                         eat_whitespace(p, os, context, false);
4726                         continue;
4727                 }
4728
4729                 if ((where = is_known(t.cs(), known_old_font_series)) &&
4730                          context.new_layout_allowed) {
4731                         context.check_layout(os);
4732                         TeXFont const oldFont = context.font;
4733                         context.font.init();
4734                         context.font.size = oldFont.size;
4735                         context.font.series =
4736                                 known_coded_font_series[where - known_old_font_series];
4737                         output_font_change(os, oldFont, context.font);
4738                         eat_whitespace(p, os, context, false);
4739                         continue;
4740                 }
4741
4742                 if ((where = is_known(t.cs(), known_old_font_shapes)) &&
4743                          context.new_layout_allowed) {
4744                         context.check_layout(os);
4745                         TeXFont const oldFont = context.font;
4746                         context.font.init();
4747                         context.font.size = oldFont.size;
4748                         context.font.shape =
4749                                 known_coded_font_shapes[where - known_old_font_shapes];
4750                         output_font_change(os, oldFont, context.font);
4751                         eat_whitespace(p, os, context, false);
4752                         continue;
4753                 }
4754
4755                 if (t.cs() == "selectlanguage") {
4756                         context.check_layout(os);
4757                         // save the language for the case that a
4758                         // \foreignlanguage is used
4759                         context.font.language = babel2lyx(p.verbatim_item());
4760                         os << "\n\\lang " << context.font.language << "\n";
4761                         continue;
4762                 }
4763
4764                 if (t.cs() == "foreignlanguage") {
4765                         string const lang = babel2lyx(p.verbatim_item());
4766                         parse_text_attributes(p, os, FLAG_ITEM, outer,
4767                                               context, "\\lang",
4768                                               context.font.language, lang);
4769                         continue;
4770                 }
4771
4772                 if (prefixIs(t.cs(), "text") && preamble.usePolyglossia()
4773                          && is_known(t.cs().substr(4), preamble.polyglossia_languages)) {
4774                         // scheme is \textLANGUAGE{text} where LANGUAGE is in polyglossia_languages[]
4775                         string lang;
4776                         // We have to output the whole command if it has an option
4777                         // because LyX doesn't support this yet, see bug #8214,
4778                         // only if there is a single option specifying a variant, we can handle it.
4779                         if (p.hasOpt()) {
4780                                 string langopts = p.getOpt();
4781                                 // check if the option contains a variant, if yes, extract it
4782                                 string::size_type pos_var = langopts.find("variant");
4783                                 string::size_type i = langopts.find(',');
4784                                 string::size_type k = langopts.find('=', pos_var);
4785                                 if (pos_var != string::npos && i == string::npos) {
4786                                         string variant;
4787                                         variant = langopts.substr(k + 1, langopts.length() - k - 2);
4788                                         lang = preamble.polyglossia2lyx(variant);
4789                                         parse_text_attributes(p, os, FLAG_ITEM, outer,
4790                                                                   context, "\\lang",
4791                                                                   context.font.language, lang);
4792                                 } else
4793                                         output_ert_inset(os, t.asInput() + langopts, context);
4794                         } else {
4795                                 lang = preamble.polyglossia2lyx(t.cs().substr(4, string::npos));
4796                                 parse_text_attributes(p, os, FLAG_ITEM, outer,
4797                                                           context, "\\lang",
4798                                                           context.font.language, lang);
4799                         }
4800                         continue;
4801                 }
4802
4803                 if (t.cs() == "inputencoding") {
4804                         // nothing to write here
4805                         string const enc = subst(p.verbatim_item(), "\n", " ");
4806                         p.setEncoding(enc, Encoding::inputenc);
4807                         continue;
4808                 }
4809
4810                 if (is_known(t.cs(), known_special_chars) ||
4811                     (t.cs() == "protect" &&
4812                      p.next_token().cat() == catEscape &&
4813                      is_known(p.next_token().cs(), known_special_protect_chars))) {
4814                         // LyX sometimes puts a \protect in front, so we have to ignore it
4815                         where = is_known(
4816                                 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
4817                                 known_special_chars);
4818                         context.check_layout(os);
4819                         os << known_coded_special_chars[where - known_special_chars];
4820                         skip_spaces_braces(p);
4821                         continue;
4822                 }
4823
4824                 if ((t.cs() == "nobreakdash" && p.next_token().asInput() == "-") ||
4825                          (t.cs() == "protect" && p.next_token().asInput() == "\\nobreakdash" &&
4826                           p.next_next_token().asInput() == "-") ||
4827                          (t.cs() == "@" && p.next_token().asInput() == ".")) {
4828                         // LyX sometimes puts a \protect in front, so we have to ignore it
4829                         if (t.cs() == "protect")
4830                                 p.get_token();
4831                         context.check_layout(os);
4832                         if (t.cs() == "nobreakdash")
4833                                 os << "\\SpecialChar nobreakdash\n";
4834                         else
4835                                 os << "\\SpecialChar endofsentence\n";
4836                         p.get_token();
4837                         continue;
4838                 }
4839
4840                 if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
4841                             || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
4842                             || t.cs() == "%" || t.cs() == "-") {
4843                         context.check_layout(os);
4844                         if (t.cs() == "-")
4845                                 os << "\\SpecialChar softhyphen\n";
4846                         else
4847                                 os << t.cs();
4848                         continue;
4849                 }
4850
4851                 if (t.cs() == "char") {
4852                         context.check_layout(os);
4853                         if (p.next_token().character() == '`') {
4854                                 p.get_token();
4855                                 if (p.next_token().cs() == "\"") {
4856                                         p.get_token();
4857                                         os << '"';
4858                                         skip_braces(p);
4859                                 } else {
4860                                         output_ert_inset(os, "\\char`", context);
4861                                 }
4862                         } else {
4863                                 output_ert_inset(os, "\\char", context);
4864                         }
4865                         continue;
4866                 }
4867
4868                 if (t.cs() == "verb") {
4869                         context.check_layout(os);
4870                         // set catcodes to verbatim early, just in case.
4871                         p.setCatcodes(VERBATIM_CATCODES);
4872                         string delim = p.get_token().asInput();
4873                         Parser::Arg arg = p.verbatimStuff(delim);
4874                         if (arg.first)
4875                                 output_ert_inset(os, "\\verb" + delim
4876                                                  + arg.second + delim, context);
4877                         else
4878                                 cerr << "invalid \\verb command. Skipping" << endl;
4879                         continue;
4880                 }
4881
4882                 // Problem: \= creates a tabstop inside the tabbing environment
4883                 // and else an accent. In the latter case we really would want
4884                 // \={o} instead of \= o.
4885                 if (t.cs() == "=" && (flags & FLAG_TABBING)) {
4886                         output_ert_inset(os, t.asInput(), context);
4887                         continue;
4888                 }
4889
4890                 if (t.cs() == "\\") {
4891                         context.check_layout(os);
4892                         if (p.hasOpt())
4893                                 output_ert_inset(os, "\\\\" + p.getOpt(), context);
4894                         else if (p.next_token().asInput() == "*") {
4895                                 p.get_token();
4896                                 // getOpt() eats the following space if there
4897                                 // is no optional argument, but that is OK
4898                                 // here since it has no effect in the output.
4899                                 output_ert_inset(os, "\\\\*" + p.getOpt(), context);
4900                         }
4901                         else {
4902                                 begin_inset(os, "Newline newline");
4903                                 end_inset(os);
4904                         }
4905                         continue;
4906                 }
4907
4908                 if (t.cs() == "newline" ||
4909                     (t.cs() == "linebreak" && !p.hasOpt())) {
4910                         context.check_layout(os);
4911                         begin_inset(os, "Newline ");
4912                         os << t.cs();
4913                         end_inset(os);
4914                         skip_spaces_braces(p);
4915                         continue;
4916                 }
4917
4918                 if (t.cs() == "input" || t.cs() == "include"
4919                     || t.cs() == "verbatiminput"
4920                     || t.cs() == "lstinputlisting"
4921                     || t.cs() == "inputminted") {
4922                         string name = t.cs();
4923                         if (name == "verbatiminput"
4924                             && p.next_token().asInput() == "*")
4925                                 name += p.get_token().asInput();
4926                         context.check_layout(os);
4927                         string lstparams;
4928                         bool literal = false;
4929                         if (name == "lstinputlisting" && p.hasOpt()) {
4930                                 lstparams = p.getArg('[', ']');
4931                                 pair<bool, string> oa = convert_latexed_command_inset_arg(lstparams);
4932                                 literal = !oa.first;
4933                                 if (literal)
4934                                         lstparams = subst(lstparams, "\n", " ");
4935                                 else
4936                                         lstparams = oa.second;
4937                         } else if (name == "inputminted") {
4938                                 name = "lstinputlisting";
4939                                 string const lang = p.getArg('{', '}');
4940                                 if (lang != "tex") {
4941                                         string cmd = "\\inputminted{" + lang + "}{";
4942                                         cmd += p.getArg('{', '}') + "}";
4943                                         output_ert_inset(os, cmd, context);
4944                                         continue;
4945                                 }
4946                                 if (prefixIs(minted_nonfloat_caption, "[t]")) {
4947                                         minted_nonfloat_caption.erase(0,3);
4948                                         // extract label and caption from the already produced LyX code
4949                                         vector<string> nfc = getVectorFromString(minted_nonfloat_caption, "\n");
4950                                         string const caption = nfc.front();
4951                                         string label;
4952                                         vector<string>::iterator it =
4953                                                 find(nfc.begin(), nfc.end(), "LatexCommand label");
4954                                         if (it != nfc.end()) {
4955                                                 ++it;
4956                                                 if (it != nfc.end())
4957                                                         label = *it;
4958                                                 label = support::split(label, '"');
4959                                                 label.pop_back();
4960                                         }
4961                                         minted_nonfloat_caption.clear();
4962                                         lstparams = "caption=" + caption;
4963                                         if (!label.empty())
4964                                                 lstparams += ",label=" + label;
4965                                         pair<bool, string> oa = convert_latexed_command_inset_arg(lstparams);
4966                                         literal = !oa.first;
4967                                         if (literal)
4968                                                 lstparams = subst(lstparams, "\n", " ");
4969                                         else
4970                                                 lstparams = oa.second;
4971                                 }
4972                         }
4973                         string lit = literal ? "\"true\"" : "\"false\"";
4974                         string filename(normalize_filename(p.getArg('{', '}')));
4975                         string const path = getMasterFilePath(true);
4976                         // We want to preserve relative / absolute filenames,
4977                         // therefore path is only used for testing
4978                         if ((t.cs() == "include" || t.cs() == "input") &&
4979                             !makeAbsPath(filename, path).exists()) {
4980                                 // The file extension is probably missing.
4981                                 // Now try to find it out.
4982                                 string const tex_name =
4983                                         find_file(filename, path,
4984                                                   known_tex_extensions);
4985                                 if (!tex_name.empty())
4986                                         filename = tex_name;
4987                         }
4988                         bool external = false;
4989                         string outname;
4990                         if (makeAbsPath(filename, path).exists()) {
4991                                 string const abstexname =
4992                                         makeAbsPath(filename, path).absFileName();
4993                                 string const absfigname =
4994                                         changeExtension(abstexname, ".fig");
4995                                 fix_child_filename(filename);
4996                                 string const lyxname = changeExtension(filename,
4997                                         roundtripMode() ? ".lyx.lyx" : ".lyx");
4998                                 string const abslyxname = makeAbsPath(
4999                                         lyxname, getParentFilePath(false)).absFileName();
5000                                 bool xfig = false;
5001                                 if (!skipChildren())
5002                                         external = FileName(absfigname).exists();
5003                                 if (t.cs() == "input" && !skipChildren()) {
5004                                         string const ext = getExtension(abstexname);
5005
5006                                         // Combined PS/LaTeX:
5007                                         // x.eps, x.pstex_t (old xfig)
5008                                         // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
5009                                         FileName const absepsname(
5010                                                 changeExtension(abstexname, ".eps"));
5011                                         FileName const abspstexname(
5012                                                 changeExtension(abstexname, ".pstex"));
5013                                         bool const xfigeps =
5014                                                 (absepsname.exists() ||
5015                                                  abspstexname.exists()) &&
5016                                                 ext == "pstex_t";
5017
5018                                         // Combined PDF/LaTeX:
5019                                         // x.pdf, x.pdftex_t (old xfig)
5020                                         // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
5021                                         FileName const abspdfname(
5022                                                 changeExtension(abstexname, ".pdf"));
5023                                         bool const xfigpdf =
5024                                                 abspdfname.exists() &&
5025                                                 (ext == "pdftex_t" || ext == "pdf_t");
5026                                         if (xfigpdf)
5027                                                 pdflatex = true;
5028
5029                                         // Combined PS/PDF/LaTeX:
5030                                         // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
5031                                         string const absbase2(
5032                                                 removeExtension(abstexname) + "_pspdftex");
5033                                         FileName const abseps2name(
5034                                                 addExtension(absbase2, ".eps"));
5035                                         FileName const abspdf2name(
5036                                                 addExtension(absbase2, ".pdf"));
5037                                         bool const xfigboth =
5038                                                 abspdf2name.exists() &&
5039                                                 abseps2name.exists() && ext == "pspdftex";
5040
5041                                         xfig = xfigpdf || xfigeps || xfigboth;
5042                                         external = external && xfig;
5043                                 }
5044                                 if (external) {
5045                                         outname = changeExtension(filename, ".fig");
5046                                         FileName abssrc(changeExtension(abstexname, ".fig"));
5047                                         copy_file(abssrc, outname);
5048                                 } else if (xfig) {
5049                                         // Don't try to convert, the result
5050                                         // would be full of ERT.
5051                                         outname = filename;
5052                                         FileName abssrc(abstexname);
5053                                         copy_file(abssrc, outname);
5054                                 } else if (t.cs() != "verbatiminput" &&
5055                                            !skipChildren() &&
5056                                     tex2lyx(abstexname, FileName(abslyxname),
5057                                             p.getEncoding())) {
5058                                         outname = lyxname;
5059                                         // no need to call copy_file
5060                                         // tex2lyx creates the file
5061                                 } else {
5062                                         outname = filename;
5063                                         FileName abssrc(abstexname);
5064                                         copy_file(abssrc, outname);
5065                                 }
5066                         } else {
5067                                 cerr << "Warning: Could not find included file '"
5068                                      << filename << "'." << endl;
5069                                 outname = filename;
5070                         }
5071                         if (external) {
5072                                 begin_inset(os, "External\n");
5073                                 os << "\ttemplate XFig\n"
5074                                    << "\tfilename " << outname << '\n';
5075                                 registerExternalTemplatePackages("XFig");
5076                         } else {
5077                                 begin_command_inset(os, "include", name);
5078                                 outname = subst(outname, "\"", "\\\"");
5079                                 os << "preview false\n"
5080                                       "filename \"" << outname << "\"\n";
5081                                 if (!lstparams.empty())
5082                                         os << "lstparams \"" << lstparams << "\"\n";
5083                                 os << "literal " << lit << "\n";
5084                                 if (t.cs() == "verbatiminput")
5085                                         preamble.registerAutomaticallyLoadedPackage("verbatim");
5086                         }
5087                         end_inset(os);
5088                         continue;
5089                 }
5090
5091                 if (t.cs() == "bibliographystyle") {
5092                         // store new bibliographystyle
5093                         bibliographystyle = p.verbatim_item();
5094                         // If any other command than \bibliography, \addcontentsline
5095                         // and \nocite{*} follows, we need to output the style
5096                         // (because it might be used by that command).
5097                         // Otherwise, it will automatically be output by LyX.
5098                         p.pushPosition();
5099                         bool output = true;
5100                         for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
5101                                 if (t2.cat() == catBegin)
5102                                         break;
5103                                 if (t2.cat() != catEscape)
5104                                         continue;
5105                                 if (t2.cs() == "nocite") {
5106                                         if (p.getArg('{', '}') == "*")
5107                                                 continue;
5108                                 } else if (t2.cs() == "bibliography")
5109                                         output = false;
5110                                 else if (t2.cs() == "phantomsection") {
5111                                         output = false;
5112                                         continue;
5113                                 }
5114                                 else if (t2.cs() == "addcontentsline") {
5115                                         // get the 3 arguments of \addcontentsline
5116                                         p.getArg('{', '}');
5117                                         p.getArg('{', '}');
5118                                         contentslineContent = p.getArg('{', '}');
5119                                         // if the last argument is not \refname we must output
5120                                         if (contentslineContent == "\\refname")
5121                                                 output = false;
5122                                 }
5123                                 break;
5124                         }
5125                         p.popPosition();
5126                         if (output) {
5127                                 output_ert_inset(os,
5128                                         "\\bibliographystyle{" + bibliographystyle + '}',
5129                                         context);
5130                         }
5131                         continue;
5132                 }
5133
5134                 if (t.cs() == "phantomsection") {
5135                         // we only support this if it occurs between
5136                         // \bibliographystyle and \bibliography
5137                         if (bibliographystyle.empty())
5138                                 output_ert_inset(os, "\\phantomsection", context);
5139                         continue;
5140                 }
5141
5142                 if (t.cs() == "addcontentsline") {
5143                         context.check_layout(os);
5144                         // get the 3 arguments of \addcontentsline
5145                         string const one = p.getArg('{', '}');
5146                         string const two = p.getArg('{', '}');
5147                         string const three = p.getArg('{', '}');
5148                         // only if it is a \refname, we support if for the bibtex inset
5149                         if (contentslineContent != "\\refname") {
5150                                 output_ert_inset(os,
5151                                         "\\addcontentsline{" + one + "}{" + two + "}{"+ three + '}',
5152                                         context);
5153                         }
5154                         continue;
5155                 }
5156
5157                 else if (t.cs() == "bibliography") {
5158                         context.check_layout(os);
5159                         string BibOpts;
5160                         begin_command_inset(os, "bibtex", "bibtex");
5161                         if (!btprint.empty()) {
5162                                 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
5163                                 // clear the string because the next BibTeX inset can be without the
5164                                 // \nocite{*} option
5165                                 btprint.clear();
5166                         }
5167                         os << "bibfiles " << '"' << normalize_filename(p.verbatim_item()) << '"' << "\n";
5168                         // Do we have addcontentsline?
5169                         if (contentslineContent == "\\refname") {
5170                                 BibOpts = "bibtotoc";
5171                                 // clear string because next BibTeX inset can be without addcontentsline
5172                                 contentslineContent.clear();
5173                         }
5174                         // Do we have a bibliographystyle set?
5175                         if (!bibliographystyle.empty()) {
5176                                 if (BibOpts.empty())
5177                                         BibOpts = normalize_filename(bibliographystyle);
5178                                 else
5179                                         BibOpts = BibOpts + ',' + normalize_filename(bibliographystyle);
5180                                 // clear it because each bibtex entry has its style
5181                                 // and we need an empty string to handle \phantomsection
5182                                 bibliographystyle.clear();
5183                         }
5184                         os << "options " << '"' << BibOpts << '"' << "\n";
5185                         if (p.getEncoding() != preamble.docencoding) {
5186                                 Encoding const * const enc = encodings.fromIconvName(
5187                                         p.getEncoding(), Encoding::inputenc, true);
5188                                 if (!enc) {
5189                                         cerr << "Unknown bib encoding " << p.getEncoding()
5190                                              << ". Ignoring." << std::endl;
5191                                 } else
5192                                         os << "encoding " << '"' << enc->name() << '"' << "\n";
5193                         }
5194                         end_inset(os);
5195                         continue;
5196                 }
5197
5198                 if (t.cs() == "printbibliography") {
5199                         context.check_layout(os);
5200                         string BibOpts;
5201                         string bbloptions = p.hasOpt() ? p.getArg('[', ']') : string();
5202                         vector<string> opts = getVectorFromString(bbloptions);
5203                         vector<string>::iterator it =
5204                                 find(opts.begin(), opts.end(), "heading=bibintoc");
5205                         if (it != opts.end()) {
5206                                 opts.erase(it);
5207                                 BibOpts = "bibtotoc";
5208                         }
5209                         bbloptions = getStringFromVector(opts);
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                         string bibfiles;
5218                         for (auto const & bf : preamble.biblatex_bibliographies) {
5219                                 if (!bibfiles.empty())
5220                                         bibfiles += ",";
5221                                 bibfiles += normalize_filename(bf);
5222                         }
5223                         if (!bibfiles.empty())
5224                                 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
5225                         // Do we have addcontentsline?
5226                         if (contentslineContent == "\\refname") {
5227                                 BibOpts = "bibtotoc";
5228                                 // clear string because next BibTeX inset can be without addcontentsline
5229                                 contentslineContent.clear();
5230                         }
5231                         os << "options " << '"' << BibOpts << '"' << "\n";
5232                         if (!bbloptions.empty())
5233                                 os << "biblatexopts " << '"' << bbloptions << '"' << "\n";
5234                         if (!preamble.bibencoding.empty()) {
5235                                 Encoding const * const enc = encodings.fromLaTeXName(
5236                                         preamble.bibencoding, Encoding::inputenc, true);
5237                                 if (!enc) {
5238                                         cerr << "Unknown bib encoding " << preamble.bibencoding
5239                                              << ". Ignoring." << std::endl;
5240                                 } else
5241                                         os << "encoding " << '"' << enc->name() << '"' << "\n";
5242                         }
5243                         end_inset(os);
5244                         need_commentbib = false;
5245                         continue;
5246                 }
5247
5248                 if (t.cs() == "bibbysection") {
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                         os << "btprint " << '"' << "bibbysection" << '"' << "\n";
5262                         string bibfiles;
5263                         for (auto const & bf : preamble.biblatex_bibliographies) {
5264                                 if (!bibfiles.empty())
5265                                         bibfiles += ",";
5266                                 bibfiles += normalize_filename(bf);
5267                         }
5268                         if (!bibfiles.empty())
5269                                 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
5270                         os << "options " << '"' << BibOpts << '"' << "\n";
5271                         if (!bbloptions.empty())
5272                                 os << "biblatexopts " << '"' << bbloptions << '"' << "\n";
5273                         end_inset(os);
5274                         need_commentbib = false;
5275                         continue;
5276                 }
5277
5278                 if (t.cs() == "parbox") {
5279                         // Test whether this is an outer box of a shaded box
5280                         p.pushPosition();
5281                         // swallow arguments
5282                         while (p.hasOpt()) {
5283                                 p.getArg('[', ']');
5284                                 p.skip_spaces(true);
5285                         }
5286                         p.getArg('{', '}');
5287                         p.skip_spaces(true);
5288                         // eat the '{'
5289                         if (p.next_token().cat() == catBegin)
5290                                 p.get_token();
5291                         p.skip_spaces(true);
5292                         Token to = p.get_token();
5293                         bool shaded = false;
5294                         if (to.asInput() == "\\begin") {
5295                                 p.skip_spaces(true);
5296                                 if (p.getArg('{', '}') == "shaded")
5297                                         shaded = true;
5298                         }
5299                         p.popPosition();
5300                         if (shaded) {
5301                                 parse_outer_box(p, os, FLAG_ITEM, outer,
5302                                                 context, "parbox", "shaded");
5303                         } else
5304                                 parse_box(p, os, 0, FLAG_ITEM, outer, context,
5305                                           "", "", t.cs(), "", "");
5306                         continue;
5307                 }
5308
5309                 if (t.cs() == "fbox" || t.cs() == "mbox" ||
5310                     t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
5311                     t.cs() == "shadowbox" || t.cs() == "doublebox") {
5312                         parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
5313                         continue;
5314                 }
5315
5316                 if (t.cs() == "fcolorbox" || t.cs() == "colorbox") {
5317                         string backgroundcolor;
5318                         preamble.registerAutomaticallyLoadedPackage("xcolor");
5319                         if (t.cs() == "fcolorbox") {
5320                                 string const framecolor = p.getArg('{', '}');
5321                                 backgroundcolor = p.getArg('{', '}');
5322                                 parse_box(p, os, 0, 0, outer, context, "", "", "", framecolor, backgroundcolor);
5323                         } else {
5324                                 backgroundcolor = p.getArg('{', '}');
5325                                 parse_box(p, os, 0, 0, outer, context, "", "", "", "", backgroundcolor);
5326                         }
5327                         continue;
5328                 }
5329
5330                 // FIXME: due to the compiler limit of "if" nestings
5331                 // the code for the alignment was put here
5332                 // put them in their own if if this is fixed
5333                 if (t.cs() == "fboxrule" || t.cs() == "fboxsep"
5334                     || t.cs() == "shadowsize"
5335                     || t.cs() == "raggedleft" || t.cs() == "centering"
5336                     || t.cs() == "raggedright") {
5337                         if (t.cs() == "fboxrule")
5338                                 fboxrule = "";
5339                         if (t.cs() == "fboxsep")
5340                                 fboxsep = "";
5341                         if (t.cs() == "shadowsize")
5342                                 shadow_size = "";
5343                         if (t.cs() != "raggedleft" && t.cs() != "centering"
5344                          && t.cs() != "raggedright") {
5345                                 p.skip_spaces(true);
5346                                 while (p.good() && p.next_token().cat() != catSpace
5347                                        && p.next_token().cat() != catNewline
5348                                        && p.next_token().cat() != catEscape) {
5349                                         if (t.cs() == "fboxrule")
5350                                                 fboxrule = fboxrule + p.get_token().asInput();
5351                                         if (t.cs() == "fboxsep")
5352                                                 fboxsep = fboxsep + p.get_token().asInput();
5353                                         if (t.cs() == "shadowsize")
5354                                                 shadow_size = shadow_size + p.get_token().asInput();
5355                                 }
5356                         } else {
5357                                 output_ert_inset(os, t.asInput(), context);
5358                         }
5359                         continue;
5360                 }
5361
5362                 //\framebox() is part of the picture environment and different from \framebox{}
5363                 //\framebox{} will be parsed by parse_outer_box
5364                 if (t.cs() == "framebox") {
5365                         if (p.next_token().character() == '(') {
5366                                 //the syntax is: \framebox(x,y)[position]{content}
5367                                 string arg = t.asInput();
5368                                 arg += p.getFullParentheseArg();
5369                                 arg += p.getFullOpt();
5370                                 eat_whitespace(p, os, context, false);
5371                                 output_ert_inset(os, arg + '{', context);
5372                                 parse_text(p, os, FLAG_ITEM, outer, context);
5373                                 output_ert_inset(os, "}", context);
5374                         } else {
5375                                 //the syntax is: \framebox[width][position]{content}
5376                                 string special = p.getFullOpt();
5377                                 special += p.getOpt();
5378                                 parse_outer_box(p, os, FLAG_ITEM, outer,
5379                                                     context, t.cs(), special);
5380                         }
5381                         continue;
5382                 }
5383
5384                 //\makebox() is part of the picture environment and different from \makebox{}
5385                 //\makebox{} will be parsed by parse_box
5386                 if (t.cs() == "makebox") {
5387                         if (p.next_token().character() == '(') {
5388                                 //the syntax is: \makebox(x,y)[position]{content}
5389                                 string arg = t.asInput();
5390                                 arg += p.getFullParentheseArg();
5391                                 arg += p.getFullOpt();
5392                                 eat_whitespace(p, os, context, false);
5393                                 output_ert_inset(os, arg + '{', context);
5394                                 parse_text(p, os, FLAG_ITEM, outer, context);
5395                                 output_ert_inset(os, "}", context);
5396                         } else
5397                                 //the syntax is: \makebox[width][position]{content}
5398                                 parse_box(p, os, 0, FLAG_ITEM, outer, context,
5399                                           "", "", t.cs(), "", "");
5400                         continue;
5401                 }
5402
5403                 if (t.cs() == "smallskip" ||
5404                     t.cs() == "medskip" ||
5405                     t.cs() == "bigskip" ||
5406                     t.cs() == "vfill") {
5407                         context.check_layout(os);
5408                         begin_inset(os, "VSpace ");
5409                         os << t.cs();
5410                         end_inset(os);
5411                         skip_spaces_braces(p);
5412                         continue;
5413                 }
5414
5415                 if ((where = is_known(t.cs(), known_spaces))) {
5416                         context.check_layout(os);
5417                         begin_inset(os, "space ");
5418                         os << '\\' << known_coded_spaces[where - known_spaces]
5419                            << '\n';
5420                         end_inset(os);
5421                         // LaTeX swallows whitespace after all spaces except
5422                         // "\\,". We have to do that here, too, because LyX
5423                         // adds "{}" which would make the spaces significant.
5424                         if (t.cs() !=  ",")
5425                                 eat_whitespace(p, os, context, false);
5426                         // LyX adds "{}" after all spaces except "\\ " and
5427                         // "\\,", so we have to remove "{}".
5428                         // "\\,{}" is equivalent to "\\," in LaTeX, so we
5429                         // remove the braces after "\\,", too.
5430                         if (t.cs() != " ")
5431                                 skip_braces(p);
5432                         continue;
5433                 }
5434
5435                 if (t.cs() == "newpage" ||
5436                     (t.cs() == "pagebreak" && !p.hasOpt()) ||
5437                     t.cs() == "clearpage" ||
5438                     t.cs() == "cleardoublepage") {
5439                         context.check_layout(os);
5440                         begin_inset(os, "Newpage ");
5441                         os << t.cs();
5442                         end_inset(os);
5443                         skip_spaces_braces(p);
5444                         continue;
5445                 }
5446
5447                 if (t.cs() == "DeclareRobustCommand" ||
5448                          t.cs() == "DeclareRobustCommandx" ||
5449                          t.cs() == "newcommand" ||
5450                          t.cs() == "newcommandx" ||
5451                          t.cs() == "providecommand" ||
5452                          t.cs() == "providecommandx" ||
5453                          t.cs() == "renewcommand" ||
5454                          t.cs() == "renewcommandx") {
5455                         // DeclareRobustCommand, DeclareRobustCommandx,
5456                         // providecommand and providecommandx could be handled
5457                         // by parse_command(), but we need to call
5458                         // add_known_command() here.
5459                         string name = t.asInput();
5460                         if (p.next_token().asInput() == "*") {
5461                                 // Starred form. Eat '*'
5462                                 p.get_token();
5463                                 name += '*';
5464                         }
5465                         string const command = p.verbatim_item();
5466                         string const opt1 = p.getFullOpt();
5467                         string const opt2 = p.getFullOpt();
5468                         add_known_command(command, opt1, !opt2.empty());
5469                         string const ert = name + '{' + command + '}' +
5470                                            opt1 + opt2 +
5471                                            '{' + p.verbatim_item() + '}';
5472
5473                         if (t.cs() == "DeclareRobustCommand" ||
5474                             t.cs() == "DeclareRobustCommandx" ||
5475                             t.cs() == "providecommand" ||
5476                             t.cs() == "providecommandx" ||
5477                             name[name.length()-1] == '*')
5478                                 output_ert_inset(os, ert, context);
5479                         else {
5480                                 context.check_layout(os);
5481                                 begin_inset(os, "FormulaMacro");
5482                                 os << "\n" << ert;
5483                                 end_inset(os);
5484                         }
5485                         continue;
5486                 }
5487
5488                 if (t.cs() == "let" && p.next_token().asInput() != "*") {
5489                         // let could be handled by parse_command(),
5490                         // but we need to call add_known_command() here.
5491                         string ert = t.asInput();
5492                         string name;
5493                         p.skip_spaces();
5494                         if (p.next_token().cat() == catBegin) {
5495                                 name = p.verbatim_item();
5496                                 ert += '{' + name + '}';
5497                         } else {
5498                                 name = p.verbatim_item();
5499                                 ert += name;
5500                         }
5501                         string command;
5502                         p.skip_spaces();
5503                         if (p.next_token().cat() == catBegin) {
5504                                 command = p.verbatim_item();
5505                                 ert += '{' + command + '}';
5506                         } else {
5507                                 command = p.verbatim_item();
5508                                 ert += command;
5509                         }
5510                         // If command is known, make name known too, to parse
5511                         // its arguments correctly. For this reason we also
5512                         // have commands in syntax.default that are hardcoded.
5513                         CommandMap::iterator it = known_commands.find(command);
5514                         if (it != known_commands.end())
5515                                 known_commands[t.asInput()] = it->second;
5516                         output_ert_inset(os, ert, context);
5517                         continue;
5518                 }
5519
5520                 if (t.cs() == "hspace" || t.cs() == "vspace") {
5521                         if (starred)
5522                                 p.get_token();
5523                         string name = t.asInput();
5524                         string const length = p.verbatim_item();
5525                         string unit;
5526                         string valstring;
5527                         bool valid = splitLatexLength(length, valstring, unit);
5528                         bool known_hspace = false;
5529                         bool known_vspace = false;
5530                         bool known_unit = false;
5531                         double value = 0.0;
5532                         if (valid) {
5533                                 istringstream iss(valstring);
5534                                 iss >> value;
5535                                 if (value == 1.0) {
5536                                         if (t.cs()[0] == 'h') {
5537                                                 if (unit == "\\fill") {
5538                                                         if (!starred) {
5539                                                                 unit = "";
5540                                                                 name = "\\hfill";
5541                                                         }
5542                                                         known_hspace = true;
5543                                                 }
5544                                         } else {
5545                                                 if (unit == "\\smallskipamount") {
5546                                                         unit = "smallskip";
5547                                                         known_vspace = true;
5548                                                 } else if (unit == "\\medskipamount") {
5549                                                         unit = "medskip";
5550                                                         known_vspace = true;
5551                                                 } else if (unit == "\\bigskipamount") {
5552                                                         unit = "bigskip";
5553                                                         known_vspace = true;
5554                                                 } else if (unit == "\\fill") {
5555                                                         unit = "vfill";
5556                                                         known_vspace = true;
5557                                                 }
5558                                         }
5559                                 }
5560                                 if (!known_hspace && !known_vspace) {
5561                                         switch (unitFromString(unit)) {
5562                                         case Length::SP:
5563                                         case Length::PT:
5564                                         case Length::BP:
5565                                         case Length::DD:
5566                                         case Length::MM:
5567                                         case Length::PC:
5568                                         case Length::CC:
5569                                         case Length::CM:
5570                                         case Length::IN:
5571                                         case Length::EX:
5572                                         case Length::EM:
5573                                         case Length::MU:
5574                                                 known_unit = true;
5575                                                 break;
5576                                         default: {
5577                                                 //unitFromString(unit) fails for relative units like Length::PCW
5578                                                 // therefore handle them separately
5579                                                 if (unit == "\\paperwidth" || unit == "\\columnwidth"
5580                                                         || unit == "\\textwidth" || unit == "\\linewidth"
5581                                                         || unit == "\\textheight" || unit == "\\paperheight"
5582                                                         || unit == "\\baselineskip")
5583                                                         known_unit = true;
5584                                                 break;
5585                                                          }
5586                                         }
5587                                 }
5588                         }
5589
5590                         // check for glue lengths
5591                         bool is_gluelength = false;
5592                         string gluelength = length;
5593                         string::size_type i = length.find(" minus");
5594                         if (i == string::npos) {
5595                                 i = length.find(" plus");
5596                                 if (i != string::npos)
5597                                         is_gluelength = true;
5598                         } else
5599                                 is_gluelength = true;
5600                         // if yes transform "9xx minus 8yy plus 7zz"
5601                         // to "9xx-8yy+7zz"
5602                         if (is_gluelength) {
5603                                 i = gluelength.find(" minus");
5604                                 if (i != string::npos)
5605                                         gluelength.replace(i, 7, "-");
5606                                 i = gluelength.find(" plus");
5607                                 if (i != string::npos)
5608                                         gluelength.replace(i, 6, "+");
5609                         }
5610
5611                         if (t.cs()[0] == 'h' && (known_unit || known_hspace || is_gluelength)) {
5612                                 // Literal horizontal length or known variable
5613                                 context.check_layout(os);
5614                                 begin_inset(os, "space ");
5615                                 os << name;
5616                                 if (starred)
5617                                         os << '*';
5618                                 os << '{';
5619                                 if (known_hspace)
5620                                         os << unit;
5621                                 os << "}";
5622                                 if (known_unit && !known_hspace)
5623                                         os << "\n\\length " << translate_len(length);
5624                                 if (is_gluelength)
5625                                         os << "\n\\length " << gluelength;
5626                                 end_inset(os);
5627                         } else if (known_unit || known_vspace || is_gluelength) {
5628                                 // Literal vertical length or known variable
5629                                 context.check_layout(os);
5630                                 begin_inset(os, "VSpace ");
5631                                 if (known_vspace)
5632                                         os << unit;
5633                                 if (known_unit && !known_vspace)
5634                                         os << translate_len(length);
5635                                 if (is_gluelength)
5636                                         os << gluelength;
5637                                 if (starred)
5638                                         os << '*';
5639                                 end_inset(os);
5640                         } else {
5641                                 // LyX can't handle other length variables in Inset VSpace/space
5642                                 if (starred)
5643                                         name += '*';
5644                                 if (valid) {
5645                                         if (value == 1.0)
5646                                                 output_ert_inset(os, name + '{' + unit + '}', context);
5647                                         else if (value == -1.0)
5648                                                 output_ert_inset(os, name + "{-" + unit + '}', context);
5649                                         else
5650                                                 output_ert_inset(os, name + '{' + valstring + unit + '}', context);
5651                                 } else
5652                                         output_ert_inset(os, name + '{' + length + '}', context);
5653                         }
5654                         continue;
5655                 }
5656
5657                 // Before we look for the layout name alone below, we check the layouts including the LateXParam, which
5658                 // might be one or several options or a star.
5659                 // The single '=' is meant here.
5660                 if ((newinsetlayout = findInsetLayout(context.textclass, starredname, true, p.getCommandLatexParam()))) {
5661                         if (starred)
5662                                 p.get_token();
5663                         p.skip_spaces();
5664                         context.check_layout(os);
5665                         // store the latexparam here. This is eaten in parse_text_in_inset
5666                         context.latexparam = newinsetlayout->latexparam();
5667                         docstring name = newinsetlayout->name();
5668                         bool const caption = name.find(from_ascii("Caption:")) == 0;
5669                         if (caption) {
5670                                 // Already done for floating minted listings.
5671                                 if (minted_float.empty()) {
5672                                         begin_inset(os, "Caption ");
5673                                         os << to_utf8(name.substr(8)) << '\n';
5674                                 }
5675                         } else {
5676                                 // FIXME: what do we do if the prefix is not Flex: ?
5677                                 if (prefixIs(name, from_ascii("Flex:")))
5678                                         name.erase(0, 5);
5679                                 begin_inset(os, "Flex ");
5680                                 os << to_utf8(name) << '\n'
5681                                    << "status collapsed\n";
5682                         }
5683                         if (!minted_float.empty()) {
5684                                 parse_text_snippet(p, os, FLAG_ITEM, false, context);
5685                         } else if (newinsetlayout->isPassThru()) {
5686                                 // set catcodes to verbatim early, just in case.
5687                                 p.setCatcodes(VERBATIM_CATCODES);
5688                                 string delim = p.get_token().asInput();
5689                                 if (delim != "{")
5690                                         cerr << "Warning: bad delimiter for command " << t.asInput() << endl;
5691                                 //FIXME: handle error condition
5692                                 string const arg = p.verbatimStuff("}").second;
5693                                 Context newcontext(true, context.textclass);
5694                                 if (newinsetlayout->forcePlainLayout())
5695                                         newcontext.layout = &context.textclass.plainLayout();
5696                                 output_ert(os, arg, newcontext);
5697                         } else
5698                                 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
5699                         context.latexparam.clear();
5700                         if (caption)
5701                                 p.skip_spaces();
5702                         // Minted caption insets are not closed here because
5703                         // we collect everything into the caption.
5704                         if (minted_float.empty())
5705                                 end_inset(os);
5706                         continue;
5707                 }
5708
5709                 // The single '=' is meant here.
5710                 if ((newinsetlayout = findInsetLayout(context.textclass, starredname, true))) {
5711                         if (starred)
5712                                 p.get_token();
5713                         p.skip_spaces();
5714                         context.check_layout(os);
5715                         docstring name = newinsetlayout->name();
5716                         bool const caption = name.find(from_ascii("Caption:")) == 0;
5717                         if (caption) {
5718                                 // Already done for floating minted listings.
5719                                 if (minted_float.empty()) {
5720                                         begin_inset(os, "Caption ");
5721                                         os << to_utf8(name.substr(8)) << '\n';
5722                                 }
5723                         } else {
5724                                 // FIXME: what do we do if the prefix is not Flex: ?
5725                                 if (prefixIs(name, from_ascii("Flex:")))
5726                                         name.erase(0, 5);
5727                                 begin_inset(os, "Flex ");
5728                                 os << to_utf8(name) << '\n'
5729                                    << "status collapsed\n";
5730                         }
5731                         if (!minted_float.empty()) {
5732                                 parse_text_snippet(p, os, FLAG_ITEM, false, context);
5733                         } else if (newinsetlayout->isPassThru()) {
5734                                 // set catcodes to verbatim early, just in case.
5735                                 p.setCatcodes(VERBATIM_CATCODES);
5736                                 string delim = p.get_token().asInput();
5737                                 if (delim != "{")
5738                                         cerr << "Warning: bad delimiter for command " << t.asInput() << endl;
5739                                 //FIXME: handle error condition
5740                                 string const arg = p.verbatimStuff("}").second;
5741                                 Context newcontext(true, context.textclass);
5742                                 if (newinsetlayout->forcePlainLayout())
5743                                         newcontext.layout = &context.textclass.plainLayout();
5744                                 output_ert(os, arg, newcontext);
5745                         } else
5746                                 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
5747                         if (caption)
5748                                 p.skip_spaces();
5749                         // Minted caption insets are not closed here because
5750                         // we collect everything into the caption.
5751                         if (minted_float.empty())
5752                                 end_inset(os);
5753                         continue;
5754                 }
5755
5756                 if (t.cs() == "includepdf") {
5757                         p.skip_spaces();
5758                         string const arg = p.getArg('[', ']');
5759                         map<string, string> opts;
5760                         vector<string> keys;
5761                         split_map(arg, opts, keys);
5762                         string name = normalize_filename(p.verbatim_item());
5763                         string const path = getMasterFilePath(true);
5764                         // We want to preserve relative / absolute filenames,
5765                         // therefore path is only used for testing
5766                         if (!makeAbsPath(name, path).exists()) {
5767                                 // The file extension is probably missing.
5768                                 // Now try to find it out.
5769                                 char const * const pdfpages_format[] = {"pdf", 0};
5770                                 string const pdftex_name =
5771                                         find_file(name, path, pdfpages_format);
5772                                 if (!pdftex_name.empty()) {
5773                                         name = pdftex_name;
5774                                         pdflatex = true;
5775                                 }
5776                         }
5777                         FileName const absname = makeAbsPath(name, path);
5778                         if (absname.exists())
5779                         {
5780                                 fix_child_filename(name);
5781                                 copy_file(absname, name);
5782                         } else
5783                                 cerr << "Warning: Could not find file '"
5784                                      << name << "'." << endl;
5785                         // write output
5786                         context.check_layout(os);
5787                         begin_inset(os, "External\n\ttemplate ");
5788                         os << "PDFPages\n\tfilename "
5789                            << name << "\n";
5790                         // parse the options
5791                         if (opts.find("pages") != opts.end())
5792                                 os << "\textra LaTeX \"pages="
5793                                    << opts["pages"] << "\"\n";
5794                         if (opts.find("angle") != opts.end())
5795                                 os << "\trotateAngle "
5796                                    << opts["angle"] << '\n';
5797                         if (opts.find("origin") != opts.end()) {
5798                                 ostringstream ss;
5799                                 string const opt = opts["origin"];
5800                                 if (opt == "tl") ss << "topleft";
5801                                 if (opt == "bl") ss << "bottomleft";
5802                                 if (opt == "Bl") ss << "baselineleft";
5803                                 if (opt == "c") ss << "center";
5804                                 if (opt == "tc") ss << "topcenter";
5805                                 if (opt == "bc") ss << "bottomcenter";
5806                                 if (opt == "Bc") ss << "baselinecenter";
5807                                 if (opt == "tr") ss << "topright";
5808                                 if (opt == "br") ss << "bottomright";
5809                                 if (opt == "Br") ss << "baselineright";
5810                                 if (!ss.str().empty())
5811                                         os << "\trotateOrigin " << ss.str() << '\n';
5812                                 else
5813                                         cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
5814                         }
5815                         if (opts.find("width") != opts.end())
5816                                 os << "\twidth "
5817                                    << translate_len(opts["width"]) << '\n';
5818                         if (opts.find("height") != opts.end())
5819                                 os << "\theight "
5820                                    << translate_len(opts["height"]) << '\n';
5821                         if (opts.find("keepaspectratio") != opts.end())
5822                                 os << "\tkeepAspectRatio\n";
5823                         end_inset(os);
5824                         context.check_layout(os);
5825                         registerExternalTemplatePackages("PDFPages");
5826                         continue;
5827                 }
5828
5829                 if (t.cs() == "loadgame") {
5830                         p.skip_spaces();
5831                         string name = normalize_filename(p.verbatim_item());
5832                         string const path = getMasterFilePath(true);
5833                         // We want to preserve relative / absolute filenames,
5834                         // therefore path is only used for testing
5835                         if (!makeAbsPath(name, path).exists()) {
5836                                 // The file extension is probably missing.
5837                                 // Now try to find it out.
5838                                 char const * const lyxskak_format[] = {"fen", 0};
5839                                 string const lyxskak_name =
5840                                         find_file(name, path, lyxskak_format);
5841                                 if (!lyxskak_name.empty())
5842                                         name = lyxskak_name;
5843                         }
5844                         FileName const absname = makeAbsPath(name, path);
5845                         if (absname.exists())
5846                         {
5847                                 fix_child_filename(name);
5848                                 copy_file(absname, name);
5849                         } else
5850                                 cerr << "Warning: Could not find file '"
5851                                      << name << "'." << endl;
5852                         context.check_layout(os);
5853                         begin_inset(os, "External\n\ttemplate ");
5854                         os << "ChessDiagram\n\tfilename "
5855                            << name << "\n";
5856                         end_inset(os);
5857                         context.check_layout(os);
5858                         // after a \loadgame follows a \showboard
5859                         if (p.get_token().asInput() == "showboard")
5860                                 p.get_token();
5861                         registerExternalTemplatePackages("ChessDiagram");
5862                         continue;
5863                 }
5864
5865                 // try to see whether the string is in unicodesymbols
5866                 // Only use text mode commands, since we are in text mode here,
5867                 // and math commands may be invalid (bug 6797)
5868                 string name = t.asInput();
5869                 // handle the dingbats, cyrillic and greek
5870                 if (name == "\\textcyr")
5871                         name = "\\textcyrillic";
5872                 if (name == "\\ding" || name == "\\textcyrillic" ||
5873                     (name == "\\textgreek" && !preamble.usePolyglossia()))
5874                         name = name + '{' + p.getArg('{', '}') + '}';
5875                 // handle the ifsym characters
5876                 else if (name == "\\textifsymbol") {
5877                         string const optif = p.getFullOpt();
5878                         string const argif = p.getArg('{', '}');
5879                         name = name + optif + '{' + argif + '}';
5880                 }
5881                 // handle the \ascii characters
5882                 // the case of \ascii within braces, as LyX outputs it, is already
5883                 // handled for t.cat() == catBegin
5884                 else if (name == "\\ascii") {
5885                         // the code is "\asci\xxx"
5886                         name = "{" + name + p.get_token().asInput() + "}";
5887                         skip_braces(p);
5888                 }
5889                 // handle some TIPA special characters
5890                 else if (preamble.isPackageUsed("tipa")) {
5891                         if (name == "\\s") {
5892                                 // fromLaTeXCommand() does not yet
5893                                 // recognize tipa short cuts
5894                                 name = "\\textsyllabic";
5895                         } else if (name == "\\=" &&
5896                                    p.next_token().asInput() == "*") {
5897                                 // fromLaTeXCommand() does not yet
5898                                 // recognize tipa short cuts
5899                                 p.get_token();
5900                                 name = "\\textsubbar";
5901                         } else if (name == "\\textdoublevertline") {
5902                                 // FIXME: This is not correct,
5903                                 // \textvertline is higher than \textbardbl
5904                                 name = "\\textbardbl";
5905                                 skip_braces(p);
5906                         } else if (name == "\\!" ) {
5907                                 if (p.next_token().asInput() == "b") {
5908                                         p.get_token();  // eat 'b'
5909                                         name = "\\texthtb";
5910                                         skip_braces(p);
5911                                 } else if (p.next_token().asInput() == "d") {
5912                                         p.get_token();
5913                                         name = "\\texthtd";
5914                                         skip_braces(p);
5915                                 } else if (p.next_token().asInput() == "g") {
5916                                         p.get_token();
5917                                         name = "\\texthtg";
5918                                         skip_braces(p);
5919                                 } else if (p.next_token().asInput() == "G") {
5920                                         p.get_token();
5921                                         name = "\\texthtscg";
5922                                         skip_braces(p);
5923                                 } else if (p.next_token().asInput() == "j") {
5924                                         p.get_token();
5925                                         name = "\\texthtbardotlessj";
5926                                         skip_braces(p);
5927                                 } else if (p.next_token().asInput() == "o") {
5928                                         p.get_token();
5929                                         name = "\\textbullseye";
5930                                         skip_braces(p);
5931                                 }
5932                         } else if (name == "\\*" ) {
5933                                 if (p.next_token().asInput() == "k") {
5934                                         p.get_token();
5935                                         name = "\\textturnk";
5936                                         skip_braces(p);
5937                                 } else if (p.next_token().asInput() == "r") {
5938                                         p.get_token();  // eat 'b'
5939                                         name = "\\textturnr";
5940                                         skip_braces(p);
5941                                 } else if (p.next_token().asInput() == "t") {
5942                                         p.get_token();
5943                                         name = "\\textturnt";
5944                                         skip_braces(p);
5945                                 } else if (p.next_token().asInput() == "w") {
5946                                         p.get_token();
5947                                         name = "\\textturnw";
5948                                         skip_braces(p);
5949                                 }
5950                         }
5951                 }
5952                 if ((name.size() == 2 &&
5953                      contains("\"'.=^`bcdHkrtuv~", name[1]) &&
5954                      p.next_token().asInput() != "*") ||
5955                     is_known(name.substr(1), known_tipa_marks)) {
5956                         // name is a command that corresponds to a
5957                         // combining character in unicodesymbols.
5958                         // Append the argument, fromLaTeXCommand()
5959                         // will either convert it to a single
5960                         // character or a combining sequence.
5961                         name += '{' + p.verbatim_item() + '}';
5962                 }
5963                 // now get the character from unicodesymbols
5964                 bool termination;
5965                 docstring rem;
5966                 set<string> req;
5967                 docstring s = normalize_c(encodings.fromLaTeXCommand(from_utf8(name),
5968                                 Encodings::TEXT_CMD, termination, rem, &req));
5969                 if (!s.empty()) {
5970                         context.check_layout(os);
5971                         os << to_utf8(s);
5972                         if (!rem.empty())
5973                                 output_ert_inset(os, to_utf8(rem), context);
5974                         if (termination)
5975                                 skip_spaces_braces(p);
5976                         for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
5977                                 preamble.registerAutomaticallyLoadedPackage(*it);
5978                 }
5979                 //cerr << "#: " << t << " mode: " << mode << endl;
5980                 // heuristic: read up to next non-nested space
5981                 /*
5982                 string s = t.asInput();
5983                 string z = p.verbatim_item();
5984                 while (p.good() && z != " " && !z.empty()) {
5985                         //cerr << "read: " << z << endl;
5986                         s += z;
5987                         z = p.verbatim_item();
5988                 }
5989                 cerr << "found ERT: " << s << endl;
5990                 output_ert_inset(os, s + ' ', context);
5991                 */
5992                 else {
5993                         if (t.asInput() == name &&
5994                             p.next_token().asInput() == "*") {
5995                                 // Starred commands like \vspace*{}
5996                                 p.get_token();  // Eat '*'
5997                                 name += '*';
5998                         }
5999                         if (!parse_command(name, p, os, outer, context))
6000                                 output_ert_inset(os, name, context);
6001                 }
6002         }
6003 }
6004
6005
6006 string guessLanguage(Parser & p, string const & lang)
6007 {
6008         typedef std::map<std::string, size_t> LangMap;
6009         // map from language names to number of characters
6010         LangMap used;
6011         used[lang] = 0;
6012         for (char const * const * i = supported_CJK_languages; *i; i++)
6013                 used[string(*i)] = 0;
6014
6015         while (p.good()) {
6016                 Token const t = p.get_token();
6017                 // comments are not counted for any language
6018                 if (t.cat() == catComment)
6019                         continue;
6020                 // commands are not counted as well, but we need to detect
6021                 // \begin{CJK} and switch encoding if needed
6022                 if (t.cat() == catEscape) {
6023                         if (t.cs() == "inputencoding") {
6024                                 string const enc = subst(p.verbatim_item(), "\n", " ");
6025                                 p.setEncoding(enc, Encoding::inputenc);
6026                                 continue;
6027                         }
6028                         if (t.cs() != "begin")
6029                                 continue;
6030                 } else {
6031                         // Non-CJK content is counted for lang.
6032                         // We do not care about the real language here:
6033                         // If we have more non-CJK contents than CJK contents,
6034                         // we simply use the language that was specified as
6035                         // babel main language.
6036                         used[lang] += t.asInput().length();
6037                         continue;
6038                 }
6039                 // Now we are starting an environment
6040                 p.pushPosition();
6041                 string const name = p.getArg('{', '}');
6042                 if (name != "CJK") {
6043                         p.popPosition();
6044                         continue;
6045                 }
6046                 // It is a CJK environment
6047                 p.popPosition();
6048                 /* name = */ p.getArg('{', '}');
6049                 string const encoding = p.getArg('{', '}');
6050                 /* mapping = */ p.getArg('{', '}');
6051                 string const encoding_old = p.getEncoding();
6052                 char const * const * const where =
6053                         is_known(encoding, supported_CJK_encodings);
6054                 if (where)
6055                         p.setEncoding(encoding, Encoding::CJK);
6056                 else
6057                         p.setEncoding("UTF-8");
6058                 string const text = p.ertEnvironment("CJK");
6059                 p.setEncoding(encoding_old);
6060                 p.skip_spaces();
6061                 if (!where) {
6062                         // ignore contents in unknown CJK encoding
6063                         continue;
6064                 }
6065                 // the language of the text
6066                 string const cjk =
6067                         supported_CJK_languages[where - supported_CJK_encodings];
6068                 used[cjk] += text.length();
6069         }
6070         LangMap::const_iterator use = used.begin();
6071         for (LangMap::const_iterator it = used.begin(); it != used.end(); ++it) {
6072                 if (it->second > use->second)
6073                         use = it;
6074         }
6075         return use->first;
6076 }
6077
6078
6079 void check_comment_bib(ostream & os, Context & context)
6080 {
6081         if (!need_commentbib)
6082                 return;
6083         // We have a bibliography database, but no bibliography with biblatex
6084         // which is completely valid. Insert a bibtex inset in a note.
6085         context.check_layout(os);
6086         begin_inset(os, "Note Note\n");
6087         os << "status open\n";
6088         os << "\\begin_layout Plain Layout\n";
6089         begin_command_inset(os, "bibtex", "bibtex");
6090         string bibfiles;
6091         for (auto const & bf : preamble.biblatex_bibliographies) {
6092                 if (!bibfiles.empty())
6093                         bibfiles += ",";
6094                 bibfiles += normalize_filename(bf);
6095         }
6096         if (!bibfiles.empty())
6097                 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
6098         end_inset(os);// Bibtex
6099         os << "\\end_layout\n";
6100         end_inset(os);// Note
6101 }
6102
6103 // }])
6104
6105
6106 } // namespace lyx