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