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