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