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