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