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