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