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