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