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