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