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