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