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