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