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